<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ryan Klapper on Medium]]></title>
        <description><![CDATA[Stories by Ryan Klapper on Medium]]></description>
        <link>https://medium.com/@ryanklapper?source=rss-51fd0854fd0f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DTr8rxZZ7rhiW4MAxRmERg.png</url>
            <title>Stories by Ryan Klapper on Medium</title>
            <link>https://medium.com/@ryanklapper?source=rss-51fd0854fd0f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 22:34:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ryanklapper/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Supercharging Your PDF Workflow with Claude by Anthropic]]></title>
            <link>https://medium.com/@ryanklapper/supercharging-your-pdf-workflow-with-claude-by-anthropic-b1061462f67d?source=rss-51fd0854fd0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1061462f67d</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[anthropic-claude]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ryan Klapper]]></dc:creator>
            <pubDate>Fri, 01 Nov 2024 17:27:02 GMT</pubDate>
            <atom:updated>2024-11-01T17:33:21.765Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Uepui0w8-Ro_Ajjz.png" /></figure><p>Claude now offers powerful PDF support, opening up exciting new possibilities for seamless document analysis and interaction. It combines not only the ability to grab the text itself, but implements the <a href="https://docs.anthropic.com/en/docs/build-with-claude/vision"><strong>vision</strong></a> components from Claude as well. There is no need to set up your own Retrieval-Augmented Generation (RAG) pipeline or worry about parsing documents manually — Claude’s API takes care of everything. Let’s explore how Claude can help you extract valuable insights from your PDFs with minimal setup.</p><h3>Key Features</h3><p>Claude’s PDF capabilities extend to any standard PDF, handling text, images, charts, and tables. Here are a few ways you might leverage Claude’s new feature:</p><ul><li><strong>Financial Analysis</strong>: Extract and analyze data from annual reports, understanding key metrics and visual charts with ease.</li><li><strong>Legal Document Summarization</strong>: Quickly pull out essential information and clauses from contracts.</li><li><strong>Multilingual Support</strong>: Get translation assistance for documents across different languages.</li><li><strong>Structured Data Conversion</strong>: Convert complex document data into structured formats for further analysis.</li></ul><h3>How PDF Support Works</h3><p>When you submit a request containing a PDF file, here’s how Claude processes it:</p><ol><li><strong>Content Extraction</strong>: The system parses the document and converts each page into an image.</li><li><strong>Text and Image Analysis</strong>: Text and images are processed together, allowing Claude to comprehend both written and visual content.</li></ol><p>This combined analysis of text and visual elements means you can ask Claude specific questions about charts, diagrams, and other non-text content within the PDF. You gain rich insights without the need for complex data extraction setups or manual text parsing.</p><h3>Built-in Feature Compatibility</h3><p>Claude’s PDF support works in harmony with other Anthropic features:</p><ul><li><strong>Prompt Caching</strong>: Improves performance for repeated queries on the same document.</li><li><strong>Batch Processing</strong>: Useful for high-volume document analysis.</li><li><strong>Tool Integration</strong>: Extract specific document data as inputs for other tools.</li></ul><h3>Use Cases</h3><p>Claude’s PDF support enables a range of applications across different fields. These are just some examples, but the possibilities are endless:</p><ul><li><strong>Summarization</strong>: Create concise summaries of lengthy research papers or reports.</li><li><strong>Data Extraction</strong>: Pull exact facts, figures, and trends from dense documents with ease.</li><li><strong>Research and Academic Analysis</strong>: Dive into multiple academic papers or industry reports to identify trends and insights.</li><li><strong>Legal Review</strong>: Extract key legal clauses and potential risks from contracts.</li><li><strong>Financial Insights</strong>: Analyze performance data from corporate reports to draw financial conclusions.</li></ul><h3>Example Code Implementation</h3><p>Here’s how to get started with Claude’s PDF capabilities using Anthropic’s API:</p><pre>import anthropic<br>import base64<br>import os<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br># Read local PDF file<br>with open(&quot;RYAN_KLAPPER_RESUME.pdf&quot;, &quot;rb&quot;) as f:<br>    pdf_data = base64.b64encode(f.read()).decode(&quot;utf-8&quot;)<br><br># Send API request<br>client = anthropic.Anthropic(api_key=os.getenv(&quot;ANTROPIC_API_KEY&quot;))<br>message = client.beta.messages.create(<br>    model=&quot;claude-3-5-sonnet-20241022&quot;,<br>    betas=[&quot;pdfs-2024-09-25&quot;],<br>    max_tokens=1024,<br>    messages=[<br>        {<br>            &quot;role&quot;: &quot;user&quot;, <br>            &quot;content&quot;: [<br>                {<br>                    &quot;type&quot;: &quot;document&quot;,<br>                    &quot;source&quot;: {<br>                        &quot;type&quot;: &quot;base64&quot;,<br>                        &quot;media_type&quot;: &quot;application/pdf&quot;,<br>                        &quot;data&quot;: pdf_data<br>                    }<br>                },<br>                {<br>                    &quot;type&quot;: &quot;text&quot;,<br>                    &quot;text&quot;: &quot;What certifications does this resume have?&quot;<br>                }<br>            ]<br>        }<br>    ],<br>)<br><br>final_message = message.content[0].text</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*YMTkPdXfjxUcFuss3YheZA.png" /><figcaption>Document that the API call is focusing on</figcaption></figure><p>Here is the response from Claude:</p><p><strong>“According to the resume, there are two certifications:\n\n1. SnowPro Core Certification from Snowflake (obtained in January 2023)\n2. AWS Certified Cloud Practitioner from Amazon (obtained in October 2023)”</strong></p><p>As shown, Claude efficiently parses the document and delivers clear, concise information.</p><h3>Limitations to Keep in Mind</h3><p>While Claude’s PDF support is powerful, a few limitations apply:</p><ul><li><strong>Modifications</strong>: Claude cannot alter or create new PDFs.</li><li><strong>File Size</strong>: Very large PDFs may need to be broken into smaller sections.</li><li><strong>Handwritten Text</strong>: Complex handwritten or stylized fonts may present challenges for accurate extraction.</li></ul><h3>Conclusion</h3><p>Claude’s PDF support is a major advancement in AI-driven document analysis. By eliminating the need for a custom RAG pipeline, Claude offers an intuitive, end-to-end solution that transforms your workflow. Whether you’re a business analyst, researcher, or just looking to streamline document processing, Claude’s PDF support makes it easier than ever to unlock insights from your files.</p><p>For a deep dive into implementation, check out Anthropic’s <a href="https://docs.anthropic.com/en/docs/build-with-claude/pdf-support">official documentation</a>.</p><h3>Get in Touch</h3><p>Linkedin — <a href="https://www.linkedin.com/in/ryan-k-ba8274122/">https://www.linkedin.com/in/ryan-k-ba8274122/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1061462f67d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turning Words into SQL: Leveraging Streamlit and OpenAI’s Structured Output for Accurate Query…]]></title>
            <link>https://medium.com/@ryanklapper/turning-words-into-sql-leveraging-streamlit-and-openais-structured-output-for-accurate-query-df5c3ab8fce6?source=rss-51fd0854fd0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/df5c3ab8fce6</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[pydantic]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[streamlit]]></category>
            <dc:creator><![CDATA[Ryan Klapper]]></dc:creator>
            <pubDate>Fri, 09 Aug 2024 19:08:02 GMT</pubDate>
            <atom:updated>2024-08-09T19:08:02.843Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Turning Words into SQL: Leveraging Streamlit and OpenAI’s Structured Output for Accurate Query Generation</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*a3GaFS6LVd0ymyNNC0nzuA.png" /></figure><h3><strong>Understanding OpenAI’s Structured Output</strong></h3><p>The launch of OpenAI’s <a href="https://openai.com/index/introducing-structured-outputs-in-the-api/"><strong>Structured Output</strong></a> marks a significant step forward in AI-assisted development. Unlike conventional language models that return text as free-form responses, the Structured Output feature generates responses in a predictable and structured format, which can be validated and parsed using libraries like <a href="https://docs.pydantic.dev/latest/"><strong>Pydantic</strong></a>. This ensures that the data the model returns aligns with specific schemas, reducing the need for post-processing and increasing reliability when integrating AI into applications.</p><h3>Why Pydantic?</h3><p>Pydantic is a data validation library that enforces type-checking and data integrity. By using Pydantic models, developers can define schemas that represent expected data structures. In this application, Pydantic ensures that the data received from OpenAI’s Structured Output conforms to predefined types and constraints, which is crucial for generating SQL queries that are syntactically and semantically correct.</p><h3>Building the SQL Query Generator in Streamlit</h3><p>Let’s dive into the code that brings all these components together.</p><h3>Setting Up the Models</h3><p>To start, we define several enums and Pydantic models to represent the elements of an SQL query. These include the table name, column names, operators (e.g., =, &gt;, &lt;), and other SQL components like aggregate functions and ranking types. Here&#39;s the code snippet for the Pydantic models:</p><pre>from enum import Enum<br>from pydantic import BaseModel<br><br>class Table(str, Enum):<br>    support_engineer_metrics = &quot;ASSISTANT_METRICS&quot;<br><br>class Column(str, Enum):<br>    id = &quot;USER_ID&quot;<br>    assistant_name = &quot;ASSISTANT_NAME&quot;<br>    assistant_id = &quot;ASSISTANT_ID&quot;<br>    question = &quot;QUESTION&quot;<br>    answer = &quot;ANSWER&quot;<br>    feedback = &quot;FEEDBACK&quot;<br>    date = &quot;DATE&quot;<br><br>class Operator(str, Enum):<br>    eq = &quot;=&quot;<br>    gt = &quot;&gt;&quot;<br>    lt = &quot;&lt;&quot;<br>    le = &quot;&lt;=&quot;<br>    ge = &quot;&gt;=&quot;<br>    ne = &quot;!=&quot;<br><br>class OrderBy(str, Enum):<br>    asc = &quot;asc&quot;<br>    desc = &quot;desc&quot;<br><br>class Aggregate(str, Enum):<br>    count = &quot;count&quot;<br>    sum = &quot;sum&quot;<br>    avg = &quot;avg&quot;<br>    min = &quot;min&quot;<br>    max = &quot;max&quot;<br><br>class RankType(str, Enum):<br>    rank = &quot;rank&quot;<br>    dense_rank = &quot;dense_rank&quot;<br><br>class Condition(BaseModel):<br>    column: str<br>    operator: Operator<br>    value: Union[str, int]<br><br>class Query(BaseModel):<br>    table_name: Table<br>    columns: list[Column]<br>    conditions: list[Condition]<br>    aggregate: Aggregate<br>    rank_type: RankType<br>    order_by: OrderBy</pre><p>These models represent the building blocks of an SQL query, ensuring that only valid data is used to construct the query.</p><h3>Generating the SQL Query</h3><p>The heart of the application is the generate_query function. This function sends a request to OpenAI&#39;s API with the user&#39;s input, expecting a structured output that conforms to the Query model. The structured response is then parsed to extract the necessary details for generating an SQL query. Here&#39;s the code snippet:</p><pre>import openai<br>from openai import OpenAI<br><br>client = OpenAI()<br><br>def generate_query(user_input):<br>    completion = client.beta.chat.completions.parse(<br>        model=&quot;gpt-4o-2024-08-06&quot;,<br>        messages=[<br>            {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful assistant that can help generate SQL queries based on a user request.&quot;},<br>            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_input},<br>        ],<br>        tools=[openai.pydantic_function_tool(Query)],<br>    )<br>    <br>    parsed_args = completion.choices[0].message.tool_calls[0].function.parsed_arguments<br>    table_name = parsed_args.table_name.value<br>    column_names = [column.value for column in parsed_args.columns]<br>    operators_and_conditions = [[condition.column, condition.operator.value, condition.value] for condition in parsed_args.conditions]<br>    aggregate_function = parsed_args.aggregate.value<br>    order_by = parsed_args.order_by.value<br>    rank_type = parsed_args.rank_type.value<br>    <br>    sql_completion = client.chat.completions.create(<br>        model=&#39;gpt-4o-2024-08-06&#39;,<br>        messages=[{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: query_gen_prompt}]<br>    )<br>    <br>    return sql_completion.choices[0].message.content</pre><h3>Integrating with Streamlit</h3><p><a href="https://streamlit.io/"><strong>Streamlit</strong></a> is a powerful tool for building interactive applications quickly. In this example, we use Streamlit to create a simple UI that allows users to input a natural language query, which is then processed to generate the corresponding SQL.</p><pre>import streamlit as st<br><br>st.title(&#39;Query Generator App&#39;)<br>user_query = st.text_area(&quot;Enter your query:&quot;, &quot;Can you rank the top users by the number of questions they have answered in July 2024?&quot;)<br><br>if st.button(&#39;Generate Query&#39;):<br>    if user_query:<br>        with st.spinner(&#39;Generating query...&#39;):<br>            generated_sql = generate_query(user_query)<br>            st.subheader(&#39;Generated SQL Query:&#39;)<br>            st.code(generated_sql, language=&#39;sql&#39;)<br>    else:<br>        st.warning(&#39;Please enter a query.&#39;)</pre><p>This interface allows users to easily interact with the AI model, providing instant SQL query generation based on natural language input.</p><h3>Benefits of This Approach</h3><ol><li><strong>Efficiency</strong>: The integration of OpenAI’s Structured Output with Pydantic ensures that queries are generated quickly and correctly, without the need for manual input validation or correction.</li><li><strong>Accuracy</strong>: By defining a strict schema using Pydantic, we ensure that the generated queries conform to expected formats, reducing the likelihood of SQL syntax errors.</li><li><strong>Scalability</strong>: This method can be extended to support more complex SQL operations, additional databases, and even custom business logic, making it highly adaptable to various use cases.</li><li><strong>Ease of Use</strong>: The Streamlit interface makes it accessible to users with limited SQL knowledge, allowing them to generate queries with natural language, thus lowering the barrier to entry for complex data analysis.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*02eumkTTgvwTlvKye1Lv-w.png" /><figcaption>The date of the question being asked was August 9th</figcaption></figure><h3>Conclusion</h3><p>By leveraging OpenAI’s Structured Output, Pydantic, and Streamlit, we can build powerful tools that simplify SQL query generation, making it more accessible and less error-prone. This approach not only saves time but also enhances the accuracy and reliability of SQL queries. Whether you’re a data analyst, a developer, or a business user, this tool can help streamline your workflow and improve your productivity.</p><h3>Get in Touch / Code Repo</h3><p>Linkedin — <a href="https://www.linkedin.com/in/ryan-k-ba8274122/">https://www.linkedin.com/in/ryan-k-ba8274122/</a></p><p>Github Repository — <a href="https://github.com/klapp101/openai_structured_output">https://github.com/klapp101/openai_structured_output</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df5c3ab8fce6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The AI Financial Analyst Advantage: How GPT-4o is Revolutionizing Investment Strategies]]></title>
            <link>https://medium.com/@ryanklapper/the-ai-financial-analyst-advantage-how-gpt-4o-is-revolutionizing-investment-strategies-02f2454dcc2b?source=rss-51fd0854fd0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/02f2454dcc2b</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Ryan Klapper]]></dc:creator>
            <pubDate>Wed, 15 May 2024 15:47:07 GMT</pubDate>
            <atom:updated>2024-05-15T15:47:07.959Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction:</h3><p>In today’s digital age, we are constantly bombarded with financial data and stock analysis from various social media platforms like Twitter, Reddit, and TikTok. Often, the intricate financial analysis performed by seasoned day traders can seem almost alien to the average investor. This inspired me to leverage AI to create a tool that could simplify this process.</p><p>Imagine scrolling through your favorite social media feed and coming across a stock chart that catches your eye. Instead of trying to decipher the complex patterns and financial jargon, what if you could take a screenshot of that chart and let AI do the heavy lifting for you? My project aims to do just that, by integrating OpenAI’s latest model, GPT-4o, with a Flask web application.</p><h3>Project Overview</h3><p>Objective: The primary goal of this project is to build an application that can:</p><ol><li>Analyze Stock Charts: Take a screenshot of a stock chart and provide an in-depth financial analysis of the stock.</li><li>Financial Statistics Retrieval: Pull comprehensive financial statistics for the company associated with the stock chart.</li><li>Investment Analysis: Let <a href="https://openai.com/index/hello-gpt-4o/">GPT-4o</a> provide a holistic financial analysis of the company, highlighting key benchmarks to assess its investment potential.</li></ol><h3>How It Works</h3><h3>Stock Chart Analysis</h3><ul><li>Using advanced vision capabilities, the application can interpret and analyze the data presented in a stock chart screenshot.</li><li>The AI evaluates key indicators such as moving averages, volume, and trend lines to provide insights into the stock’s performance.</li></ul><h3>Financial Statistics Retrieval</h3><ul><li>By leveraging the <a href="https://pypi.org/project/yfinance/">yfinance</a> library, the application fetches real-time financial data for the company, including earnings reports, revenue, profit margins, and other crucial metrics.</li><li>This data is used to paint a comprehensive picture of the company’s financial health.</li></ul><h3>Overall Financial Analysis</h3><p>The application integrates with the <a href="https://platform.openai.com/docs/api-reference">OpenAI API</a> to generate a detailed financial analysis report. The report includes:</p><ul><li>The application integrates with the OpenAI API to generate a detailed financial analysis report</li><li>The report includes a breakdown of the company’s financial performance, comparisons to industry benchmarks, and an assessment of the company’s potential as an investment</li></ul><h3>Why This Matters</h3><p>The stock market can be intimidating for many, especially those without a background in finance. This tool aims to democratize financial analysis by making it accessible and understandable to a broader audience. By combining AI’s analytical power with real-time financial data, investors can make more informed decisions without needing to decode complex charts and reports themselves.</p><h3>Incorporating OpenAI’s GPT-4o</h3><p>On Monday, May 13th, OpenAI released their newest foundational model, GPT-4o. Dubbed the “omni” model, GPT-4o marks a significant leap towards more intuitive human-computer interaction. This cutting-edge technology accepts a wide range of inputs, including text, audio, images, and videos, and can generate diverse outputs such as text, audio, and images.</p><h4>Enhanced Capabilities:</h4><ul><li>Speed and Efficiency: GPT-4o can respond to audio prompts in as little as 232 milliseconds, with an average response time of 320 milliseconds, rivaling human conversation speeds.</li><li>Multilingual Proficiency: The model showcases notable improvements in non-English languages, making it highly versatile for global users.</li><li>Advanced Vision and Audio Comprehension: With enhanced capabilities in vision and audio comprehension, GPT-4o outperforms existing models, making it perfect for analyzing stock charts and financial data.</li><li>Cost and Efficiency: GPT-4o offers a 50% cost reduction and increased efficiency through the API, making advanced AI technology more accessible and affordable.</li></ul><p>By integrating GPT-4o into my project, I can leverage its powerful vision and language processing capabilities to provide faster, more accurate financial analysis. This enhances the user experience, making it easier for investors to understand stock performance and company fundamentals.</p><h3>Why Flask?</h3><p>For this project, I decided to use Flask. Flask is a lightweight WSGI web application framework in Python, designed with simplicity and flexibility in mind, making it an excellent choice for developing web applications. The project is organized into three main files: app.py, index.html, and style.css.</p><h3>Key Components</h3><h4>1. app.py</h4><p>app.py is the core of the project. It handles the application logic, including data fetching, chart generation, and the integration of GPT-4o for financial analysis.</p><p>Here are some key functions and their roles:</p><ul><li>Image Handling Functions:</li></ul><pre>def save_image(image_data, filename):<br>    with open(filename, &#39;wb&#39;) as f:<br>        f.write(base64.b64decode(image_data))<br><br>def encode_image(image_path):<br>    with open(image_path, &quot;rb&quot;) as image_file:<br>        return base64.b64encode(image_file.read()).decode(&quot;utf-8&quot;)</pre><ul><li>Plotting Stock Data</li></ul><pre>def plot_stock_data(hist, ticker, indicators):<br>    plt.switch_backend(&#39;Agg&#39;)<br>    plt.figure(figsize=(10, 5))<br>    <br>    for indicator in indicators:<br>        plt.plot(hist[indicator], label=indicator)<br>    <br>    plt.title(f&#39;{ticker} Stock Price&#39;)<br>    plt.xlabel(&#39;Date&#39;)<br>    plt.ylabel(&#39;Price&#39;)<br>    plt.legend()<br>    plt.grid()<br>    <br>    img = io.BytesIO()<br>    plt.savefig(img, format=&#39;png&#39;)<br>    img.seek(0)<br>    plot_url = base64.b64encode(img.getvalue()).decode()<br>    <br>    save_image(plot_url, f&#39;images/{ticker}_stock_plot.png&#39;)<br>    <br>    plt.close()<br>    return plot_url</pre><ul><li>Analyzing Stock Image with GPT-4o</li></ul><pre>def analyze_stock_image(image_path):<br>    base64_image = encode_image(image_path)<br>    response = client.chat.completions.create(<br>        model=&#39;gpt-4o&#39;,<br>        messages=[<br>            {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful financial stock analyst who provides insights on stock data.&quot;},<br>            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [<br>                {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;Can you describe the chart below?&quot;},<br>                {&quot;type&quot;: &quot;image_url&quot;, &quot;image_url&quot;: {<br>                &quot;url&quot;: f&quot;data:image/png;base64,{base64_image}&quot;}<br>                }<br>            ]}<br>        ],<br>        temperature=0.0,<br>    )<br><br>    return response.choices[0].message.content</pre><ul><li>In the provided code, I highlight how GPT-4o is used to analyze an image of the stock chart. We use Matplotlib to generate the chart, save it locally, and encode it as a base64 string to send to GPT-4o for analysis.</li><li>Generating Financial Analysis</li></ul><pre>def generate_financial_analysis(chart_summary, financials):<br>    messages = [<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful financial analyst. Provide a detailed financial analysis based on the given chart summary and financial data. Make sure to give insights on the company&#39;s financial performance and to output using markdown format.&quot;},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: f&quot;Chart Summary:\n{chart_summary}\n\nFinancial Data:\nInfo: {financials[&#39;info&#39;]}\nActions: {financials[&#39;actions&#39;]}\nDividends: {financials[&#39;dividends&#39;]}\nSplits: {financials[&#39;splits&#39;]}\nIncome Statement: {financials[&#39;income_stmt&#39;]}\nBalance Sheet: {financials[&#39;balance_sheet&#39;]}\nCash Flow: {financials[&#39;cashflow&#39;]}\nMajor Holders: {financials[&#39;major_holders&#39;]}\nInstitutional Holders: {financials[&#39;institutional_holders&#39;]}\nInsider Transactions: {financials[&#39;insider_transactions&#39;]}&quot;}<br>    ]<br>    <br>    response = client.chat.completions.create(<br>        model=&#39;gpt-4o&#39;,<br>        messages=messages,<br>        temperature=0.0,<br>    )<br>    <br>    return response.choices[0].message.content</pre><ul><li>The code combines the chart summary and additional financial metrics retrieved via yfinance to generate a comprehensive financial analysis using GPT-4o.</li><li>Flask Route</li></ul><pre>@app.route(&#39;/&#39;, methods=[&#39;GET&#39;, &#39;POST&#39;])<br>def index():<br>    ticker = None<br>    indicators = [&#39;Close&#39;]<br>    plot_url = None<br>    stock_data = {}<br>    analysis = None<br><br>    if request.method == &#39;POST&#39;:<br>        ticker = request.form[&#39;ticker&#39;]<br>        indicators = request.form.getlist(&#39;indicators&#39;) or [&#39;Close&#39;]<br>        stock_data = fetch_stock_data(ticker)<br>        plot_url = plot_stock_data(stock_data[&#39;hist&#39;], ticker, indicators)<br>        <br>        image_path = f&#39;images/{ticker}_stock_plot.png&#39;<br>        chart_summary = analyze_stock_image(image_path)<br>        raw_analysis = generate_financial_analysis(chart_summary, stock_data)<br>        analysis = markdown2.markdown(raw_analysis)<br><br>    return render_template(&#39;index.html&#39;, plot_url=plot_url, ticker=ticker, indicators=indicators, stock_data=stock_data, analysis=analysis)</pre><ul><li>The main route handles the form submission, processes the input, generates the chart, analyzes it using GPT-4o, and renders the results.</li></ul><h4>2. index.html</h4><ul><li>index.html provides the basic structure for our Flask application. It includes the form for user input and sections for displaying the generated stock chart and financial analysis.</li></ul><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Stock Trends&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;{{ url_for(&#39;static&#39;, filename=&#39;style.css&#39;) }}&quot;&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;Stock Trends&lt;/h1&gt;<br>    &lt;form method=&quot;POST&quot;&gt;<br>        &lt;input type=&quot;text&quot; name=&quot;ticker&quot; placeholder=&quot;Enter stock ticker&quot; value=&quot;{{ ticker }}&quot; required&gt;<br>        &lt;div&gt;<br>            &lt;label&gt;&lt;input type=&quot;checkbox&quot; name=&quot;indicators&quot; value=&quot;Close&quot; {% if &#39;Close&#39; in indicators %}checked{% endif %}&gt; Close Price&lt;/label&gt;<br>            &lt;label&gt;&lt;input type=&quot;checkbox&quot; name=&quot;indicators&quot; value=&quot;Open&quot; {% if &#39;Open&#39; in indicators %}checked{% endif %}&gt; Open Price&lt;/label&gt;<br>            &lt;label&gt;&lt;input type=&quot;checkbox&quot; name=&quot;indicators&quot; value=&quot;High&quot; {% if &#39;High&#39; in indicators %}checked{% endif %}&gt; High Price&lt;/label&gt;<br>            &lt;label&gt;&lt;input type=&quot;checkbox&quot; name=&quot;indicators&quot; value=&quot;Low&quot; {% if &#39;Low&#39; in indicators %}checked{% endif %}&gt; Low Price&lt;/label&gt;<br>            &lt;label&gt;&lt;input type=&quot;checkbox&quot; name=&quot;indicators&quot; value=&quot;Volume&quot; {% if &#39;Volume&#39; in indicators %}checked{% endif %}&gt; Volume&lt;/label&gt;<br>        &lt;/div&gt;<br>        &lt;button type=&quot;submit&quot;&gt;Get Trend&lt;/button&gt;<br>    &lt;/form&gt;<br>    {% if plot_url %}<br>        &lt;h2&gt;{{ ticker }} Stock Price&lt;/h2&gt;<br>        &lt;img src=&quot;data:image/png;base64,{{ plot_url }}&quot; alt=&quot;{{ ticker }} Stock Price&quot;&gt;<br>        <br>        &lt;h3&gt;Financial Analysis - GPT-4o Generated&lt;/h3&gt;<br>        &lt;div&gt;{{ analysis|safe }}&lt;/div&gt;<br>    {% endif %}<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h4>3. style.css</h4><ul><li>style.css provides the styling for the web application, ensuring it is visually appealing and user-friendly.</li></ul><pre>body {<br>    font-family: Arial, sans-serif;<br>    margin: 0;<br>    padding: 0;<br>    display: flex;<br>    flex-direction: column;<br>    align-items: center;<br>    background-color: #f4f4f4;<br>}<br><br>h1 {<br>    margin-top: 20px;<br>}<br><br>form {<br>    margin: 20px 0;<br>}<br><br>input[type=&quot;text&quot;] {<br>    padding: 10px;<br>    margin-right: 10px;<br>    border-radius: 5px;<br>    border: 1px solid #ccc;<br>}<br><br>label {<br>    margin-right: 10px;<br>}<br><br>button {<br>    padding: 10px 20px;<br>    border-radius: 5px;<br>    border: none;<br>    background-color: #007bff;<br>    color: white;<br>    cursor: pointer;<br>}<br><br>button:hover {<br>    background-color: #0056b3;<br>}<br><br>img {<br>    margin-top: 20px;<br>    max-width: 80%;<br>}<br><br>div {<br>    margin-top: 20px;<br>    text-align: left;<br>}</pre><h3>Final State of the Application</h3><p>Here are some screenshots that showcase the final state of the application:</p><ol><li>Stock Trends Form and Chart:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJdAbl5p2tMcUIRIuqiG0g.png" /><figcaption>Chart created via Matplotlib</figcaption></figure><p>2. Financial Company &amp; Chart Summary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jsan49mDWWIExqggJ3Brlg.png" /><figcaption>Chart &amp; Financial Analysis</figcaption></figure><p>3. Detailed Financial Analysis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CBk-GXTRYB_kYvqhlYjovA.png" /><figcaption>Detailed Financial Analysis</figcaption></figure><p>4. GPT-4o Analyst Recommendations and Insights:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q6G-2AtNuirE6llzxcg5-g.png" /><figcaption>GPT-4o Analyst Recommendations and Analysis</figcaption></figure><h3>Conclusion</h3><p>By integrating GPT-4o with Flask, this project harnesses the power of cutting-edge AI technology to provide enhanced financial analysis. GPT-4o’s advanced vision and language processing capabilities enable it to generate detailed and accurate financial reports, making it an invaluable tool for investors. Flask provides the web framework to build a user-friendly interface, allowing users to easily interact with the application.</p><p>This combination of GPT-4o and Flask offers a robust solution for anyone looking to better understand stock performance and company fundamentals. Stay tuned as I continue to develop and refine this exciting project!</p><h3><strong>Get in Touch / Code Repo</strong></h3><p>Linkedin — <a href="https://www.linkedin.com/in/ryan-k-ba8274122/">https://www.linkedin.com/in/ryan-k-ba8274122/</a></p><p>Github Repository — <a href="https://github.com/klapp101/ai_financial_analyst">https://github.com/klapp101/ai_financial_analyst</a></p><p>Helpful Resources:</p><ul><li><a href="https://github.com/openai/openai-cookbook/">https://github.com/openai/openai-cookbook/</a></li><li><a href="https://openai.com/index/hello-gpt-4o/">https://openai.com/index/hello-gpt-4o/</a></li><li><a href="https://pypi.org/project/yfinance/">https://pypi.org/project/yfinance/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02f2454dcc2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Future of LLMs: How Groq’s LPU Technology is Disrupting the Status Quo]]></title>
            <link>https://medium.com/@ryanklapper/the-future-of-llms-how-groqs-lpu-technology-is-disrupting-the-status-quo-8c71ae71a3a5?source=rss-51fd0854fd0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c71ae71a3a5</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[groq]]></category>
            <category><![CDATA[assistants-api]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Ryan Klapper]]></dc:creator>
            <pubDate>Fri, 19 Apr 2024 05:00:45 GMT</pubDate>
            <atom:updated>2024-04-19T05:00:45.102Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SA6bjEBoXEki5r2GW0vP1g.png" /></figure><p>In today’s fast-paced digital landscape, applications are expected to be lightning-quick, setting unrealistic expectations for page loading, video streaming, and more. This is especially true for Large Language Models (LLMs), where the benchmark is often set by ChatGPT. However, the reality is that most LLM applications rely on APIs, which can limit their speed and functionality.</p><p>Enter <a href="https://wow.groq.com/">Groq</a>, an innovative player in the LLM space, tackling this problem head-on with their LPU technology. This game-changing approach is designed to overcome the two major LLM bottlenecks: compute density and memory bandwidth. The result? An <a href="https://wow.groq.com/why-groq/">LPU Inference Engine</a> that provides the fastest inference for computationally intensive applications, leaving ChatGPT in the dust.</p><h3>What sets Groq apart?</h3><p>Groq’s LPU technology is a new type of end-to-end processing unit system that provides unparalleled performance for sequential applications like LLMs. With greater compute capacity than traditional GPUs and CPUs, LPUs reduce the time per word calculated, generating text sequences at unprecedented speeds. By eliminating external memory bottlenecks, LPUs deliver orders of magnitude better performance compared to GPUs.</p><h3>Developing with Groq’s API: A seamless experience</h3><p>Groq’s approach to their API is simplicity itself: model it after the leader in the space, OpenAI. This allows for extremely quick integration, making the transition from OpenAI’s API to Groq’s API a breeze. However, it’s worth noting that while OpenAI’s API offers access to a wide range of foundational models, Groq’s API currently only offers a select few open-sourced models to choose from. While this limited selection does contribute to faster performance, the difference is not drastic. Despite this, Groq’s API still shines with its lightning-fast speeds and seamless integration.</p><p>OpenAI Assistants API with GPT-4:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Jdc4rNHd9s8KzoK-zDhMg.gif" /><figcaption>OpenAI Assistants API (GPT-4) — Approximately 35 seconds</figcaption></figure><p>Groq API with Mixtral-8x7b-32768</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X2OdRxfbYnoY-Fc92lbZkw.gif" /><figcaption>Groq API (Mixtral-8x7b-32768) — Almost Instant</figcaption></figure><p>As you can see, the difference in output is like night and day. Groq’s API delivers faster results, leading to happier stakeholders and significant improvements in user satisfaction.</p><h3>Conclusion</h3><p>Groq’s LPU technology is revolutionizing the LLM space, offering a faster and more efficient alternative to traditional GPU-based approaches. With its seamless API integration and unparalleled performance, Groq is poised to disrupt the status quo and set a new standard for LLM development.</p><h3><strong>Get in Touch</strong></h3><p>Linkedin — <a href="https://www.linkedin.com/in/ryan-k-ba8274122/">https://www.linkedin.com/in/ryan-k-ba8274122/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c71ae71a3a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Claude 3: Function Calling in Action]]></title>
            <link>https://medium.com/@ryanklapper/claude-3-function-calling-in-action-09a0c03c56c3?source=rss-51fd0854fd0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/09a0c03c56c3</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[anthropic-claude]]></category>
            <category><![CDATA[nba]]></category>
            <dc:creator><![CDATA[Ryan Klapper]]></dc:creator>
            <pubDate>Wed, 10 Apr 2024 01:01:49 GMT</pubDate>
            <atom:updated>2024-04-10T01:01:49.948Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nztiCF0SgYCRhQtX" /></figure><p><strong>Introduction:</strong></p><p>OpenAI unleashed the power of function calling first, changing the game for how developers interact with LLMs. Function calling enables Large Language Models (LLMs) to connect with and effectively use external tools, facilitating interaction with external APIs. Similar to what we see in ChatGPT, where multiple tools can be used through chat (Data Analysis, Image Generation, etc.), we can give our agents access to tools we develop.</p><p>Anthropic’s Claude has emerged as a game-changer, offering developers and researchers a powerful suite of models to tackle complex tasks. <a href="https://docs.anthropic.com/claude/docs/tool-use">In a recent announcement from Anthropic</a>, Claude joined the function calling party. This allows developers to open up a world of possibilities for seamless data integration and task automation. In this article, we’ll dive into a codebase that showcases Claude’s function-calling prowess in the context of an NBA chatbot application.</p><p><strong>Anthropic vs. OpenAI — Cost Comparison</strong></p><p>For many categories, we’re seeing the <a href="https://www.anthropic.com/news/claude-3-family">Claude 3 family</a> outperform GPT and Gemini. Not only are we seeing improvements across many benchmark tests in the industry, but we are seeing massive speed and price improvements. Haiku speeds are on par with GPT-3.5 and are consistently more accurate across the board.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4tqIREGyfqJme76Qv6qMJg.png" /><figcaption>Claude 3 Haiku vs. GPT 3.5 pricing</figcaption></figure><p>Since the 2024 NBA playoffs are about to begin, I wanted to focus on the NBA for my application. To get some NBA data, <a href="https://github.com/swar/nba_api/tree/master">we’ll be interacting with an API</a> that makes it extremely easy to pull NBA statistics. When it comes to function calling, the primary thing to keep in mind is making your descriptions clear and concise:</p><pre>tools = [<br>            {<br>                &quot;name&quot;: &quot;get_player_info&quot;,<br>                &quot;description&quot;: &quot;Retrieves player information based on their name. Returns the player id and team&quot;,<br>                &quot;input_schema&quot;: {<br>                    &quot;type&quot;: &quot;object&quot;,<br>                    &quot;properties&quot;: {<br>                        &quot;DISPLAY_FIRST_LAST&quot;: {<br>                            &quot;type&quot;: &quot;string&quot;,<br>                            &quot;description&quot;: &quot;The name for the player.&quot;<br>                        }<br>                    },<br>                    &quot;required&quot;: [&quot;DISPLAY_FIRST_LAST&quot;]<br>                }<br>            }<br>]</pre><p>In the example above, we are creating a list of tools that have a function named get_player_info . We describe this function that is clear and easy for the LLM to understand. Any tool that we create is tied to a real python function, so when the LLM identifies which tool to use, it can do so and have a repeatable output with ease:</p><pre>    def get_player_info(self, player_name):<br>        players = commonallplayers.CommonAllPlayers()<br>        players_df = players.get_data_frames()[0]<br>        players_df = players_df[players_df[&#39;DISPLAY_FIRST_LAST&#39;] == player_name]<br>        return players_df</pre><p>In this function, we’re pulling in data based on the player&#39;s name. This is essentially the same as the tool we listed above. Now that there is a base understanding of how function calling works, let’s dive into the code:</p><pre>import streamlit as st<br>import os<br>from dotenv import load_dotenv<br>import anthropic<br>from nba_api.stats.endpoints import commonallplayers<br>from nba_api.stats.endpoints import playercareerstats<br>from nba_api.stats.endpoints import franchisehistory<br><br>load_dotenv()<br><br>class AnthropicFunctionCalling:<br>    def __init__(self):<br>        self.API_KEY = os.getenv(&#39;ANTHROPIC_API_KEY&#39;)<br>        self.MODEL_NAME = &quot;claude-3-haiku-20240307&quot;<br>        self.client = anthropic.Client(api_key=self.API_KEY)<br>        self.tools = [<br>            {<br>                &quot;name&quot;: &quot;get_player_info&quot;,<br>                &quot;description&quot;: &quot;Retrieves player information based on their name. Returns the player id and team&quot;,<br>                &quot;input_schema&quot;: {<br>                    &quot;type&quot;: &quot;object&quot;,<br>                    &quot;properties&quot;: {<br>                        &quot;DISPLAY_FIRST_LAST&quot;: {<br>                            &quot;type&quot;: &quot;string&quot;,<br>                            &quot;description&quot;: &quot;The name for the player.&quot;<br>                        }<br>                    },<br>                    &quot;required&quot;: [&quot;DISPLAY_FIRST_LAST&quot;]<br>                }<br>            },<br>            {<br>                &quot;name&quot;: &quot;get_player_statistics&quot;,<br>                &quot;description&quot;: &quot;Retrieves the statistics of a specific player based on the player name. Returns the player ID, most points scored in a season, free throw pct for the same season, and the team the player is currently playing for.&quot;,<br>                &quot;input_schema&quot;: {<br>                    &quot;type&quot;: &quot;object&quot;,<br>                    &quot;properties&quot;: {<br>                        &quot;DISPLAY_FIRST_LAST&quot;: {<br>                            &quot;type&quot;: &quot;string&quot;,<br>                            &quot;description&quot;: &quot;The name for the player.&quot;<br>                        }<br>                    },<br>                    &quot;required&quot;: [&quot;DISPLAY_FIRST_LAST&quot;]<br>                }<br>            },<br>            {<br>                &quot;name&quot;: &quot;get_league_titles&quot;,<br>                &quot;description&quot;: &quot;Gets the number of league titles won by a team based on the team ID. Returns the team ID, team city, team name, start year, end year, and the number of league titles won.&quot;,<br>                &quot;input_schema&quot;: {<br>                    &quot;type&quot;: &quot;object&quot;,<br>                    &quot;properties&quot;: {<br>                        &quot;TEAM_ID&quot;: {<br>                            &quot;type&quot;: &quot;string&quot;,<br>                            &quot;description&quot;: &quot;The unique identifier for the team.&quot;<br>                        }<br>                    },<br>                    &quot;required&quot;: [&quot;TEAM_ID&quot;]<br>                }<br>            }<br>        ]</pre><p>In the code above, we create the class <strong>AnthropicFunctionCalling</strong>, which allows us to set up all the variables that we’ll need for the rest of our app. We declare our API key, the primary model we’ll be using (Claude 3’s Haiku), the client, and our list of tools. Still, inside of this function, we’ll declare the 3 functions necessary to make the magic happen:</p><pre>    def get_player_info(self, player_name):<br>        players = commonallplayers.CommonAllPlayers()<br>        players_df = players.get_data_frames()[0]<br>        players_df = players_df[players_df[&#39;DISPLAY_FIRST_LAST&#39;] == player_name]<br>        return players_df<br><br>    def get_player_statistics(self, player_name):<br>        player_info = self.get_player_info(player_name)<br>        player_id = player_info[&#39;PERSON_ID&#39;].values[0]<br>        career = playercareerstats.PlayerCareerStats(player_id=player_id)<br>        career_df = career.get_data_frames()[0]<br>        career_df = career_df[career_df[&#39;PTS&#39;] == career_df[&#39;PTS&#39;].max()]<br>        career_df = career_df[[&#39;PLAYER_ID&#39;, &#39;SEASON_ID&#39;, &#39;PTS&#39;, &#39;FT_PCT&#39;, &#39;TEAM_ID&#39;, &#39;TEAM_ABBREVIATION&#39;]]<br>        return career_df<br><br>    def get_league_titles(self, team_id):<br>        history = franchisehistory.FranchiseHistory()<br>        history_df = history.get_data_frames()[0]   <br>        history_df = history_df[history_df[&#39;TEAM_ID&#39;] == int(team_id)]<br>        history_df = history_df[[&#39;TEAM_ID&#39;,&#39;TEAM_CITY&#39;,&#39;TEAM_NAME&#39;,&#39;START_YEAR&#39;, &#39;END_YEAR&#39;, &#39;LEAGUE_TITLES&#39;]]<br>        return history_df</pre><p>After we’ve declared our functions, we need the ability to choose which tool to call. We’ll pass this to the LLM to ensure that it can process between the tools. Alongside this, we want to keep track of much money we are spending with each API call. We’ve created a function that calculates the cost of each API call:</p><pre>    def process_tool_call(self, tool_name, tool_input):<br>        if tool_name == &quot;get_player_info&quot;:<br>            return self.get_player_info(tool_input[&quot;DISPLAY_FIRST_LAST&quot;])<br>        elif tool_name == &quot;get_player_statistics&quot;:<br>            return self.get_player_statistics(tool_input[&quot;DISPLAY_FIRST_LAST&quot;])<br>        elif tool_name == &quot;get_league_titles&quot;:<br>            return self.get_league_titles(tool_input[&quot;TEAM_ID&quot;])<br>        <br>    def calculate_cost(self, model_type, response_body):<br><br>        if &#39;tools&#39; not in response_body:<br>            input_tokens = response_body.usage.input_tokens<br>            output_tokens = response_body.usage.output_tokens<br>        else:<br>            input_tokens = response_body[&#39;usage&#39;][&#39;input_tokens&#39;]<br>            output_tokens = response_body[&#39;usage&#39;][&#39;output_tokens&#39;]<br>        # Define a dictionary with the cost per 1000 tokens for each model type<br>        cost_per_thousand_tokens = {<br>            &quot;anthropic.claude-3-sonnet-20240229-v1:0&quot;: {&quot;input&quot;: 0.003, &quot;output&quot;: 0.015},<br>            &quot;claude-3-haiku-20240307&quot;: {&quot;input&quot;: 0.00025, &quot;output&quot;: 0.00125},<br>            &quot;claude-3-opus-20240229&quot;: {&quot;input&quot;: 0.015, &quot;output&quot;: 0.075},<br>            &quot;meta.llama2-70b-chat-v1&quot;: {&quot;input&quot;: 0.00195, &quot;output&quot;: 0.00256},<br>            &quot;ai21.j2-ultra-v1&quot;: {&quot;input&quot;: 0.0188, &quot;output&quot;: 0.0188}<br>        }<br><br>        # Get the cost per 1000 tokens for the given model type<br>        cost = cost_per_thousand_tokens.get(model_type)<br><br>        if cost is None:<br>            raise ValueError(f&quot;Invalid model type: {model_type}&quot;)<br><br>        # Calculate the total cost<br>        total_cost = cost[&quot;input&quot;] * (input_tokens / 1000) + cost[&quot;output&quot;] * (output_tokens / 1000)<br><br>        return total_cost</pre><p><strong>Putting it all together:</strong></p><p>Now that we’ve done the heavy lifting, we need some ability to interact with the app that we’ve created. We are going to be leveraging my favorite tool to demo data apps, <a href="https://streamlit.io/">Streamlit</a>. Streamlit is a software product that allows you to share data apps in seconds and can bring LLM applications to life with ease:</p><pre>def main():<br>    st.title(&quot;NBA Chatbot&quot;)<br>    avatar = &quot;avatar.jpeg&quot;<br><br>    afc = AnthropicFunctionCalling()<br><br>    if &#39;messages&#39; not in st.session_state:<br>        st.session_state.messages = []<br><br>    if &quot;dataframes&quot; not in st.session_state:<br>        st.session_state.dataframes = []<br><br>    for message in st.session_state.messages:<br>        with st.chat_message(message[&quot;role&quot;], avatar=avatar):<br>            st.markdown(message[&quot;content&quot;])<br><br>    prompt = st.chat_input(&quot;Write your question&quot;)<br><br>    if prompt:<br>        st.session_state.messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt})<br>        with st.chat_message(&quot;user&quot;):<br>            st.markdown(prompt)<br><br>        with st.chat_message(&quot;assistant&quot;, avatar=avatar):<br>            response = afc.client.beta.tools.messages.create(<br>                model=afc.MODEL_NAME,<br>                max_tokens=4096,<br>                tools=afc.tools,<br>                messages=st.session_state.messages<br>            )<br>            <br>            initial_response_cost = afc.calculate_cost(response.model, response)<br><br>            st.session_state.messages.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: response.content})<br><br>            while response.stop_reason == &quot;tool_use&quot;:<br>                tool_use = next(block for block in response.content if block.type == &quot;tool_use&quot;)<br>                tool_name = tool_use.name<br>                tool_input = tool_use.input<br>                tool_result = afc.process_tool_call(tool_name, tool_input)<br><br>                st.session_state.messages.append({<br>                        &quot;role&quot;: &quot;user&quot;,<br>                        &quot;content&quot;: [<br>                            {<br>                                &quot;type&quot;: &quot;tool_result&quot;,<br>                                &quot;tool_use_id&quot;: tool_use.id,<br>                                &quot;content&quot;: str(tool_result),<br>                            }<br>                        ],<br>                    }<br>                )<br><br>                response = afc.client.beta.tools.messages.create(<br>                    model=afc.MODEL_NAME,<br>                    max_tokens=4096,<br>                    tools=afc.tools,<br>                    messages=st.session_state.messages<br>                )<br><br>                second_response_cost = afc.calculate_cost(response.model, response)<br><br>                st.session_state.messages.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: response.content})<br><br>            <br>            final_response = next(<br>                (block.text for block in response.content if hasattr(block, &quot;text&quot;)),<br>                None,<br>            )<br><br>            formatted_response = f&quot;&quot;&quot;<br>            Based on the response, ensure to format the message as follows:<br><br>            {final_response}<br><br>            Rules:<br><br>            - The message should be formatted as a string.<br>            - The message should be a response to the user&#39;s question.<br>            - The message should not mention the tool used.<br>            - Do not include the xml tags in the response<br>            - Respond in the exact format in the examples below<br><br>            Example:<br><br>            &lt;get_player_info&gt;&quot;Draymond Greene currently plays for the Golden State Warriors.&quot;&lt;/get_player_info&gt;<br>            &lt;get_player_statistics&gt;&quot;Here are some statistics regarding Draymond Greene:<br>            1. The most amount of points he scored in a season was 100 and that occured during the 2020-2021 season.<br>            2. His free throw percentage was 100% during the same season.<br>            3. For the season he had his most points scored, he played for the Golden State Warriors.<br>            &quot;&lt;/get_player_statistics&gt;<br>            &lt;get_league_titles&gt;&quot;The Golden State Warriors have won 6 league titles.&quot;&lt;/get_league_titles&gt;<br>            &quot;&quot;&quot;<br><br>            st.session_state.messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: final_response})<br>            formatted_response = [{&#39;role&#39;: &#39;user&#39;, &#39;content&#39;: formatted_response}]<br><br>            final_output_response = afc.client.messages.create(<br>                model=&#39;claude-3-opus-20240229&#39;,<br>                max_tokens=4096,<br>                temperature=0.0,<br>                messages=formatted_response<br>            )<br>            final_output_response_text = final_output_response.content[0].text<br>            st.markdown(final_output_response_text)<br>            final_output_response_cost = afc.calculate_cost(response.model, final_output_response)<br>            total_cost = initial_response_cost + second_response_cost + final_output_response_cost<br><br>        st.session_state.messages.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: final_output_response_text})<br>        st.session_state.dataframes.append((prompt, total_cost))<br><br>        for question, cost in st.session_state.dataframes:<br>            with st.expander(f&quot;Question - {question}&quot;):<br>                st.write(f&quot;TOTAL COST: ${cost}&quot;)<br><br>    <br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Inside of our main function, we are instantiating our class and setting up the chatbot. There is a bit of prompt engineering in here, so I would definitely recommend checking out Anthropic’s prompt engineer guide which can be found <a href="https://docs.anthropic.com/claude/docs/prompt-engineering">here</a>. After this occurs, we prompt the user what type of question they would like to ask and then begin sending requests to Claude:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*4LNtaVRu-2uFou30hr9dog.png" /></figure><p>In the screenshot above, we can see that just asking a question about statistics prompted the get_player_statistics function to be called. Claude was able to identify which tool to use and then return a response back to the user. To add to this, we can see the cost of the query in the screenshot as well.</p><p><strong>Conclusion:</strong></p><p>Automated function calling represents a pivotal advancement in the realm of application development, heralding a new era where efficiency and innovation converge. By seamlessly integrating with various tools and technologies, it not only promises to redefine the operational paradigms of numerous industries but also sets the stage for unprecedented growth and possibilities. As we stand on the cusp of this technological revolution, the anticipation for the transformative impact of automated function calling on our future workflows and industry standards is a testament to the promising horizon that lies ahead.</p><p><strong>Get in Touch / Code Repo</strong></p><p>Linkedin — <a href="https://www.linkedin.com/in/ryan-k-ba8274122/">https://www.linkedin.com/in/ryan-k-ba8274122/</a></p><p>Github Repository — <a href="https://github.com/klapp101/anthropic_function_calling/tree/main">https://github.com/klapp101/anthropic_function_calling/tree/main</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09a0c03c56c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Python App to Capture Images and Interact with OpenAI’s Vision API]]></title>
            <link>https://medium.com/@ryanklapper/building-a-python-app-to-capture-images-and-interact-with-openais-vision-api-bba7570f60a4?source=rss-51fd0854fd0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bba7570f60a4</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Ryan Klapper]]></dc:creator>
            <pubDate>Thu, 09 Nov 2023 00:54:01 GMT</pubDate>
            <atom:updated>2023-11-09T01:11:59.684Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fG5LnaZlbvl_J7-XHwc7hw.png" /></figure><p>In a world teeming with data, our ability to make sense of visual information is paramount. <a href="https://www.youtube.com/watch?v=U9mJuUkhUzk">OpenAI’s recent DevDay</a> introduced breakthroughs like the Vision API, which empowers developers to extend the sense of sight to machines. With this advancement, applications can now not only see but also interpret the world around us, laying the foundation for a myriad of innovative uses.</p><h3>The Project’s Heartbeat</h3><p>The app’s primary function is to capture an image using a camera and then apply AI to interpret and describe that image. In this project, I’ve utilized OpenAI’s newly released <a href="https://platform.openai.com/docs/guides/vision">Vision API</a> in conjunction with their <a href="https://platform.openai.com/docs/guides/text-to-speech">Audio API</a>. This combination allows the system to not only analyze visual content but also convey the findings through synthesized speech, effectively translating visual information into auditory descriptions. The integration showcases how visual and linguistic AI models can be orchestrated to convert image data into a spoken narrative.</p><h3>Why This Matters</h3><p>As highlighted during the keynote, OpenAI’s mission extends beyond the technology itself — it’s about augmenting human capabilities and fostering creativity. By leveraging the <a href="https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo">GPT-4 Turbo model</a>, developers like myself can craft solutions that bring this vision to life, making technology an active participant in our daily lives.</p><h3>The Tools</h3><p>The core technologies I used for this project were:</p><ul><li>Python: A versatile programming language that’s become synonymous with AI and machine learning projects.</li><li>OpenCV (Open Source Computer Vision Library): A library of programming functions aimed at real-time computer vision.</li><li>OpenAI’s API: Provides access to powerful AI models capable of understanding and generating natural language and now, analyzing images.</li></ul><h3>Step-by-Step Implementation</h3><h4>Initializing the Camera Application</h4><p>We begin by defining a CameraApp class with an initializer that takes a camera_index to identify which camera device to use and an api_key for authenticating with the OpenAI API. The initialize_camera method attempts to start video capture with the specified camera index.</p><pre>from openai import OpenAI<br>import cv2<br>import time<br>import base64<br>import requests<br><br>client = OpenAI(api_key=&#39;API_KEY_HERE&#39;)<br><br>class CameraApp:<br>    def __init__(self, camera_index, api_key):<br>        self.camera_index = camera_index<br>        self.api_key = api_key<br><br>    def initialize_camera(self):<br>        self.cap = cv2.VideoCapture(self.camera_index)<br>        if not self.cap.isOpened():<br>            print(&quot;Cannot open camera&quot;)<br>            return False<br>        return True</pre><h4>Capturing and Saving the Image</h4><p>The capture_image method activates the camera, waits for it to adjust its autoexposure settings, and then captures a single frame. If successful, it saves the frame to a file.</p><pre>def capture_image(self, filename=&#39;capture.jpg&#39;):<br>    if not self.initialize_camera():<br>        return False<br>    time.sleep(2)  # Camera warm-up<br>    for _ in range(10): self.cap.read()  # Autoexposure adjustment<br>    ret, frame = self.cap.read()<br>    if ret:<br>        cv2.imwrite(filename, frame)<br>        print(&quot;Image captured successfully&quot;)<br>    else:<br>        print(&quot;Failed to capture image&quot;)<br>    self.cap.release()<br>    cv2.destroyAllWindows()<br>    return ret</pre><h4>Encoding the Image and Making the API Request</h4><p>To interact with the OpenAI API, the image needs to be encoded in base64. The encode_image method handles this, and send_request sends the encoded image to the OpenAI API, asking for a description of the image limited to 100 words.</p><pre>def encode_image(self, image_path):<br>    with open(image_path, &quot;rb&quot;) as image_file:<br>        return base64.b64encode(image_file.read()).decode(&#39;utf-8&#39;)<br><br>def send_request(self, image_data):<br>    headers = {&quot;Content-Type&quot;: &quot;application/json&quot;, &quot;Authorization&quot;: f&quot;Bearer {self.api_key}&quot;}<br>    payload = {<br>        &quot;model&quot;: &quot;gpt-4-vision-preview&quot;,<br>        &quot;messages&quot;: [{<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;Tell me about this image. Limit your response to 100 words.&quot;}, {&quot;type&quot;: &quot;image_url&quot;, &quot;image_url&quot;: {&quot;url&quot;: f&quot;data:image/jpeg;base64,{image_data}&quot;}}]<br>        }],<br>        &quot;max_tokens&quot;: 300<br>    }<br>    return requests.post(&quot;https://api.openai.com/v1/chat/completions&quot;, headers=headers, json=payload).json()</pre><h4>Converting the Response to Audio</h4><p>Once we have the textual response, save_response_as_audio uses the OpenAI Audio API to create a speech output of the description which is saved as an MP3 file.</p><pre>def save_response_as_audio(self, response_data):<br>    response = client.audio.speech.create(<br>        model=&quot;tts-1&quot;,<br>        voice=&quot;alloy&quot;,<br>        input=response_data[&#39;choices&#39;][0][&#39;message&#39;][&#39;content&#39;],<br>    )<br>    response.stream_to_file(&quot;output.mp3&quot;)</pre><h4>Estimating the API Usage Cost</h4><p>The openai_api_calculate_cost method calculates the cost of using the <a href="https://openai.com/pricing">OpenAI API</a> based on the number of tokens used in the prompt and completion.</p><pre>def openai_api_calculate_cost(self, usage, model=&quot;gpt-4-1106-vision-preview&quot;):<br>  pricing = {<br>      &#39;gpt-3.5-turbo-1106&#39;: {<br>          &#39;prompt&#39;: 0.001,<br>          &#39;completion&#39;: 0.002,<br>      },<br>      &#39;gpt-4-8k&#39;: {<br>          &#39;prompt&#39;: 0.03,<br>          &#39;completion&#39;: 0.06,<br>      },<br>      &#39;gpt-4-32k&#39;: {<br>          &#39;prompt&#39;: 0.06,<br>          &#39;completion&#39;: 0.12,<br>      },<br>      &#39;gpt-4-1106-vision-preview&#39;: {<br>          &#39;prompt&#39;: 0.01,<br>          &#39;completion&#39;: 0.03,<br>      }<br>  }<br><br>  try:<br>      model_pricing = pricing[model]<br>  except KeyError:<br>      raise ValueError(&quot;Invalid model specified&quot;)<br>  <br>  prompt_cost = usage[&#39;prompt_tokens&#39;] * model_pricing[&#39;prompt&#39;] / 1000<br>  completion_cost = usage[&#39;completion_tokens&#39;] * model_pricing[&#39;completion&#39;] / 1000<br><br>  total_cost = prompt_cost + completion_cost<br>  print(f&quot;\nTokens used:  {usage[&#39;prompt_tokens&#39;]:,} prompt + {usage[&#39;completion_tokens&#39;]:,} completion = {usage[&#39;total_tokens&#39;]:,} tokens&quot;)<br>  print(f&quot;Total cost for {model}: ${total_cost:.4f}\n&quot;)<br><br>  return total_cost</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*h2dMv6G4MDvnZG6D4tSgxA.png" /><figcaption>Cost for me to generate the photo</figcaption></figure><h4>Running the Application</h4><p>Finally, we instantiate the CameraApp with the appropriate camera index and API key. We then capture an image, send it for analysis, calculate the cost, and generate the audio output.</p><pre>camera_app = CameraApp(camera_index=1, api_key=client.api_key)<br>if camera_app.capture_image():<br>    encoded_image = camera_app.encode_image(&#39;capture.jpg&#39;)<br>    response_data = camera_app.send_request(encoded_image)<br>    camera_app.save_response_as_audio(response_data)<br>    total_cost = camera_app.openai_api_calculate_cost(response_data[&#39;usage&#39;])</pre><h4>Here are the final results</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xz7irtuqGBkrgg2u5KDgdg.jpeg" /><figcaption>Here I am!</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F1660226718%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Fryan-klapper-396034775%2Fai-describing-me%3Fsi%3D424de166e6fd41c4b25584c0b12245b4%26utm_source%3Dclipboard%26utm_medium%3Dtext%26utm_campaign%3Dsocial_sharing&amp;image=https%3A%2F%2Fi1.sndcdn.com%2Fartworks-wKI32HM8xSVV9gOI-yQGZag-t500x500.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/162e0902f358277b95bad48cee525bba/href">https://medium.com/media/162e0902f358277b95bad48cee525bba/href</a></iframe><h3>Connect with Me</h3><p>I’m always open to connecting with fellow developers and tech enthusiasts. If you want to discuss this project, share ideas, or simply connect, feel free to reach out to me.</p><ul><li>LinkedIn: <a href="https://www.linkedin.com/in/ryan-k-ba8274122/">Ryan Klapper</a></li><li>GitHub: <a href="https://github.com/klapp101/">klapp101</a></li></ul><h3>Explore the Codebase</h3><p>The complete code for this project is available for you to delve into. Check it out, play around with it, and let me know what you think!</p><ul><li>GitHub Repository: <a href="https://github.com/klapp101/vision_to_speech/tree/main">CameraApp Codebase</a></li></ul><p>I encourage you to star, fork, and contribute to the repository. Any feedback or contributions are highly appreciated!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bba7570f60a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>