RSSHub icon indicating copy to clipboard operation
RSSHub copied to clipboard

feat(route/cookbook): Add OpenAICookbook

Open liyaozhong opened this issue 2 years ago • 6 comments

Involved Issue / 该 PR 相关 Issue

Example for the Proposed Route(s) / 路由地址示例

/cookbook

New RSS Route Checklist / 新 RSS 路由检查表

  • [x] New Route / 新的路由
  • [ ] Anti-bot or rate limit / 反爬/频率限制
    • [ ] If yes, do your code reflect this sign? / 如果有, 是否有对应的措施?
  • [x] Date and time / 日期和时间
    • [x] Parsed / 可以解析
    • [x] Correct time zone / 时区正确
  • [ ] New package added / 添加了新的包
  • [ ] Puppeteer

Note / 说明

OpenAI Cookbook provides a wealth of example code on how to use the OpenAI API, covering common tasks such as natural language generation, language translation, and chat dialogue. These examples are suitable for developers of all skill levels, from beginners to experienced users.

liyaozhong avatar Oct 19 '24 13:10 liyaozhong

Successfully generated as following:

http://localhost:1200/cookbook - Success ✔️
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <title>OpenAI Cookbook</title>
    <link>https://cookbook.openai.com/</link>
    <atom:link href="http://localhost:1200/cookbook" rel="self" type="application/rss+xml"></atom:link>
    <description>OpenAI Cookbook - Powered by RSSHub</description>
    <generator>RSSHub</generator>
    <webMaster>[email protected] (RSSHub)</webMaster>
    <language>en</language>
    <lastBuildDate>Sat, 19 Oct 2024 13:15:18 GMT</lastBuildDate>
    <ttl>5</ttl>
    <item>
      <title>Orchestrating Agents: Routines and Handoffs</title>
      <description>When working with language models, quite often all you need for solid performance is a good prompt and the right tools. However, when dealing with many unique flows, things may get hairy. This cookbook will walk through one way to tackle this.
        We&#39;ll introduce the notion of routines and handoffs, then walk through the implementation and show how they can be used to orchestrate multiple agents in a simple, powerful, and controllable way.
        Finally, we provide a sample repo, Swarm, that implements these ideas along with examples.
        Let&#39;s start by setting up our imports.
        The notion of a &quot;routine&quot; is not strictly defined, and instead meant to capture the idea of a set of steps. Conretely, let&#39;s define a routine to be a list of instructions in natural langauge (which we&#39;ll represent with a system prompt), along with the tools necessary to complete them.
        Let&#39;s take a look at an example. Below, we&#39;ve defined a routine for a customer service agent instructing it to triage the user issue, then either suggest a fix or provide a refund. We&#39;ve also defined the necessary functions execute_refund and look_up_item. We can call this a customer service routine, agent, assistant, etc –&amp;nbsp;however the idea itself is the same: a set of steps and the tools to execute them.
        The main power of routines is their simplicity and robustness. Notice that these instructions contain conditionals much like a state machine or branching in code. LLMs can actually handle these cases quite robustly for small and medium sized routine, with the added benefit of having &quot;soft&quot; adherance –&amp;nbsp;the LLM can naturally steer the conversation without getting stuck in dead-ends.
        To execute a routine, let&#39;s implement a simple loop that:
        - Gets user input.
        - Appends user message to messages.
        - Calls the model.
        - Appends model response to messages.
        As you can see, this currently ignores function calls, so let&#39;s add that.
        Models require functions to be formatted as a function schema. For convenience, we can define a helper function that turns python functions into the corresponding function schema.
        For example:
        Now, we can use this function to pass the tools to the model when we call it.
        Finally, when the model calls a tool we need to execute the corresponding function and provide the result back to the model.
        We can do this by mapping the name of the tool to the python function in a tool_map, then looking it up in execute_tool_call and calling it. Finally we add the result to the conversation.
        In practice, we&#39;ll also want to let the model use the result to produce another response. That response might also contain a tool call, so we can just run this in a loop until there are no more tool calls.
        If we put everything together, it will look something like this:
        Now that we have a routine, let&#39;s say we want to add more steps and more tools. We can up to a point, but eventually if we try growing the routine with too many different tasks it may start to struggle. This is where we can leverage the notion of multiple routines – given a user request, we can load the right routine with the appropriate steps and tools to address it.
        Dynamically swapping system instructions and tools may seem daunting. However, if we view &quot;routines&quot; as &quot;agents&quot;, then this notion of handoffs allow us to represent these swaps simply –&amp;nbsp;as one agent handing off a conversation to another.
        Let&#39;s define a handoff as an agent (or routine) handing off an active conversation to another agent, much like when you get transfered to someone else on a phone call. Except in this case, the agents have complete knowledge of your prior conversation!
        To see handoffs in action, let&#39;s start by defining a basic class for an Agent.
        Now to make our code support it, we can change run_full_turn to take an Agent instead of separate system_message and tools:
        We can now run multiple agents easily:
        Great! But we did the handoff manually here –&amp;nbsp;we want the agents themselves to decide when to perform a handoff. A simple, but surprisingly effective way to do this is by giving them a transfer_to_XXX function, where XXX is some agent. The model is smart enough to know to call this function when it makes sense to make a handoff!
        ## Handoff Functions
        Now that agent can express the intent to make a handoff, we must make it actually happen. There&#39;s many ways to do this, but there&#39;s one particularly clean way.
        For the agent functions we&#39;ve defined so far, like execute_refund or place_order they return a string, which will be provided to the model. What if instead, we return an Agent object to indate which agent we want to transfer to? Like so:
        We can then update our code to check the return type of a function response, and if it&#39;s an Agent, update the agent in use! Additionally, now run_full_turn will need to return the latest agent in use in case there are handoffs. (We can do this in a Response class to keep things neat.)
        Now for the updated run_full_turn:
        Let&#39;s look at an example with more Agents.
        Finally, we can run this in a loop (this won&#39;t run in python notebooks, so you can try this in a separate python file):
        As a proof of concept, we&#39;ve packaged these ideas into a sample library called Swarm. It is meant as an example only, and should not be directly used in production. However, feel free to take the ideas and code to build your own!
      </description>
      <link>https://cookbook.openai.com/examples/orchestrating_agents</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/orchestrating_agents</guid>
      <pubDate>Wed, 09 Oct 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Functions</category>
    </item>
    <item>
      <title>Prompt Caching 101</title>
      <description>OpenAI offers discounted prompt caching for prompts exceeding 1024 tokens, resulting in up to an 80% reduction in latency for longer prompts over 10,000 tokens. By caching repetitive information across LLM API requests, you can greatly reduce both latency and costs. Prompt caching is scoped at the organization level, meaning only members of the same organization can access shared caches. Additionally, caching is eligible for zero data retention, as no data is stored during the process.
        Prompt caching automatically activates for prompts longer than 1024 tokens-- you don&#39;t have to change anything in your completions request. When an API request is made, the system first checks if the beginning portion (prefix) of the prompt has already been cached. If a match is found (cache hit), the cached prompt is used, leading to reduced latency and costs. If there&#39;s no match, the system processes the full prompt from scratch and caches the prefix for future use.
        With these benefits in mind, some of the key use cases where prompt caching can be especially advantageous are:
        - Agents using tools and structured outputs: Cache the extended list of tools and schemas.
        - Coding and writing assistants: Insert large sections or summaries of codebases and workspaces directly in prompts.
        - Chatbots: Cache static portions of multi-turn conversations to maintain context efficiently over extended dialogues.
        In this cookbook, we&#39;ll go through a couple examples of caching tools and images. Recall that in general, you&#39;ll want to put static content like instructions and examples at the beginning of your prompt, and variable content, such as user-specific information, at the end. This also applies to images and tools, which must be identical even in their ordering between requests. All requests, including those with fewer than 1024 tokens, will display a cached_tokens field of the usage.prompt_tokens_details chat completions object indicating how many of the prompt tokens were a cache hit. For requests under 1024 tokens, cached_tokens will be zero. Caching discounts are based on the actual number of tokens processed, including those used for images, which also count toward your rate limits.
        In this example, we define tools and interactions for a customer support assistant, capable of handling tasks such as checking delivery dates, canceling orders, and updating payment methods. The assistant processes two separate messages, first responding to an initial query, followed by a delayed response to a follow-up query.
        When caching tools, it is important that the tool definitions and their order remain identical for them to be included in the prompt prefix. To cache message histories in a multi-turn conversation, append new elements to the end of the messages array. In the response object and the output below, for the second completion run2, you can see that the cached_tokens value is greater than zero, indicating successful caching.
        In our second example we include multiple image URLs of grocery items in the messages array, along with a user query, run three times with delays. Images—whether linked or encoded in base64 within user messages—qualify for caching. Make sure the detail parameter remains consistent, as it affects how images are tokenized. Note that GPT-4o-mini adds extra tokens to cover image processing costs, even though it uses a low-cost token model for text. Caching discounts are based on the actual number of tokens processed, including those used for images, which also count toward your rate limits.
        The output for this example shows that a cache was hit for the second run, however it was not hit for the third run because of a different first url (eggs_url instead of veggie_url), even though the user query is the same.
        To get the most out of prompt caching, consider following these best practices:
        - Place static or frequently reused content at the beginning of prompts: This helps ensure better cache efficiency by keeping dynamic data towards the end of the prompt.
        - Maintain consistent usage patterns: Prompts that aren&#39;t used regularly are automatically removed from the cache. To prevent cache evictions, maintain consistent usage of prompts.
        - Monitor key metrics: Regularly track cache hit rates, latency, and the proportion of cached tokens. Use these insights to fine-tune your caching strategy and maximize performance.
        By implementing these practices, you can take full advantage of prompt caching, ensuring that your applications are both responsive and cost-efficient. A well-managed caching strategy will significantly reduce processing times, lower costs, and help maintain smooth user experiences.
      </description>
      <link>https://cookbook.openai.com/examples/prompt_caching101</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/prompt_caching101</guid>
      <pubDate>Mon, 30 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
    </item>
    <item>
      <title>Using chained calls for o1 structured outputs</title>
      <description>The initially released versions (September 2024) of o1 reasoning models have advanced capabilities but do not have structured outputs support.
        This means that requests with o1 don&#39;t have reliable type-safety and rely on the prompt itself to return a useful JSON.
        In this guide, we&#39;ll explore two methods to prompt o1 models, specifically o1-preview, to return a valid JSON format when using the OpenAI API.
        The simplest way to return a JSON response using o1-preview is to explicitly prompt it.
        Let&#39;s run through an example of:
        - Fetching a wikipedia page of companies
        - Determining which could benefit the most from AI capabilities
        - Returning them in a JSON format, which could then be ingested by other systems
        Note that the response is already quite good - it returns the JSON with the appropriate responses. However, it runs into the same pitfalls as existing use-cases of prompt-only JSON inference:
        - You must manually process this JSON into your type-safe structure
        - Model refusals are not explicitly returned from the API as a separate structure
        Let&#39;s now do this with structured outputs. To enable this functionality, we’ll link the o1-preview response with a follow-up request to gpt-4o-mini, which can effectively process the data returned from the initial o1-preview response.
        Structured outputs allow your code to have reliable type-safety and simpler prompting. In addition, it allows you to re-use your object schemas for easier integration into your existing workflows.
        The o1 class of models currently doesn&#39;t have structured outputs support, but we can re-use existing structured outputs functionality from gpt-4o-mini by chaining two requests together. This flow currently requires two calls, but the second gpt-4o-mini call cost should be minimal compared to the o1-preview/o1-mini calls.
      </description>
      <link>https://cookbook.openai.com/examples/o1/using_chained_calls_for_o1_structured_outputs</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/o1/using_chained_calls_for_o1_structured_outputs</guid>
      <pubDate>Wed, 25 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Reasoning</category>
    </item>
    <item>
      <title>Building a Bring Your Own Browser (BYOB) Tool for Web Browsing and Summarization</title>
      <description>Disclaimer: This cookbook is for educational purposes only. Ensure that you comply with all applicable laws and service terms when using web search and scraping technologies. This cookbook will restrict the search to openai.com domain to retrieve the public information to illustrate the concepts.
        Large Language Models (LLMs) such as GPT-4o have a knowledge cutoff date, which means they lack information about events that occurred after that point. In scenarios where the most recent data is essential, it&#39;s necessary to provide LLMs with access to current web information to ensure accurate and relevant responses.
        In this guide, we will build a Bring Your Own Browser (BYOB) tool using Python to overcome this limitation. Our goal is to create a system that provides up-to-date answers in your application, including the most recent developments such as the latest product launches by OpenAI. By integrating web search capabilities with an LLM, we&#39;ll enable the model to generate responses based on the latest information available online.
        While you can use any publicly available search APIs, we&#39;ll utilize Google&#39;s Custom Search API to perform web searches. The retrieved information from the search results will be processed and passed to the LLM to generate the final response through Retrieval-Augmented Generation (RAG).
        Bring Your Own Browser (BYOB) tools allow users to perform web browsing tasks programmatically. In this notebook, we&#39;ll create a BYOB tool that:
        #1. Set Up a Search Engine: Use a public search API, such as Google&#39;s Custom Search API, to perform web searches and obtain a list of relevant search results.
        #2. Build a Search Dictionary: Collect the title, URL, and a summary of each web page from the search results to create a structured dictionary of information.
        #3. Generate a RAG Response: Implement Retrieval-Augmented Generation (RAG) by passing the gathered information to the LLM, which then generates a final response to the user&#39;s query.
        ## Use Case
        In this cookbook, we&#39;ll take the example of a user who wants to list recent product launches by OpenAI in chronological order. Because the current GPT-4o model has a knowledge cutoff date, it is not expected that the model will know about recent product launches such as the o1-preview model launched in September 2024.
        Given the knowledge cutoff, as expected the model does not know about the recent product launches by OpenAI.
        ## Setting up a BYOB tool
        To provide the model with recent events information, we&#39;ll follow these steps:
        Before we begin, ensure you have the following: Python 3.12 or later installed on your machine. You will also need a Google Custom Search API key and Custom Search Engine ID (CSE ID). Necessary Python packages installed: requests, beautifulsoup4, openai. And ensure the OPENAI_API_KEY is set up as an environment variable.
        You can use any publicly available web search APIs to perform this task. We will configure a custom search engine using Google&#39;s Custom Search API. This engine will fetch a list of relevant web pages based on the user&#39;s query, focusing on obtaining the most recent and pertinent results.
        a. Configure Search API key and Function: Acquire a Google API key and a Custom Search Engine ID (CSE ID) from the Google Developers Console. You can navigate to this Programmable Search Engine Link to set up an API key as well as Custom Search Engine ID (CSE ID).
        The search function below sets up the search based on search term, the API and CSE ID keys, as well as number of search results to return. We&#39;ll introduce a parameter site_filter to restrict the output to only openai.com
        b. Identify the search terms for search engine: Before we can retrieve specific results from a 3rd Party API, we may need to use Query Expansion to identify specific terms our browser search API should retrieve. Query expansion is a process where we broaden the original user query by adding related terms, synonyms, or variations. This technique is essential because search engines, like Google&#39;s Custom Search API, are often better at matching a range of related terms rather than just the natural language prompt used by a user.
        For example, searching with only the raw query &quot;List the latest OpenAI product launches in chronological order from latest to oldest in the past 2 years&quot; may return fewer and less relevant results than a more specific and direct search on a succinct phrase such as &quot;Latest OpenAI product launches&quot;. In the code below, we will use the user&#39;s original search_query to produce a more specific search term to use with the Google API to retrieve the results.
        c. Invoke the search function: Now that we have the search term, we will invoke the search function to retrieve the results from Google search API. The results only have the link of the web page and a snippet at this point. In the next step, we will retrieve more information from the webpage and summarize it in a dictionary to pass to the model.
        After obtaining the search results, we&#39;ll extract and organize the relevant information, so it can be passed to the LLM for final output.
        a. Scrape Web Page Content: For each URL in the search results, retrieve the web page to extract textual content while filtering out non-relevant data like scripts and advertisements as demonstrated in function retrieve_content.
        b. Summarize Content: Use an LLM to generate concise summaries of the scraped content, focusing on information pertinent to the user&#39;s query. Model can be provided the original search text, so it can focus on summarizing the content for the search intent as outlined in function summarize_content.
        c. Create a Structured Dictionary: Organize the data into a dictionary or a DataFrame containing the title, link, and summary for each web page. This structure can be passed on to the LLM to generate the summary with the appropriate citations.
        We retrieved the most recent results. (Note these will vary depending on when you execute this script.)
        With the search data organized in a JSON data structure, we will pass this information to the LLM with the original user query to generate the final response. Now, the LLM response includes information beyond its original knowledge cutoff, providing current insights.
        ## Conclusion
        Large Language Models (LLMs) have a knowledge cutoff and may not be aware of recent events. To provide them with the latest information, you can build a Bring Your Own Browser (BYOB) tool using Python. This tool retrieves current web data and feeds it to the LLM, enabling up-to-date responses.
        The process involves three main steps:
        #1 Set Up a Search Engine: Use a public search API, like Google&#39;s Custom Search API, to perform web searches and obtain a list of relevant search results.
        #2 Build a Search Dictionary: Collect the title, URL, and a summary of each web page from the search results to create a structured dictionary of information.
        #3. Generate a RAG Response: Implement Retrieval-Augmented Generation (RAG) by passing the gathered information to the LLM, which then generates a final response to the user&#39;s query.
        By following these steps, you enhance the LLMs ability to provide up-to-date answers in your application that include the most recent developments, such as the latest product launches by OpenAI.
      </description>
      <link>https://cookbook.openai.com/examples/third_party/web_search_with_google_api_bring_your_own_browser_tool</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/third_party/web_search_with_google_api_bring_your_own_browser_tool</guid>
      <pubDate>Wed, 25 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
    </item>
    <item>
      <title>GPT Actions library - Retool Workflow</title>
      <description>This page provides an instruction &amp;amp; guide for developers building a GPT Action for a specific application. Before you proceed, make sure to first familiarize yourself with the following information:
        - Introduction to GPT Actions
        - Introduction to GPT Actions Library
        - Example of Building a GPT Action from Scratch
        This particular GPT Action provides an overview of how to connect to a Retool Workflow. This Action takes a users input and sends it to the workflow in Retool using a webhook trigger. Retool then performns the configured workflow and sends a response back to ChatGPT as a JSON object.
        ## Value + Example Business Use Cases
        Value: Users can now leverage ChatGPT&#39;s natural language capability to connect directly to any workflow in Retool.
        Example Use Cases:
        - You have custom code running in a Retool workflow that you&#39;d like to incorporate into a GPT.
        - Data Scientists maintain an external VectorDB (either using Retool Vector or another vector DB) and would like to send the results of the vector search back to ChatGPT.
        - Retool is used as middleware to connect to internal services, and you&#39;d like to use Retool&#39;s webhooks to provide access to these services to ChatGPT.
        ## Application Key Links
        Check out these links from the application before you get started:
        - Application Website: https://retool.com/products/workflows
        - Application API Documentation: https://docs.retool.com/workflows
        ## Application Prerequisites
        Before you get started, make sure you go through the following steps in your Retool environment:
        - Set up a Retool account
        - Create a simple workflow
        ## Application Workflow Steps
        Below is an example of a basic Retool Workflow. This workflow takes in 2 values and adds them and responds to the webhook trigger with the result.
        Note: Your workflow must be deployed before it will be accessible from your GPT.
        ## Custom GPT Instructions
        Once you&#39;ve created a Custom GPT, you should add Instructions to the GPT providing context about the GPTs role, and the actions it is able to perform. Have questions? Check out Getting Started Example to see how this step works in more detail.
        ## OpenAPI Schema
        Once you&#39;ve created a Custom GPT, copy the text below in the Actions panel. Have questions? Check out Getting Started Example to see how this step works in more detail.
        Note: You need to replace the &lt;workflow_id&gt; value in the OpenAPI spec below with the ID for your workflow.
        Below are instructions on setting up authentication with this 3rd party application. Have questions? Check out Getting Started Example to see how this step works in more detail.
        ## Pre-Action Steps
        Before you set up authentication in ChatGPT, please take the following steps in the application.
        - Get your API Key from the Webhook config panel
        ## In ChatGPT
        In ChatGPT, click on &quot;Authentication&quot; and choose &quot;API Key&quot;. Enter in the information below.
        - API Key: (Paste your API Key provided by the Retool Workflow Webhook Trigger)
        - Auth Type: Custom
        - Custom Header Name: X-Workflow-Api-Key
        ## FAQ &amp;amp; Troubleshooting
        - Auth Error: Ensure you have set the custom header name correctly.
        - Invalid Workflow Error: Ensure you have deployed your workflow within Retool.
        Are there integrations that you’d like us to prioritize? Are there errors in our integrations? File a PR or issue in our github, and we’ll take a look.
        &lt;/workflow_id&gt;</description>
      <link>https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_retool_workflow</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_retool_workflow</guid>
      <pubDate>Tue, 27 Aug 2024 16:00:00 GMT</pubDate>
      <category>ChatGPT</category>
      <category>GPT actions library</category>
    </item>
    <item>
      <title>GPT Actions library - Snowflake Middleware</title>
      <description>This page provides an instruction &amp;amp; guide for developers building a GPT Action for a specific application. Before you proceed, make sure to first familiarize yourself with the following information:
        - Introduction to GPT Actions
        - Introduction to GPT Actions Library
        - Example of Buliding a GPT Action from Scratch
        This guide provides details on how to connect ChatGPT with a Snowflake Data Warehouse for the purposes of returning a SQL query to ChatGPT for use with Data Analysis. The GPT requires an action that interfaces with middleware (ie Azure function) so that the action can properly format the response from Snowflake for use in the Python notebook environment. Data must be returned as a file, so the middleware function should transform the SQL response into a CSV/Excel file, under 10MB in size.
        This document will outline the Middleware function GPT action. For setting up the middleware function itself, see GPT Actions library (Middleware) - Azure Functions. You can combine this Snowflake middleware action with an action to Snowflake Directly to enable a GPT that can form and test SQL queries prior to executing them.
        ## Value + Example Business Use Cases
        Existing Snowflake customers can leverage these guidelines to query data from their data warehouse and load that data into the Data Analysis Python environment for further insights. This enables ChatGPT powered analysis such as visualizing data sets, identifying patterns/anomalies, or identifying gaps for data cleansing purposes. This GPT can be used to drive business decisions from relatively small datasets, or to explore subsets of data through AI to generate hypotheses as you explore the holistic dataset in your BI tool, saving time and money, while identifying previously unseen patterns.
        ## Application Key Links
        Check out these links from Snowflake and Azure before you get started:
        Snowflake Action
        - Application Website: https://app.snowflake.com/
        - Application Python Connector Documentation: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-connect
        Azure Function
        - Application Website: https://learn.microsoft.com/en-us/azure/azure-functions/
        - Application API Documentation: https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference/
        ## Application Prerequisites
        Before you get started, make sure you go through the following steps in your application environment:
        - Provision a Snowflake Data Warehouse
        - Ensure that the user authenticating into Snowflake via ChatGPT has access to the database, schemas, and tables with the necessary role
        In addition, before creating your application in Azure Function App, you’ll need a way to handle user authentication. You’ll need to set up an OAuth App Registration in Azure Entra ID that can be linked with a Snowflake External OAuth security integration. Snowflake’s External OAuth security integrations allow external systems to issue access tokens that Snowflake can use for determining level of access. In this case, that external token provider is Azure Entra ID. Since ChatGPT will connect to Azure rather than Snowflake, the GPT user’s OAuth token will be provisioned by Azure associated with their user in Entra ID. Thus you’ll need a way to map users in Snowflake to their corresponding user in Azure.
        All of the necessary steps for both the Azure side and the Snowflake side are laid out below.
        We’ll set up a new App Registration, configure the necessary Snowflake Scopes in Azure that will be used, and retrieve all of the OAuth configuration parameters that will be needed in both Snowflake and ChatGPT. This section will all be in Azure so that in the next section, you’ll have the necessary info to link to this App Registration when configuring on the Snowflake side.
        - Navigate to the Microsoft Azure Portal and authenticate.
        - Navigate to Azure Entra ID (formerly Active Directory).
        - Click on App Registrations under Manage.
        - Click on New Registration.
        - Enter Snowflake GPT OAuth Client, or similar value as the Name.
        - Verify the Supported account types is set to Single Tenant.
        - Ignore Redirect URI for now. You will come back for this once you are configuring your GPT
        - Click Register.
        - Note down the Directory (tenant) ID (TENANT_ID) under Essentials. You will use this to generate your AZURE_AD_ISSUER and AZURE_AD_JWS_KEY_ENDPOINT.
        The AZURE_AD_ISSUER is https://sts.windows.net/TENANT_ID/
        The AZURE_AD_JWS_KEY_ENDPOINT is https://login.microsoftonline.com/TENANT_ID/discovery/v2.0/keys
        - The AZURE_AD_ISSUER is https://sts.windows.net/TENANT_ID/
        - The AZURE_AD_JWS_KEY_ENDPOINT is https://login.microsoftonline.com/TENANT_ID/discovery/v2.0/keys
        - Click on Endpoints in the Overview interface.
        - On the right-hand side, note the OAuth 2.0 authorization endpoint (v2) as the AZURE_AD_OAUTH_AUTHORIZATION_ENDPOINT and OAuth 2.0 token endpoint (v2) as the AZURE_AD_OAUTH_TOKEN_ENDPOINT.
        The endpoints should be similar to https://login.microsoftonline.com/90288a9b-97df-4c6d-b025-95713f21cef9/oauth2/v2.0/authorization and https://login.microsoftonline.com/90288a9b-97df-4c6d-b025-95713f21cef9/oauth2/v2.0/token.
        - The endpoints should be similar to https://login.microsoftonline.com/90288a9b-97df-4c6d-b025-95713f21cef9/oauth2/v2.0/authorization and https://login.microsoftonline.com/90288a9b-97df-4c6d-b025-95713f21cef9/oauth2/v2.0/token.
        - Click on **Expose an API **under Manage.
        - Click on the Set link next to Application ID URI to set the Application ID URI.
        The Application ID URI must be unique within your organization’s directory, such as https://your.company.com/4d2a8c2b-a5f4-4b86-93ca-294185f45f2e. This value will be referred to as the &lt;snowflake_application_id_uri&gt; in the subsequent configuration steps.
        - The Application ID URI must be unique within your organization’s directory, such as https://your.company.com/4d2a8c2b-a5f4-4b86-93ca-294185f45f2e. This value will be referred to as the &lt;snowflake_application_id_uri&gt; in the subsequent configuration steps.
        - To add a Snowflake Role as an OAuth scope for OAuth flows where the programmatic client acts on behalf of a user, click on Add a scope to add a scope representing the Snowflake role.
        Enter the scope by having the name of the Snowflake role with the session:scope: prefix. For example, for the Snowflake Analyst role, enter session:scope:analyst.
        Select who can consent.
        Enter a display name for the scope (e.g.: Account Admin).
        Enter a description for the scope (e.g.: Can administer the Snowflake account).
        Click Add Scope.
        Save the scope as AZURE_AD_SCOPE. It should be a concatenation of your Application ID URI and your Scope name
        - Enter the scope by having the name of the Snowflake role with the session:scope: prefix. For example, for the Snowflake Analyst role, enter session:scope:analyst.
        - Select who can consent.
        - Enter a display name for the scope (e.g.: Account Admin).
        - Enter a description for the scope (e.g.: Can administer the Snowflake account).
        - Click Add Scope.
        - Save the scope as AZURE_AD_SCOPE. It should be a concatenation of your Application ID URI and your Scope name
        - In the Overview section, copy the ClientID from the Application (client) ID field. This will be known as the OAUTH_CLIENT_ID in the following steps.
        - Click on Certificates &amp;amp; secrets and then New client secret.
        - Add a description of the secret.
        - Select 730 days (24 months). For testing purposes, select secrets that don’t expire soon.
        - Click Add. Copy the secret. This will be known as the OAUTH_CLIENT_SECRET in the following steps.
        - For programmatic clients that will request an Access Token on behalf of a user, configure Delegated permissions for Applications as follows.
        Click on API Permissions.
        Click on Add Permission.
        Click on My APIs.
        Click on the Snowflake OAuth Resource that you created in Configure the OAuth resource in Azure AD.
        Click on the Delegated Permissions box.
        Check on the Permission related to the Scopes defined in the Application that you wish to grant to this client.
        Click Add Permissions.
        Click on the Grant Admin Consent button to grant the permissions to the client. Note that for testing purposes, permissions are configured this way. However, in a production environment, granting permissions in this manner is not advisable.
        Click Yes.
        - Click on API Permissions.
        - Click on Add Permission.
        - Click on My APIs.
        - Click on the Snowflake OAuth Resource that you created in Configure the OAuth resource in Azure AD.
        - Click on the Delegated Permissions box.
        - Check on the Permission related to the Scopes defined in the Application that you wish to grant to this client.
        - Click Add Permissions.
        - Click on the Grant Admin Consent button to grant the permissions to the client. Note that for testing purposes, permissions are configured this way. However, in a production environment, granting permissions in this manner is not advisable.
        - Click Yes.
        Once the App Registration is complete in Azure Entra ID, the next step is to link that App Registration to Snowflake via an External OAuth Security Integration. The external_oauth_audience_list parameter of the security integration must match the Application ID URI that you specified while configuring Azure Entra ID.
        The Issuer and the JWS Keys endpoint will also come from values collected in the previous steps. The User Mapping Attribute can either be set to EMAIL_ADDRESS or LOGIN_NAME, and this is how user’s Microsoft login credentials will be mapped to their user in Snowflake to ensure permissions in Snowflake are honored by the access token issued to ChatGPT.
        ## Middleware information:
        Make sure you go through the following steps in your Azure environment:
        - Azure Portal or VS Code with access to create Azure Function Apps and Azure Entra App Registrations
        - There is a detailed section in this guide related to deploying and designing the function required to wrap the response from Snowflake in order to return the query results as a CSV to ChatGPT. The Azure Function App allows your GPT to ingest larger datasets as ChatGPT can ingest more data from files responses rather than from application/json payloads. Additionally, those datasets will only be available for Data Analysis (aka Code Interpreter) with a response formatted as a CSV file.
        ## Azure Function App
        Now that we have the GPT created and handled Azure/Snowflake authentication, we can create the Azure Function App itself to execute the SQL query and handle the response formatting enabling the GPT to download the result as a CSV for use with Data Analysis.
        Follow this Azure Cookbook Guide for further details deploying an Azure Function App. Below you will find sample code to add to the function.
        This code is meant to be directional - while it should work out of the box, you should customize it based on the needs specific to your GPT and your IT setup.
        ## Application Code
        You’ll need to setup the following flows in your Azure Function App:
        - Extracting the token from the HTTP request and using it to connect to Snowflake
        - Executing the SQL query and writing the results to a CSV
        - Temporarily storing that CSV in Blob Storage*
        - Generating a pre-signed URL to access that CSV securely*
        - Responding with an openaiFileResponse
        *These steps may not be required if you use the file stream option instead of the url option for returning files to your GPT. More on this below.
        Ensure you have the necessary libraries installed and imported into your script. In addition to Python standard libraries, this sample script leveraged the following:
        To connect to Snowflake, you’ll need to extract the access token assigned from Azure Entra ID from the Authorization header and use that token when connecting to the Snowflake server.
        In this this example, Snowflake usernames are email addresses which simplifies the mapping of the Entra ID user extracted from the HTTP access token to the Snowflake user ID needed to connect. If this is not the case for your organization, you can map email addresses to Snowflake user IDs in your Python application.
        My application was built to interface with a single Snowflake Account (i.e. ab12345.eastus2.azure) and Warehouse. If you need to access multiple accounts or warehouses, you may consider passing these parameters in your GPT action parameters so you can extract them from the HTTP request.
        Once you connect to Snowflake you’ll need to execute the query and store the results into a CSV. While the role in Snowflake should prevent any chance of harmful queries, you may want to sanitize your query in your application (not included below) just as you would any other programmatic SQL query execution.
        There are 2 methods for returning files to ChatGPT for processing. You can either stream the base64 encoded data along with the mimeType and file name in the openaiFileResponse list response, or you can return a list of URLs. In this solution we’ll focus on the latter.
        To do this, you’ll need to upload the CSV to Azure Blob Storage and return a pre-signed URL for accessing that file securely in ChatGPT. It is important to note that in order to download a URL in ChatGPT, you’ll need to ensure that URL includes a content_type and content_disposition, as in the below example. If you’d like to inspect whether a URL has the necessary headers, you can use curl -I &lt;url&gt; from any terminal.
        You’ll need to get a connection String for your Azure storage bucket, as per instructions here.
        Lastly, you’ll need to format the response appropriately to instruct ChatGPT to process that response as a file or series of files. The openaiFileResponse is a list which can include up to 10 URLs (or base64 encodings if using the inline option).
        There are a lot of moving pieces to this application, so testing your Azure Function App can be important. ChatGPT can be a difficult testing grounds given that requests and responses can sometimes be more opaque than needed for debugging. Initial testing of your application through cURL or Postman to invoke the HTTP request from a more controlled environment will allow you to debug and triage issues more easily. Once you determine that responses are being returned as expected in those tools, you are ready to build your GPT.
        ## Custom GPT Instructions
        Once you&#39;ve created a Custom GPT, use the text below in the Instructions panel for inspiration. Have questions? Check out Getting Started Example to see how this step works in more detail.
        It is important that ChatGPT understands your table schema to properly form SQL queries. There are different methods for doing so, and this Instruction set represents the most direct way. We are working to publish additional instructions for different versions of Snowflake GPTs you may want to build to allow for working with multiple different tables, schemas and databases, or to even learn dynamically for schemas that tend to change over time.
        Below are some basic instructions when working with a single schema and table. This GPT has been optimized for a single use case (analyzing flight data from January 2013 out of NYC) which allows for the most simple instructions to provide the most reliable GPT performance.
        You are an expert at writing SQL queries to fetch data from Snowflake. You help users convert their prompts into SQL queries. Any question around flight data will be converted into a Snowflake SQL query that hits the table FLIGHTS.PUBLIC.JAN_2013_NYC. Pass any query into the &quot;sql_query&quot; parameter
        The schema of the table includes
        When a user asks for data around flights, perform the following:
        - Use the executeSQL action to send a POST request to the Azure function endpoint
        - Receive the file that is returned as part of the Action response. Display it as a spreadsheet
        - Perform analysis on the file and provide the necessary information that the user has asked for
        The user will wish to ask questions about the data in code interpreter, so use that for any data analysis insights from the dataset you pulled.
        ## OpenAPI Schema
        Once you&#39;ve created a Custom GPT, copy the text below in the Actions panel, replacing the placeholder values with your specific function details and updating your parameters based on any additional inputs you built into your Azure Function App.
        Have questions? Check out Getting Started Example to see how this step works in more detail.
        ## FAQ &amp;amp; Troubleshooting
        - Files returned to ChatGPT are limited in size to 10MB. Your request may fail if the file returned is larger than that. Ensure to include LIMITs on your SQL commands if you find you are running into these limitations.
        - Why is the Azure Function App requred in the first place? ChatGPT’s Data Analysis feature (aka Code Interpreter) depends on a secure Python environment that is separate from the model’s context window. Data passed to Data Analysis must be done so by uploading a file today. GPT actions returning data must then return that data as a CSV or other data file type. In order to return a file via GPT action, the response must be wrapped in an openaiFileResponse object. This requires custom code to properly format the response.
        - My company uses a different cloud provider than Azure. For connecting other middleware functions to ChatGPT via GPT action, please refer to other AWS or GCP middleware cookbooks. You can use the concepts discussed in this cookbook to advise on considerations when building your middleware app, but connecting that middleware to Snowflake may be different for different cloud providers. For example, Snowflake built an External OAuth integration specifically for linking with Azure Entra ID.
        - How do I limit the datasets that my GPT has access to? It can be imporant to limit the scope of access ChatGPT has within Snowflake. There are a few ways to do this:
        Snowflake roles can limit who has access to which tables, and will be respected by the GPT user’s access token provisioned by Azure Entra ID
        In your middleware function you can add sanity checks to verify the tables accessed are approved by for that application
        You may want to generate an entirely new Database/Warehouse specific to integrating with ChatGPT that is scrubbed of anything sensitive, such as PII.
        - Snowflake roles can limit who has access to which tables, and will be respected by the GPT user’s access token provisioned by Azure Entra ID
        - In your middleware function you can add sanity checks to verify the tables accessed are approved by for that application
        - You may want to generate an entirely new Database/Warehouse specific to integrating with ChatGPT that is scrubbed of anything sensitive, such as PII.
        - Schema calls the wrong warehouse or dataset: If ChatGPT calls the wrong warehouse or database, consider updating your instructions to make it more explicit either (a) which warehouse / database should be called or (b) to require the user provide those exact details before it runs the query
        Are there integrations that you’d like us to prioritize? Are there errors in our integrations? File a PR or issue in our github, and we’ll take a look.
        &lt;/url&gt;&lt;/snowflake_application_id_uri&gt;&lt;/snowflake_application_id_uri&gt;</description>
      <link>https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_snowflake_middleware</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_snowflake_middleware</guid>
      <pubDate>Tue, 13 Aug 2024 16:00:00 GMT</pubDate>
      <category>ChatGPT</category>
      <category>GPT actions library</category>
    </item>
    <item>
      <title>GPT Actions library (Middleware) - Google Cloud Function</title>
      <description>This page provides an instruction &amp;amp; guide for developers building middleware to connect a GPT Action to a specific application. Before you proceed, make sure to first familiarize yourself with the following information:
        - Introduction to GPT Actions
        - Introduction to GPT Actions Library
        - Example of Building a GPT Action from Scratch
        This particular GPT Action provides an overview of how to build an Google Cloud Function, Google&#39;s cloud-based function builder. This documentation helps a user set up an OAuth-protected Google Cloud Function to connect to a GPT Action, and to a sample application.
        ## Value + Example Business Use Cases
        Value: Users can now leverage ChatGPT&#39;s natural language capability to connect directly to Google Cloud Function. This can in a few ways:
        - 100k character limit in GPT Actions: users can use the middleware to pre-process the text response from an API. For example, you can use OpenAI’s API in the middleware to summarize the text before sending it back to ChatGPT.
        - Typically for actions, users are relying on the SaaS API to return text. You can convert the response for the vendor API into easily digestible text, and it can handle different data types such as structured and unstructured data.
        - It can return files instead of just text. This can be useful to surface CSV files for Data Analysis, or bring back an PDF file and ChatGPT will treat it like an upload.
        Example Use Cases:
        - A user needs to look up query Google Cloud SQL, but needs a middleware app between ChatGPT and Google Cloud SQL
        - A user has built several steps in a row in a Google Cloud function, and needs to be able to kick off that process using ChatGPT
        ## Application Key Links
        Check out these links from the application before you get started:
        - Application Website: https://cloud.google.com/functions/docs
        - Application API Documentation: https://cloud.google.com/functions/docs/writing/write-http-functions
        ## Application Prerequisites
        Before you get started, make sure you go through the following steps in your application environment:
        - Google Cloud Console with access to create Google Cloud Functions and Google Cloud APIs (you will need this to set up the OAuth Client)
        ## Installing the app
        There are 3 options to create and deploy the Google Cloud Functions
        - IDE - create using your favorite IDE, e.g. VS Code
        - Google Cloud Console - create using your browser
        - Google Cloud CLI (gcloud) - create through command line
        You can read up on the supported runtimes here
        See Google&#39;s documentation here for how to deploy using VSCode. If you have familiarity with this approach, feel free to use it.
        See the documentation here for how to deploy using the Google Cloud Console.
        See the documentation here for how to deploy using the Google Cloud Console. We’ll walk through an example here step by step.
        Follow the steps here that are relevant to the OS you are runnning. The last step of this process is for you to run gcloud init and sign in to your Google account
        In this example, we will be setting up a Node.js environment.
        Initialize the Node.js project
        Accept the default values for npm init
        Create the index.js file
        This step below will install and add the necessary dependencies in your package.json file
        ## Custom GPT Instructions
        Once you&#39;ve created a Custom GPT, copy the text below in the Instructions panel. Have questions? Check out Getting Started Example to see how this step works in more detail.
        ## OpenAPI Schema
        Once you&#39;ve created a Custom GPT, copy the text below in the Actions panel. Have questions? Check out Getting Started Example to see how this step works in more detail.
        Below is an example of what connecting to this Middlware might look like. You&#39;ll need to insert your application&#39;s &amp;amp; function&#39;s information in this section.
        Below are instructions on setting up authentication with this 3rd party application. Have questions? Check out Getting Started Example to see how this step works in more detail.
        ## In Google Cloud Console
        In Google Cloud Console, you need to create OAuth client ID credentials. To navigate to the right page search for &quot;Credentials&quot; in Google Cloud Console or enter https://console.cloud.google.com/apis/credentials?project=&lt;your_project_id&gt; in your browser. You can read more about it here.
        Click on &quot;CREATE CREDENTIALS&quot; and select &quot;Oauth client ID&quot;. Select &quot;Web Application&quot; for &quot;Application type&quot; and enter the name of your application (see below).
        In the &quot;OAuth client created&quot; modal dialog, please take note of the
        - Client ID
        - Client secret
        ## In ChatGPT (refer to Step 2 in the Getting Started Example)
        In ChatGPT, click on &quot;Authentication&quot; and choose &quot;OAuth&quot;. Enter in the information below.
        - Client ID: see step above
        - Client Secret: see step above
        - Authorization URL: https://accounts.google.com/o/oauth2/auth
        - Token URL: https://oauth2.googleapis.com/token
        - Scope: https://www.googleapis.com/auth/userinfo.email
        ## Back in Google Cloud Console (while referring to Step 4 in the Getting Started Example)
        Edit the OAuth 2.0 Client ID you create in Google Cloud earlier and add the callback URL you received after creating your custom action.
        ## Test the GPT
        You are now ready to test out the GPT. You can enter a simple prompt like &quot;Test Integration&quot; and expect to see the following:
        - Request to sign into Google
        - Allow request to your Google Function
        - Response from ChatGPT showing the response from your function - e.g. &quot;You have connected as an authenticated user to Google Functions&quot;
        Are there integrations that you’d like us to prioritize? Are there errors in our integrations? File a PR or issue in our github, and we’ll take a look.
        &lt;/your_project_id&gt;</description>
      <link>https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_middleware_google_cloud_function</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_middleware_google_cloud_function</guid>
      <pubDate>Sat, 10 Aug 2024 16:00:00 GMT</pubDate>
      <category>ChatGPT</category>
      <category>GPT actions library</category>
    </item>
    <item>
      <title>GPT Actions library - Google Drive</title>
      <description>This page provides an instruction &amp;amp; guide for developers building a GPT Action for a specific application. Before you proceed, make sure to first familiarize yourself with the following information:
        - Introduction to GPT Actions
        - Introduction to GPT Actions Library
        - Example of Building a GPT Action from Scratch
        This particular GPT Action provides an overview of how to connect to Google Drive, Google’s File storage system. This action will allow you to list and query against file names, load the file content into your GPT, and ultimately use that data as context in ChatGPT. This set of actions is extensible by additional methods found via the Google Drive API. This is great if you want a generalist GPT that can read smaller files, such as:
        - Meetings minutes
        - Product design documents
        - Short memos
        - Frequently-asked questions
        For something that wants to read longer memos such as entire books, complex CSVs with many rows, we suggest building a Google Docs or Google Sheets-specific GPT.
        ## Value + Example business case
        Users can now leverage ChatGPT&#39;s natural language capability to connect directly to files in Google Drive
        Example Use Cases:
        - A user needs to look up which files relate to a certain topic
        - A user needs an answer to a critical question, buried deep in documents
        ## Application Key Links
        Check out these links from the application before you get started:
        - Application Website: https://www.google.com/drive/
        - Application API Documentation: https://developers.google.com/drive/api/guides/about-sdk
        ## Application Prerequisites
        Before you get started, make sure you have a Google Cloud account and that the Drive API is enabled:
        - Set up a Google Cloud project
        - Enable Google Drive API from Google API Library
        - If application’s “Publishing Status” is “Testing”, ensure users are added to your application
        ## Example Custom GPT Instructions
        Once you&#39;ve created a Custom GPT, to get started, copy the text below in the Instructions panel. You may have to add additional context specific to your use case. In this way, it is worth testing additional instructions you add to optimize for clarity and accuracy. Have questions? Check out Getting Started Example to see how this step works in more detail.
        ## Example OpenAPI Schema
        Once you&#39;ve created a Custom GPT, copy the text below in the Actions panel. This offers an example of what you could include within functions, but . Have questions? Check out Getting Started Example to see how this step works in more detail. As well, try ActionsGPT, a CustomGPT OpenAI created to help with Actions. The three examples are:
        - List Files: this is the core action that lists the files in your drive. Within this are a few parameters, such as q, includeItemsFromAllDrives,supportsAllDrives
        - Get Metadata: in case list doesn&#39;t work, this can offer as a backup based on certain results - for example, if users attempt to make a search via “meeting from last week”, etc
        - Export: exports in a byte content. For more reading, please consult https://developers.google.com/drive/api/reference/rest/v3/files/export
        Generally, if ‘get’ is used, the model will attempt to download the file, which may be undesirable. Thus, Export is recommended instead.
        Below are instructions on setting up authentication with this 3rd party application. Have questions? Check out Getting Started Example to see how this step works in more detail.
        ## Pre-Action Steps
        Before you set up authentication in ChatGPT, please take the following steps in the application.
        - Go to the Google Cloud Console
        - Navigate to Enabled API &amp;amp; Services and enable Google Drive API
        - Within the search bar, search Google Drive API:
        - Create new OAuth credentials (or use an existing one). Note that if you haven’t set up an OAuth credentials screen, you will need to do that.
        - Within this process, you will need to grant access to the correct permissions, establish the primary tester as a testing email if Testing is enabled, and set up the OAuth rate limit.
        - Next, go to credentials and click “+ Create Credentials” and click “Create Credentials”. Below is an example of what this screen looks like when it’s already set up.
        - Locate your OAuth Client ID &amp;amp; Client Secret and store both values securely (see screenshot below)
        ## In ChatGPT
        In ChatGPT, click on &quot;Authentication&quot; and choose &quot;OAuth&quot;. Enter in the information below.
        - Client ID: use Client ID from steps above
        - Client Secret: use Client Secret from steps above
        - Authorization URL: https://accounts.google.com/o/oauth2/auth
        - Token URL: https://oauth2.googleapis.com/token
        - Scope: https://www.googleapis.com/auth/drive
        Note: for a list of more detailed scopes enabled, please refer to Google’s OAuth 2.0 guide.
        - Note: for a list of more detailed scopes enabled, please refer to Google’s OAuth 2.0 guide.
        - Token: Default (POST)
        - Privacy Policy: https://policies.google.com/privacy?hl=en-US
        ## Post-Action Steps
        Once you&#39;ve set up authentication in ChatGPT, follow the steps below in the application to finalize the Action.
        - Copy the callback URL from the GPT Action
        - In the “Authorized redirect URIs”, add your callback URL
        ## FAQ &amp;amp; Troubleshooting
        - Callback URL Error: If you get a callback URL error in ChatGPT, pay close attention to the screenshot above. You need to add the callback URL directly into GCP for the action to authenticate correctly.
        Are there integrations that you’d like us to prioritize? Are there errors in our integrations? File a PR or issue in our GitHub, and we’ll take a look.
      </description>
      <link>https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_google_drive</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_google_drive</guid>
      <pubDate>Sat, 10 Aug 2024 16:00:00 GMT</pubDate>
      <category>ChatGPT</category>
      <category>GPT actions library</category>
    </item>
    <item>
      <title>GPT Actions library - AWS Redshift</title>
      <description>This page provides an instruction &amp;amp; guide for developers building a GPT Action for a specific application. Before you proceed, make sure to first familiarize yourself with the following information:
        - Introduction to GPT Actions
        - Introduction to GPT Actions Library
        - Example of Building a GPT Action from Scratch
        This solution enables a GPT action to retrieve data from Redshift and perform data analysis.It uses AWS Functions, performing every action from AWS ecosystem and network. The middleware (AWS function) will perform the SQL query, wait for its completion and return the data as a file. The code is provided for information purpose only and should be modified to your needs.
        This solution uses the ability to retrieve files in Actions and use them as if you had uploaded them directly to a conversation.
        This solution highlight a connection to Redshift serverless, the integration with a provisioned Redshift might differ slighltly to retrieve networks and set-up connection, the overall code and (minimal) integration should be similar.
        ## Value &amp;amp; Example Business Use Cases
        Value: Leverage ChatGPT&#39;s natural language capabilities to connect to Redshift&#39;s DWH.
        Example Use Cases:
        - Data scientists can connect to tables and run data analyses using ChatGPT&#39;s Data Analysis
        - Citizen data users can ask basic questions of their transactional data
        - Users gain more visibility into their data &amp;amp; potential anomalies
        ## Application Prerequisites
        Before you get started, make sure that:
        - You have access to a Redshift environment
        - You have the rights to deploy AWS function in the same VPC (Virtual Private Network)
        - Your AWS CLI is authenticated
        ## Install required libraries
        - Install AWS CLI, required for AWS SAM (docs)
        - Install AWS SAM CLI (docs)
        - Install Python
        - Install yq docs
        ## Middleware function
        To create a function, follow the steps in the AWS Middleware Action cookbook.
        To deploy specifically an application that connects to Redshift, use the following code instead of the &quot;hello-world&quot; GitHub repository referenced in the Middleware AWS Function cookbook. You can either clone the repository or take the code pasted below and modify it to your needs.
        To get the code, you can clone openai-cookbook repository and navigate to the redshift-middleware directory
        ## Retrieve VPC information
        We will need to connnect our function to Redshift, therefore we need to find the network used by Redshift. You can find this on your Redshift interface the AWS console, under Amazon Redshift Serverless &amp;gt; Workgroup configuration &amp;gt; your_workgroup &amp;gt; Data access, or through the CLI:
        ## Set up AWS function
        Copy env.sample.yaml to env.yaml and replace with the values obtained above. You will need a Redshift user with access to your DB/schema.
        Fill in env.yaml with the values retrieved by the previous command as well as your credentials to Redshift.
        Alternatively, you can create a file named env.yaml manually and fill the following variables:
        This file will be used to deploy your function with parameters, as shown below:
        The template.yaml has the following content:
        Retrieve the URL information from the previous command output, you can then run a cURL request, which should return data in a file format:
        ## Custom GPT Instructions
        Once you&#39;ve created a Custom GPT, copy the text below in the Instructions panel.
        ## OpenAPI Schema
        Once you&#39;ve created a Custom GPT, copy the text below in the Actions panel.
        This expects a response that matches the file retrieval structure in our doc here and passes in a query as a parameter to execute.
        Make sure to follow the steps in the AWS Middleware cookbook to set up authentication.
        You now have deployed a GPT that uses a middleware in AWS, in an authenticated manner, that&#39;s able to connect to Redsfhit. Users with access (that are in Cognito) can now query y

github-actions[bot] avatar Oct 19 '24 13:10 github-actions[bot]

Successfully generated as following:

http://localhost:1200/cookbook - Success ✔️
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <title>OpenAI Cookbook</title>
    <link>https://cookbook.openai.com/</link>
    <atom:link href="http://localhost:1200/cookbook" rel="self" type="application/rss+xml"></atom:link>
    <description>OpenAI Cookbook - Powered by RSSHub</description>
    <generator>RSSHub</generator>
    <webMaster>[email protected] (RSSHub)</webMaster>
    <language>en</language>
    <lastBuildDate>Sun, 20 Oct 2024 02:52:06 GMT</lastBuildDate>
    <ttl>5</ttl>
    <item>
      <title>Leveraging model distillation to fine-tune a model</title>
      <description>OpenAI recently released Distillation which allows to leverage the outputs of a (large) model to fine-tune another (smaller) model. This can significantly reduce the price and the latency for specific tasks as you move to a smaller model. In this cookbook we&#39;ll look at a dataset, distill the output of gpt-4o to gpt-4o-mini and show how we can get significantly better results than on a generic, non-distilled, 4o-mini.
        We&#39;ll also leverage Structured Outputs for a classification problem using a list of enum. We&#39;ll see how fine-tuned model can benefit from structured output and how it will impact the performance. We&#39;ll show that Structured Ouputs work with all of those models, including the distilled one.
        We&#39;ll first analyze the dataset, get the output of both 4o and 4o mini, highlighting the difference in performance of both models, then proceed to the distillation and analyze the performance of this distilled model.
        Prerequisites
        Let&#39;s install and load dependencies.
        Make sure your OpenAI API key is defined in your environment as &quot;OPENAI_API_KEY&quot; and it&#39;ll be loaded by the client directly.
        Loading and understanding the dataset
        For this cookbook, we&#39;ll load the data from the following Kaggle challenge: https://www.kaggle.com/datasets/zynicide/wine-reviews.
        This dataset has a large number of rows and you&#39;re free to run this cookbook on the whole data, but as a biaised french wine-lover, I&#39;ll narrow down the dataset to only French wine to focus on less rows and grape varieties.
        We&#39;re looking at a classification problem where we&#39;d like to guess the grape variety based on all other criterias available, including description, subregion and province that we&#39;ll include in the prompt. It gives a lot of information to the model, you&#39;re free to also remove some information that can help significantly the model such as the region in which it was produced to see if it does a good job at finding the grape.
        Let&#39;s filter the grape varieties that have less than 5 occurences in reviews.
        Let&#39;s proceed with a subset of 500 random rows from this dataset.
        Let&#39;s retrieve all grape varieties to include them in the prompt and in our structured outputs enum list.
        Generating the prompt
        Let&#39;s build out a function to generate our prompt and try it for the first wine of our list.
        To get a understanding of the cost before running the queries, you can leverage tiktoken to understand the number of tokens we&#39;ll send and the cost associated to run this. This will only give you an estimate for to run the completions, not the fine-tuning process (used later in this cookbook when running the distillation), which depends on other factors such as the number of epochs, training set etc.
        Preparing functions to Store Completions
        As we&#39;re looking at a limited list of response (enumerate list of grape varieties), let&#39;s leverage structured outputs so we make sure the model will answer from this list. This also allows us to compare the model&#39;s answer directly with the grape variety and have a deterministic answer (compared to a model that could answer &quot;I think the grape is Pinot Noir&quot; instead of just &quot;Pinot noir&quot;), on top of improving the performance to avoid grape varieties not in our dataset.
        If you want to know more on Structured Outputs you can read this cookbook and this documentation guide.
        To distill a model, you need to store all completions from a model, allowing you to give it as a reference to the smaller model to fine-tune it. We&#39;re therefore adding a store=True parameter to our client.chat.completions.create method so we can store those completions from gpt-4o.
        We&#39;re going to store all completions (even 4o-mini and our future fine-tuned model) so we are able to run Evals from OpenAI platform directly.
        When storing those completions, it&#39;s useful to store them with a metadata tag, that will allow filtering from the OpenAI platform to run distillation &amp;amp; evals on the specific set of completions you&#39;d like to run those.
        Parallel processing
        As we&#39;ll run this on a large number of rows, let&#39;s make sure we run those completions in parallel and use concurrent futures for this. We&#39;ll iterate on our dataframe and output progress every 20 rows. We&#39;ll store the completion from the model we run the completion for in the same dataframe using the column name {model}-variety.
        Let&#39;s try out our call model function before processing the whole dataframe and check the output.
        Great! We confirmed we can get a grape variety as an output, let&#39;s now process the dataset with both gpt-4o and gpt-4o-mini and compare the results.
        Comparing gpt-4o and gpt-4o-mini
        Now that we&#39;ve got all chat completions for those two models ; let&#39;s compare them against the expected grape variety and assess their accuracy at finding it. We&#39;ll do this directly in python here as we&#39;ve got a simple string check to run, but if your task involves more complex evals you can leverage OpenAI Evals or our open-source eval framework.
        We can see that gpt-4o is better a finding grape variety than 4o-mini (12.80% higher or almost 20% relatively to 4o-mini!). Now I&#39;m wondering if we&#39;re making gpt-4o drink wine during training!
        Distilling gpt-4o outputs to gpt-4o-mini
        Let&#39;s assume we&#39;d like to run this prediction often, we want completions to be faster and cheaper, but keep that level of accuracy. That&#39;d be great to be able to distill 4o accuracy to 4o-mini, wouldn&#39;t it? Let&#39;s do it!
        We&#39;ll now go to OpenAI Stored completions page: https://platform.openai.com/chat-completions.
        Let&#39;s select the model gpt-4o (make sure to do this, you don&#39;t want to distill the outputs of 4o-mini that we ran). Let&#39;s also select the metadata distillation: wine-distillation to get only stored completions ran from this cookbook.
        Once you&#39;ve selected completions, you can click on &quot;Distill&quot; on the top right corner to fine-tune a model based on those completions. Once we&#39;ve done that, a file to run the fine-tuning process will automatically be created. Let&#39;s then select gpt-4o-mini as the base model, keep the default parameters (but you&#39;re free to change them or iterate with it to improve performance).
        Once the fine-tuning job is starting, you can retrieve the fine tuning job ID from the fine-tuning page, we&#39;ll use it to monitor status of the fine-tuned job as well as retrieving the fine-tuned model id once done.
        Running completions for the distilled model
        Now that we&#39;ve got our model fine-tuned, we can use this model to run completions and compare accuracy with both gpt4o and gpt4o-mini.
        Let&#39;s grab a different subset of french wines (as we restricted the outputs to french grape varieties, without outliers, we&#39;ll need to focus our validation dataset to this too). Let&#39;s run this on 300 entries for each models.
        Let&#39;s compare accuracy of models
        That&#39;s almost a 22% relative improvement over the non-distilled gpt-4o-mini! 🎉
        Our fine-tuned model performs way better than gpt-4o-mini, while having the same base model. We&#39;ll be able to use this model to run inferences at a lower cost and lower latency for future grape variety prediction.
      </description>
      <link>https://cookbook.openai.com/examples/leveraging_model_distillation_to_fine-tune_a_model</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/leveraging_model_distillation_to_fine-tune_a_model</guid>
      <pubDate>Tue, 15 Oct 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Fine-tuning</category>
    </item>
    <item>
      <title>Orchestrating Agents: Routines and Handoffs</title>
      <description>When working with language models, quite often all you need for solid performance is a good prompt and the right tools. However, when dealing with many unique flows, things may get hairy. This cookbook will walk through one way to tackle this.
        We&#39;ll introduce the notion of routines and handoffs, then walk through the implementation and show how they can be used to orchestrate multiple agents in a simple, powerful, and controllable way.
        Finally, we provide a sample repo, Swarm, that implements these ideas along with examples.
        Let&#39;s start by setting up our imports.
        Routines
        The notion of a &quot;routine&quot; is not strictly defined, and instead meant to capture the idea of a set of steps. Conretely, let&#39;s define a routine to be a list of instructions in natural langauge (which we&#39;ll represent with a system prompt), along with the tools necessary to complete them.
        Let&#39;s take a look at an example. Below, we&#39;ve defined a routine for a customer service agent instructing it to triage the user issue, then either suggest a fix or provide a refund. We&#39;ve also defined the necessary functions execute_refund and look_up_item. We can call this a customer service routine, agent, assistant, etc –&amp;nbsp;however the idea itself is the same: a set of steps and the tools to execute them.
        The main power of routines is their simplicity and robustness. Notice that these instructions contain conditionals much like a state machine or branching in code. LLMs can actually handle these cases quite robustly for small and medium sized routine, with the added benefit of having &quot;soft&quot; adherance –&amp;nbsp;the LLM can naturally steer the conversation without getting stuck in dead-ends.
        Executing Routines
        To execute a routine, let&#39;s implement a simple loop that:
        Gets user input.
        Appends user message to messages.
        Calls the model.
        Appends model response to messages.
        As you can see, this currently ignores function calls, so let&#39;s add that.
        Models require functions to be formatted as a function schema. For convenience, we can define a helper function that turns python functions into the corresponding function schema.
        For example:
        Now, we can use this function to pass the tools to the model when we call it.
        Finally, when the model calls a tool we need to execute the corresponding function and provide the result back to the model.
        We can do this by mapping the name of the tool to the python function in a tool_map, then looking it up in execute_tool_call and calling it. Finally we add the result to the conversation.
        In practice, we&#39;ll also want to let the model use the result to produce another response. That response might also contain a tool call, so we can just run this in a loop until there are no more tool calls.
        If we put everything together, it will look something like this:
        Now that we have a routine, let&#39;s say we want to add more steps and more tools. We can up to a point, but eventually if we try growing the routine with too many different tasks it may start to struggle. This is where we can leverage the notion of multiple routines – given a user request, we can load the right routine with the appropriate steps and tools to address it.
        Dynamically swapping system instructions and tools may seem daunting. However, if we view &quot;routines&quot; as &quot;agents&quot;, then this notion of handoffs allow us to represent these swaps simply –&amp;nbsp;as one agent handing off a conversation to another.
        Handoffs
        Let&#39;s define a handoff as an agent (or routine) handing off an active conversation to another agent, much like when you get transfered to someone else on a phone call. Except in this case, the agents have complete knowledge of your prior conversation!
        To see handoffs in action, let&#39;s start by defining a basic class for an Agent.
        Now to make our code support it, we can change run_full_turn to take an Agent instead of separate system_message and tools:
        We can now run multiple agents easily:
        Great! But we did the handoff manually here –&amp;nbsp;we want the agents themselves to decide when to perform a handoff. A simple, but surprisingly effective way to do this is by giving them a transfer_to_XXX function, where XXX is some agent. The model is smart enough to know to call this function when it makes sense to make a handoff!
        Handoff Functions
        Now that agent can express the intent to make a handoff, we must make it actually happen. There&#39;s many ways to do this, but there&#39;s one particularly clean way.
        For the agent functions we&#39;ve defined so far, like execute_refund or place_order they return a string, which will be provided to the model. What if instead, we return an Agent object to indate which agent we want to transfer to? Like so:
        We can then update our code to check the return type of a function response, and if it&#39;s an Agent, update the agent in use! Additionally, now run_full_turn will need to return the latest agent in use in case there are handoffs. (We can do this in a Response class to keep things neat.)
        Now for the updated run_full_turn:
        Let&#39;s look at an example with more Agents.
        Finally, we can run this in a loop (this won&#39;t run in python notebooks, so you can try this in a separate python file):
        Swarm
        As a proof of concept, we&#39;ve packaged these ideas into a sample library called Swarm. It is meant as an example only, and should not be directly used in production. However, feel free to take the ideas and code to build your own!
      </description>
      <link>https://cookbook.openai.com/examples/orchestrating_agents</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/orchestrating_agents</guid>
      <pubDate>Wed, 09 Oct 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Functions</category>
    </item>
    <item>
      <title>Prompt Caching 101</title>
      <description>OpenAI offers discounted prompt caching for prompts exceeding 1024 tokens, resulting in up to an 80% reduction in latency for longer prompts over 10,000 tokens. By caching repetitive information across LLM API requests, you can greatly reduce both latency and costs. Prompt caching is scoped at the organization level, meaning only members of the same organization can access shared caches. Additionally, caching is eligible for zero data retention, as no data is stored during the process.
        Prompt caching automatically activates for prompts longer than 1024 tokens-- you don&#39;t have to change anything in your completions request. When an API request is made, the system first checks if the beginning portion (prefix) of the prompt has already been cached. If a match is found (cache hit), the cached prompt is used, leading to reduced latency and costs. If there&#39;s no match, the system processes the full prompt from scratch and caches the prefix for future use.
        With these benefits in mind, some of the key use cases where prompt caching can be especially advantageous are:
        Agents using tools and structured outputs: Cache the extended list of tools and schemas.
        Coding and writing assistants: Insert large sections or summaries of codebases and workspaces directly in prompts.
        Chatbots: Cache static portions of multi-turn conversations to maintain context efficiently over extended dialogues.
        In this cookbook, we&#39;ll go through a couple examples of caching tools and images. Recall that in general, you&#39;ll want to put static content like instructions and examples at the beginning of your prompt, and variable content, such as user-specific information, at the end. This also applies to images and tools, which must be identical even in their ordering between requests. All requests, including those with fewer than 1024 tokens, will display a cached_tokens field of the usage.prompt_tokens_details chat completions object indicating how many of the prompt tokens were a cache hit. For requests under 1024 tokens, cached_tokens will be zero. Caching discounts are based on the actual number of tokens processed, including those used for images, which also count toward your rate limits.
        Example 1: Caching tools and multi-turn conversations
        In this example, we define tools and interactions for a customer support assistant, capable of handling tasks such as checking delivery dates, canceling orders, and updating payment methods. The assistant processes two separate messages, first responding to an initial query, followed by a delayed response to a follow-up query.
        When caching tools, it is important that the tool definitions and their order remain identical for them to be included in the prompt prefix. To cache message histories in a multi-turn conversation, append new elements to the end of the messages array. In the response object and the output below, for the second completion run2, you can see that the cached_tokens value is greater than zero, indicating successful caching.
        Example 2: Images
        In our second example we include multiple image URLs of grocery items in the messages array, along with a user query, run three times with delays. Images—whether linked or encoded in base64 within user messages—qualify for caching. Make sure the detail parameter remains consistent, as it affects how images are tokenized. Note that GPT-4o-mini adds extra tokens to cover image processing costs, even though it uses a low-cost token model for text. Caching discounts are based on the actual number of tokens processed, including those used for images, which also count toward your rate limits.
        The output for this example shows that a cache was hit for the second run, however it was not hit for the third run because of a different first url (eggs_url instead of veggie_url), even though the user query is the same.
        Overall tips
        To get the most out of prompt caching, consider following these best practices:
        Place static or frequently reused content at the beginning of prompts: This helps ensure better cache efficiency by keeping dynamic data towards the end of the prompt.
        Maintain consistent usage patterns: Prompts that aren&#39;t used regularly are automatically removed from the cache. To prevent cache evictions, maintain consistent usage of prompts.
        Monitor key metrics: Regularly track cache hit rates, latency, and the proportion of cached tokens. Use these insights to fine-tune your caching strategy and maximize performance.
        By implementing these practices, you can take full advantage of prompt caching, ensuring that your applications are both responsive and cost-efficient. A well-managed caching strategy will significantly reduce processing times, lower costs, and help maintain smooth user experiences.
      </description>
      <link>https://cookbook.openai.com/examples/prompt_caching101</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/prompt_caching101</guid>
      <pubDate>Mon, 30 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
    </item>
    <item>
      <title>Using chained calls for o1 structured outputs</title>
      <description>The initially released versions (September 2024) of o1 reasoning models have advanced capabilities but do not have structured outputs support.
        This means that requests with o1 don&#39;t have reliable type-safety and rely on the prompt itself to return a useful JSON.
        In this guide, we&#39;ll explore two methods to prompt o1 models, specifically o1-preview, to return a valid JSON format when using the OpenAI API.
        Prompting
        The simplest way to return a JSON response using o1-preview is to explicitly prompt it.
        Let&#39;s run through an example of:
        Fetching a wikipedia page of companies
        Determining which could benefit the most from AI capabilities
        Returning them in a JSON format, which could then be ingested by other systems
        Note that the response is already quite good - it returns the JSON with the appropriate responses. However, it runs into the same pitfalls as existing use-cases of prompt-only JSON inference:
        You must manually process this JSON into your type-safe structure
        Model refusals are not explicitly returned from the API as a separate structure
        Structured Outputs
        Let&#39;s now do this with structured outputs. To enable this functionality, we’ll link the o1-preview response with a follow-up request to gpt-4o-mini, which can effectively process the data returned from the initial o1-preview response.
        Conclusion
        Structured outputs allow your code to have reliable type-safety and simpler prompting. In addition, it allows you to re-use your object schemas for easier integration into your existing workflows.
        The o1 class of models currently doesn&#39;t have structured outputs support, but we can re-use existing structured outputs functionality from gpt-4o-mini by chaining two requests together. This flow currently requires two calls, but the second gpt-4o-mini call cost should be minimal compared to the o1-preview/o1-mini calls.
      </description>
      <link>https://cookbook.openai.com/examples/o1/using_chained_calls_for_o1_structured_outputs</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/o1/using_chained_calls_for_o1_structured_outputs</guid>
      <pubDate>Wed, 25 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Reasoning</category>
    </item>
    <item>
      <title>Building a Bring Your Own Browser (BYOB) Tool for Web Browsing and Summarization</title>
      <description>Disclaimer: This cookbook is for educational purposes only. Ensure that you comply with all applicable laws and service terms when using web search and scraping technologies. This cookbook will restrict the search to openai.com domain to retrieve the public information to illustrate the concepts.
        Large Language Models (LLMs) such as GPT-4o have a knowledge cutoff date, which means they lack information about events that occurred after that point. In scenarios where the most recent data is essential, it&#39;s necessary to provide LLMs with access to current web information to ensure accurate and relevant responses.
        In this guide, we will build a Bring Your Own Browser (BYOB) tool using Python to overcome this limitation. Our goal is to create a system that provides up-to-date answers in your application, including the most recent developments such as the latest product launches by OpenAI. By integrating web search capabilities with an LLM, we&#39;ll enable the model to generate responses based on the latest information available online.
        While you can use any publicly available search APIs, we&#39;ll utilize Google&#39;s Custom Search API to perform web searches. The retrieved information from the search results will be processed and passed to the LLM to generate the final response through Retrieval-Augmented Generation (RAG).
        Bring Your Own Browser (BYOB) tools allow users to perform web browsing tasks programmatically. In this notebook, we&#39;ll create a BYOB tool that:
        #1. Set Up a Search Engine: Use a public search API, such as Google&#39;s Custom Search API, to perform web searches and obtain a list of relevant search results.
        #2. Build a Search Dictionary: Collect the title, URL, and a summary of each web page from the search results to create a structured dictionary of information.
        #3. Generate a RAG Response: Implement Retrieval-Augmented Generation (RAG) by passing the gathered information to the LLM, which then generates a final response to the user&#39;s query.
        Use Case
        In this cookbook, we&#39;ll take the example of a user who wants to list recent product launches by OpenAI in chronological order. Because the current GPT-4o model has a knowledge cutoff date, it is not expected that the model will know about recent product launches such as the o1-preview model launched in September 2024.
        Given the knowledge cutoff, as expected the model does not know about the recent product launches by OpenAI.
        Setting up a BYOB tool
        To provide the model with recent events information, we&#39;ll follow these steps:
        Step 1: Set Up a Search Engine to Provide Web Search Results
        Step 2: Build a Search Dictionary with Titles, URLs, and Summaries of Web Pages
        Step 3: Pass the information to the model to generate a RAG Response to the User Query
        Before we begin, ensure you have the following: Python 3.12 or later installed on your machine. You will also need a Google Custom Search API key and Custom Search Engine ID (CSE ID). Necessary Python packages installed: requests, beautifulsoup4, openai. And ensure the OPENAI_API_KEY is set up as an environment variable.
        Step 1: Set Up a Search Engine to Provide Web Search Results
        You can use any publicly available web search APIs to perform this task. We will configure a custom search engine using Google&#39;s Custom Search API. This engine will fetch a list of relevant web pages based on the user&#39;s query, focusing on obtaining the most recent and pertinent results.
        a. Configure Search API key and Function: Acquire a Google API key and a Custom Search Engine ID (CSE ID) from the Google Developers Console. You can navigate to this Programmable Search Engine Link to set up an API key as well as Custom Search Engine ID (CSE ID).
        The search function below sets up the search based on search term, the API and CSE ID keys, as well as number of search results to return. We&#39;ll introduce a parameter site_filter to restrict the output to only openai.com
        b. Identify the search terms for search engine: Before we can retrieve specific results from a 3rd Party API, we may need to use Query Expansion to identify specific terms our browser search API should retrieve. Query expansion is a process where we broaden the original user query by adding related terms, synonyms, or variations. This technique is essential because search engines, like Google&#39;s Custom Search API, are often better at matching a range of related terms rather than just the natural language prompt used by a user.
        For example, searching with only the raw query &quot;List the latest OpenAI product launches in chronological order from latest to oldest in the past 2 years&quot; may return fewer and less relevant results than a more specific and direct search on a succinct phrase such as &quot;Latest OpenAI product launches&quot;. In the code below, we will use the user&#39;s original search_query to produce a more specific search term to use with the Google API to retrieve the results.
        c. Invoke the search function: Now that we have the search term, we will invoke the search function to retrieve the results from Google search API. The results only have the link of the web page and a snippet at this point. In the next step, we will retrieve more information from the webpage and summarize it in a dictionary to pass to the model.
        Step 2: Build a Search Dictionary with Titles, URLs, and Summaries of Web Pages
        After obtaining the search results, we&#39;ll extract and organize the relevant information, so it can be passed to the LLM for final output.
        a. Scrape Web Page Content: For each URL in the search results, retrieve the web page to extract textual content while filtering out non-relevant data like scripts and advertisements as demonstrated in function retrieve_content.
        b. Summarize Content: Use an LLM to generate concise summaries of the scraped content, focusing on information pertinent to the user&#39;s query. Model can be provided the original search text, so it can focus on summarizing the content for the search intent as outlined in function summarize_content.
        c. Create a Structured Dictionary: Organize the data into a dictionary or a DataFrame containing the title, link, and summary for each web page. This structure can be passed on to the LLM to generate the summary with the appropriate citations.
        We retrieved the most recent results. (Note these will vary depending on when you execute this script.)
        Step 3: Pass the information to the model to generate a RAG Response to the User Query
        With the search data organized in a JSON data structure, we will pass this information to the LLM with the original user query to generate the final response. Now, the LLM response includes information beyond its original knowledge cutoff, providing current insights.
        Conclusion
        Large Language Models (LLMs) have a knowledge cutoff and may not be aware of recent events. To provide them with the latest information, you can build a Bring Your Own Browser (BYOB) tool using Python. This tool retrieves current web data and feeds it to the LLM, enabling up-to-date responses.
        The process involves three main steps:
        #1 Set Up a Search Engine: Use a public search API, like Google&#39;s Custom Search API, to perform web searches and obtain a list of relevant search results.
        #2 Build a Search Dictionary: Collect the title, URL, and a summary of each web page from the search results to create a structured dictionary of information.
        #3. Generate a RAG Response: Implement Retrieval-Augmented Generation (RAG) by passing the gathered information to the LLM, which then generates a final response to the user&#39;s query.
        By following these steps, you enhance the LLMs ability to provide up-to-date answers in your application that include the most recent developments, such as the latest product launches by OpenAI.
      </description>
      <link>https://cookbook.openai.com/examples/third_party/web_search_with_google_api_bring_your_own_browser_tool</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/third_party/web_search_with_google_api_bring_your_own_browser_tool</guid>
      <pubDate>Wed, 25 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
    </item>
    <item>
      <title>GPT Actions library - Canvas Learning Management System</title>
      <description>Table of Contents
        General App Information - Overview of Canvas LMS, its functionality, and the role of ChatGPT&#39;s Custom Actions to enhance educational experiences through AI integration.
        Authentication from ChatGPT to Canvas - Explanation of authentication methods (OAuth and User Generated Access Tokens) for connecting ChatGPT to Canvas, with detailed instructions for setting up each option.
        Sample Use Case: Student Course Assistant - Detailed example of using ChatGPT to assist students with course navigation, exam preparation, and personalized feedback, including specific API calls and workflows.
        Other Use Cases for Consideration - Additional potential integrations using the Canvas API, such as classroom analytics and report generation.
        Congratulations
        General App Information
        Canvas is a widely-used Learning Management System (LMS) designed to support online learning and teaching. It offers a robust set of tools for course management, content delivery, assessments, and student collaboration. Through the Canvas REST API, Canvas allows for extensive customization and integration with third-party applications, including AI-powered tools like ChatGPT.
        ChatGPT’s Custom Actions with Canvas enable educators to leverage AI to enhance course content, automate tasks, and provide personalized learning journeys for students. Examples include virtual teaching assistants based on active courses, as the capabilities are well-suited for pulling information in from Canvas to create an educational dialogue. ChatGPT with Custom Actions is not meant for automating the entire Canvas experience nor act as a replacement to many of its capabilities better suited for completion in the Canvas app.
        Authentication from ChatGPT to Canvas
        For a general overview on Authentication in Custom Actions, see the Action authentication documentation.
        There are two options for authentication in Canvas: 1) OAuth and 2) User Generated Access Tokens.
        For large-scale deployments, it is required to use OAuth for Action Authentication.
        If the user is considering a single-user deployment or does not have access to Admin Settings, they may consider User Generated Access Tokens. Be aware that any request made by the action will be made using the token the user generated, so Canvas will register all requests as the user&#39;s activity and use the user&#39;s permissions to complete them.
        Implementing OAuth for Canvas
        While this Canvas Cookbook does not use OAuth, any deployment with more than one user must use it. See OAuth for Canvas Documentation for a detailed walkthrough.
        Here are some things to keep in mind while implementing OAuth in a Canvas Custom Action:
        Access to Canvas’ Admin settings is required for OAuth in order to retrieve a Client ID and Client Secret.
        The Authorization URL will look like (make sure to update the Canvas Install URL): https:///login/oauth2/auth
        The Token URL will look like (make sure to update the Canvas Install URL): ttps:///login/oauth2/token
        Scopes may not need to be defined in the Custom Action. If the developer key does not require scopes and no scope parameter is specified, the access token will have access to all scopes. If the developer key does require scopes and no scope parameter is specified, Canvas will respond with &quot;invalid_scope.&quot; More information on developer keys here and endpoints here.
        Token Exchange Method is Default (POST Request)
        Canvas uses the term redirect_uri where ChatGPT uses the term Callback URL for URL to complete the redirect process after successful authentication.
        Implementing authentication with User Generated Access Tokens
        In some cases, it may be appropriate to use User Generated Access Tokens for Custom Action authentication with Canvas. Here are the steps to follow to do so:
        Proceed to Canvas Account Settings shown here:
        Scroll down to the List of Tokens shown here:
        Generate a New Token, and store this token. It will not be accessible later.
        Sample Use Case: Student Course Assistant
        Overview
        Assists students in navigating and understanding their courses by providing detailed information, generating personalized practice exams, and offering constructive feedback to enhance learning.
        Considerations
        Some information like the Syllabus is returned as an HTML page when requested by the API. This renders it impossible to show in ChatGPT. Instead, reference course description, modules, and the assignments to guide the user.
        Requests can be modified to retrieve specific pieces of information using the include[] query parameter. If you need to request specific information about a course, provide an example in the GPT instructions.
        GPT Instructions
        There can be multiple ways to write these instructions. See here for guidance on Prompt Engineering strategies and best practices.
        # **Context:** You support college students by providing detailed information about their courses hosted on the Canvas Learning Management System. You help them understand course content, generate practice exams based on provided materials, and offer insightful feedback to aid their learning journey. Assume the students are familiar with basic academic terminologies.
        # **Instructions:**
        ## Scenarios
        ### - When the user asks for information about a specific course, follow this 5 step process:
        1. Ask the user to specify the course they want assistance with and the particular area of focus (e.g., overall course overview, specific module).
        2. If you do not know the Course ID for the course requested, use the listYourCourses to find the right course and corresponding ID in Canvas. If none of the courses listed returned courses that seem to match the course request, use the searchCourses to see if there are any similarly named course.
        3. Retrieve the course information from Canvas using the getSingleCourse API call and the listModules API call.
        4. Ask the user which module(s) they would like to focus on and use the listModuleItems to retrieve the requested module items. For any assignments, share links to them.
        5. Ask if the user needs more information or if they need to prepare for an exam.
        ### When a user asks to take a practice test or practice exam for a specific course, follow this 6 step process:
        1. Ask how many questions
        2. Ask which chapters or topics they want to be tested on, provide a couple examples from the course modules in Canvas.
        3. Ask 1 question at a time, be sure the questions are multiple choice (do not generate the next question until the question is answered)
        4. When the user answers, tell them if its right or wrong and give a description for the correct answer
        5. Ask the user if they want to export the test results and write the code to create the PDF
        6. Offer additional resources and study tips tailored to the user&#39;s needs and progress, and inquire if they require further assistance with other courses or topics.
        ### When a user asks to create a study guide
        - Format the generated study guide in a table
        OpenAPI Schema
        API Calls Featured
        [GET] listYourCourses
        [GET] getSingleCourse
        [GET] listModules
        [GET] listModuleItems
        [GET] searchCourses
        Below was generated with a combination of Canvas API Reference and the ActionsGPT.
        openapi: 3.1.0
        info:
        title: Canvas API
        description: API for interacting with Canvas LMS, including courses, modules, module items, and search functionalities.
        version: 1.0.0
        servers:
        - url: https://canvas.instructure.com/api/v1
        description: Canvas LMS API server
        variables:
        domain:
        default: canvas.instructure.com
        description: The domain of your Canvas instance
        paths:
        /courses:
        get:
        operationId: listYourCourses
        summary: List your courses
        description: Retrieves a paginated list of active courses for the current user.
        parameters:
        - name: enrollment_type
        in: query
        description: Filter by enrollment type (e.g., &quot;teacher&quot;, &quot;student&quot;).
        schema:
        type: string
        - name: enrollment_role
        in: query
        description: Filter by role type. Requires admin permissions.
        schema:
        type: string
        - name: enrollment_state
        in: query
        description: Filter by enrollment state (e.g., &quot;active&quot;, &quot;invited&quot;).
        schema:
        type: string
        - name: exclude_blueprint_courses
        in: query
        description: Exclude Blueprint courses if true.
        schema:
        type: boolean
        - name: include
        in: query
        description: Array of additional information to include (e.g., &quot;term&quot;, &quot;teachers&quot;).
        schema:
        type: array
        items:
        type: string
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of courses.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the course.
        name:
        type: string
        description: The name of the course.
        account_id:
        type: integer
        description: The ID of the account associated with the course.
        enrollment_term_id:
        type: integer
        description: The ID of the term associated with the course.
        start_at:
        type: string
        format: date-time
        description: The start date of the course.
        end_at:
        type: string
        format: date-time
        description: The end date of the course.
        course_code:
        type: string
        description: The course code.
        state:
        type: string
        description: The current state of the course (e.g., &quot;unpublished&quot;, &quot;available&quot;).
        &#39;400&#39;:
        description: Bad request, possibly due to invalid query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        /courses/{course_id}:
        get:
        operationId: getSingleCourse
        summary: Get a single course
        description: Retrieves the details of a specific course by its ID.
        parameters:
        - name: course_id
        in: path
        required: true
        description: The ID of the course.
        schema:
        type: integer
        - name: include
        in: query
        description: Array of additional information to include (e.g., &quot;term&quot;, &quot;teachers&quot;).
        schema:
        type: array
        items:
        type: string
        responses:
        &#39;200&#39;:
        description: A single course object.
        content:
        application/json:
        schema:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the course.
        name:
        type: string
        description: The name of the course.
        account_id:
        type: integer
        description: The ID of the account associated with the course.
        enrollment_term_id:
        type: integer
        description: The ID of the term associated with the course.
        start_at:
        type: string
        format: date-time
        description: The start date of the course.
        end_at:
        type: string
        format: date-time
        description: The end date of the course.
        course_code:
        type: string
        description: The course code.
        state:
        type: string
        description: The current state of the course (e.g., &quot;unpublished&quot;, &quot;available&quot;).
        is_public:
        type: boolean
        description: Whether the course is public.
        syllabus_body:
        type: string
        description: The syllabus content of the course.
        term:
        type: object
        description: The term associated with the course.
        properties:
        id:
        type: integer
        name:
        type: string
        start_at:
        type: string
        format: date-time
        end_at:
        type: string
        format: date-time
        &#39;400&#39;:
        description: Bad request, possibly due to an invalid course ID or query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: Course not found, possibly due to an invalid course ID.
        /courses/{course_id}/modules:
        get:
        operationId: listModules
        summary: List modules in a course
        description: Retrieves the list of modules for a given course in Canvas.
        parameters:
        - name: course_id
        in: path
        required: true
        description: The ID of the course.
        schema:
        type: integer
        - name: include
        in: query
        description: Include additional information such as items in the response.
        schema:
        type: array
        items:
        type: string
        example: [&quot;items&quot;]
        - name: search_term
        in: query
        description: The partial title of the module to match and return.
        schema:
        type: string
        - name: student_id
        in: query
        description: Return module completion information for the student with this ID.
        schema:
        type: integer
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of modules in the course.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the module.
        name:
        type: string
        description: The name of the module.
        items_count:
        type: integer
        description: The number of items in the module.
        state:
        type: string
        description: The state of the module (e.g., &quot;active&quot;, &quot;locked&quot;).
        &#39;400&#39;:
        description: Bad request, possibly due to an invalid course ID or query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: Course not found, possibly due to an invalid course ID.
        /courses/{course_id}/modules/{module_id}/items:
        get:
        operationId: listModuleItems
        summary: List items in a module
        description: Retrieves the list of items within a specific module in a Canvas course.
        parameters:
        - name: course_id
        in: path
        required: true
        description: The ID of the course.
        schema:
        type: integer
        - name: module_id
        in: path
        required: true
        description: The ID of the module.
        schema:
        type: integer
        - name: include
        in: query
        description: Include additional information in the response, such as content details.
        schema:
        type: array
        items:
        type: string
        example: [&quot;content_details&quot;]
        - name: student_id
        in: query
        description: Return completion information for the student with this ID.
        schema:
        type: integer
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of items in the module.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the module item.
        title:
        type: string
        description: The title of the module item.
        type:
        type: string
        description: The type of the module item (e.g., &quot;Assignment&quot;, &quot;File&quot;).
        position:
        type: integer
        description: The position of the item within the module.
        indent:
        type: integer
        description: The level of indentation of the item in the module.
        completion_requirement:
        type: object
        description: The completion requirement for the item.
        properties:
        type:
        type: string
        min_score:
        type: integer
        content_id:
        type: integer
        description: The ID of the associated content item (e.g., assignment, file).
        state:
        type: string
        description: The state of the item (e.g., &quot;active&quot;, &quot;locked&quot;).
        &#39;400&#39;:
        description: Bad request, possibly due to an invalid module ID or query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: Module or course not found, possibly due to an invalid module or course ID.
        /search/all_courses:
        get:
        operationId: searchCourses
        summary: Search for courses
        description: Searches for public courses in Canvas.
        parameters:
        - name: search
        in: query
        description: The search term to filter courses.
        schema:
        type: string
        - name: public_only
        in: query
        description: If true, only returns public courses.
        schema:
        type: boolean
        - name: open_enrollment_only
        in: query
        description: If true, only returns courses with open enrollment.
        schema:
        type: boolean
        - name: enrollment_type
        in: query
        description: Filter by enrollment type (e.g., &quot;teacher&quot;, &quot;student&quot;).
        schema:
        type: string
        - name: sort
        in: query
        description: Sort the results by &quot;asc&quot; or &quot;desc&quot; order.
        schema:
        type: string
        enum:
        - asc
        - desc
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of courses matching the search criteria.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the course.
        name:
        type: string
        description: The name of the course.
        account_id:
        type: integer
        description: The ID of the account associated with the course.
        enrollment_term_id:
        type: integer
        description: The ID of the term associated with the course.
        start_at:
        type: string
        format: date-time
        description: The start date of the course.
        end_at:
        type: string
        format: date-time
        description: The end date of the course.
        course_code:
        type: string
        description: The course code.
        state:
        type: string
        description: The current state of the course (e.g., &quot;unpublished&quot;, &quot;available&quot;).
        is_public:
        type: boolean
        description: Whether the course is public.
        term:
        type: object
        description: The term associated with the course.
        properties:
        id:
        type: integer
        name:
        type: string
        start_at:
        type: string
        format: date-time
        end_at:
        type: string
        format: date-time
        &#39;400&#39;:
        description: Bad request, possibly due to invalid query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: No courses found matching the criteria.
        Sample Conversation Starters
        Help me take a practice exam.
        Give an overview of one of my courses.
        List all of my courses.
        GPT Capabilities
        [On] Web Browsing
        [On] DALL·E Image Generation
        [On] Code Interpreter &amp;amp; Data Analysis
        Other Use Cases for Consideration
        Below is a non-exhaustive list of additional use cases that could be explored using the Canvas API. The basic outline for each is provided, but the GPT Instructions and specific API calls referenced are intentionally left to you as the user to decide what works best for your needs.
        Classroom Analytics and Reports
        Use Case: Empowers teachers with comprehensive analytics and performance reports on student engagement, grades, and participation. By leveraging this data, teachers can make informed decisions to tailor their course delivery, identify at-risk students, and enhance overall classroom effectiveness.
        API Resources:
        Analytics and Quiz Statistics: Retrieve detailed data on student participation, grades, and course-level statistics.
        Quiz Reports: Generate and view various reports to analyze overall class performance and track progress over time.
        Review and Improvement Guidance for Graded Assignments
        Use Case: Provide students with a tool to review their graded assignments, analyze their performance, and receive targeted guidance on how to improve in areas where they have knowledge gaps. The tool can highlight specific questions or sections where the student struggled and suggest additional resources or practice materials to help them improve.
        API Resources:
        Submissions and Quiz Submissions: Retrieve the student’s submissions and associated grades.
        Assignments: Retrieve detailed information about the assignment, including rubrics and grading criteria.
        Rubric Assessments: Access detailed feedback and rubric assessments
        Modules: Suggest additional learning modules that target the student’s weak areas using the List modules API.
        Quizzes: Recommend practice quizzes to help the student improve on specific knowledge gaps
        Congratulations!
        You’ve successfully created a Custom GPT with a working Custom Action using Canvas LMS. You should be able to have a conversation that looks similar to the screenshot below. Great job and keep going!
      </description>
      <link>https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_canvas</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_canvas</guid>
      <pubDate>Mon, 16 Sep 2024 16:00:00 GMT</pubDate>
      <category>ChatGPT</category>
      <category>GPT actions library</category>
    </item>
    <item>
      <title>Using reasoning for data validation</title>
      <description>In this guide, we’ll explore how to use the o1 model, specifically o1-preview, to perform data validation through reasoning. We’ll walk through a practical example involving a synthetic medical dataset and demonstrate how to assess the model’s accuracy in identifying issues within the data.
        Overview
        Data validation is a critical step in ensuring the quality and reliability of datasets, especially in sensitive fields like healthcare. Traditional validation methods often rely on predefined rules and patterns. However, advanced models like o1 can understand context and reason about data, offering a more flexible and intelligent approach to validation.
        In this tutorial, we will:
        Generate a synthetic dataset of medical data that contains inconsistencies.
        Define a function that takes in a row of data and validates its accuracy
        Run the validation process and compute accuracy metrics.
        Analyze and interpret the results.
        Synthetic Data Generation
        We will use a lot of the principles described in the Synthetic Data Generation cookbook to create the foundation of our dataset.
        We will prompt the model to generate sets of medical data for our use case. We have provide detailed instructions to the model on how to create the dataset, what format to follow, and how to fill it with inaccuracies. We also provide a few rows of sample data to get the model started.
        Each row in the dataset will have the following fields:
        Patient ID: A randomly generated patient id
        Date of Birth: Date of birth of the patient
        Gender: M/F
        Medical History: Past diagnoses
        Current Medications: Medication the patient is taking
        Allergies: Identified allergies
        Lab Results (Glucose mg/dL)
        Diagnoses: Current diagnosis
        Treatment Plan: Current treatment plan
        Is Valid: Whether or not the current row of data is valid (True/False)
        Issue: If the row of data is not valid, what the issue is
        Some examples of inaccuracies that may be present in the data are:
        Prescribing medications that the patient is allergic to
        Current medications do not match medical history
        Treatment plan does not match diagnosis
        Data Validation
        Now that we have our dataset prepared, we will prompt the reasoning model to review each row of data and determine whether or not it contains an issue. We will ask the model to output whether or not there is an issue in the data and then offer an explanation of the issue.
        Once we have the model determine its list of invalid data, we will pass those results on to a model grader to assess two metrics:
        Accuracy of the model&#39;s ability correctly identify issues with the data
        For the subset of data that issues have been correctly identified, what is the accuracy of the model in identifying the issue at hand
        Given that this task is much more narrow, we can use the faster gpt-4o model to calculate the accuracy.
        REMINDER: Given that these models are still in beta, rate limits will be significantly reduced. Please adjust the number of concurrent workers accordingly.
        Now that we have the model&#39;s results, we can compare it against the source of truth and determine the system&#39;s accuracy
        Issue Identification
        We will now determine the model&#39;s ability to accurately classify the issue in the data
        Below we&#39;ll display the subset of rows that we correctly identified contained an issue. For each row, we&#39;ll show the predicted vs. true issue and whether or not there is a match
        Conclusion
        We can see from the results here that we&#39;re able to generate a high precision/recall for issue identification as well as decent accuracy for pinpointing the exact issue in the data.
        This should help streamline data validation for eval sets across a variety of domains.
      </description>
      <link>https://cookbook.openai.com/examples/o1/using_reasoning_for_data_validation</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/o1/using_reasoning_for_data_validation</guid>
      <pubDate>Wed, 11 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Reasoning</category>
    </item>
    <item>
      <title>Using reasoning for routine generation</title>
      <description>When developing customer service solutions, one of the initial steps involves transforming knowledge base articles into a set of routines that an LLM can comprehend and follow. A routine, in this context, refers to a set of step-by-step instructions designed specifically for the LLM to execute efficiently. Each routine is carefully structured so that a step corresponds to a clear action. Actions can include responding to a user, triggering a function call, or retrieving additional relevant knowledge.
        Most internal knowledge base articles are complex and structured for human interpretation. They often include intricate diagrams, multi-step processes, and decision trees that pose challenges for LLM-based solutions to reason through in a meaningful way. By breaking down these documents into routines, each instruction can be simplified and formatted in a way that guides the LLM through a series of small, manageable tasks. This granular approach reduces ambiguity, allowing the LLM to process the information methodically and reducing the risk of hallucination or deviation from the expected path.
        Converting these knowledge base articles into routines can be time-consuming and challenging, especially for companies attempting to build an automated pipeline. Each routine must account for various user scenarios, where actions need to be clearly defined. For instance, when a function call is necessary, the routine must specify the exact information to retrieve or the action to execute—whether it’s triggering an API, retrieving external data, or pulling in additional context. While automating this process with traditional GPT-class models can significantly reduce the manual effort involved, it often introduces new challenges. Some challenges include designing robust instructions that are specific enough for the LLM to follow consistently, capturing unique edge cases that may arise during customer interactions, providing high-quality few-shot examples to guide the model’s behavior, and in some cases, fine-tuning the model to achieve more reliable or specialized outcomes.
        o1 has demonstrated the capability to efficiently deconstruct these articles and convert them into sets of routines zero-shot, meaning that the LLM can understand and follow the instructions without extensive examples or prior training on similar tasks. This minimizes the prompting effort required, as the routine structure itself provides the necessary guidance for the LLM to complete each step. By breaking down tasks into specific actions and integrating function calls where needed, o1’s approach ensures that even complex workflows can be handled seamlessly by the LLM, leading to more effective and scalable customer service solutions.
        Selecting Knowledge Base Articles
        In this example, we will use a set of publicly available Help Center articles from the OpenAI website and convert them into internal routines that an LLM can execute. Besides transforming the policies into routines, we will also have the model generate functions that allow the LLM to perform actions on behalf of the user. This is necessary to allow the LLM to execute the same actions that human agents have, and access additional information that may not be immediately available just from the policy documentation.
        We will begin by using the following Help Center articles for conversion into routines:
        How do I delete my payment method
        How can I get a Business Associate Agreement (BAA) with OpenAI?
        How can I set up prepaid billing?
        How do I submit a VAT exemption request
        We have our articles stored in an accessible csv. We will take the articles and pass them to o1-preview in parallel and generate the initial routines.
        Our instructions for converting the policy to a routine include:
        Converting the policy from an external facing document to an internal SOP routine
        Breaking down the policy in specific actions and sub-actions
        Outlining specific conditions for moving between steps
        Determing where external knowledge/actions may be required, and defining functions that we could use to get that information
        We&#39;ll store the results of our routines in a dataframe and print them out so we can get an initial look.
        Results
        Upon reviewing the generated routines, we can derive several insights:
        Sample Responses: The model effectively generates sample responses that the LLM can utilize when executing the policy (e.g., “Instruct the user: ‘Confirm and purchase your initial amount of credits.’”).
        Discrete Steps: The model excels at decomposing the problem into discrete actions that the LLM needs to execute. Each instruction is clearly defined and easy to interpret.
        Function Definitions: The routines’ outputs include clearly defined functions to retrieve external information or trigger actions (e.g., rev

github-actions[bot] avatar Oct 20 '24 02:10 github-actions[bot]

Successfully generated as following:

http://localhost:1200/cookbook - Success ✔️
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <title>OpenAI Cookbook</title>
    <link>https://cookbook.openai.com/</link>
    <atom:link href="http://localhost:1200/cookbook" rel="self" type="application/rss+xml"></atom:link>
    <description>OpenAI Cookbook - Powered by RSSHub</description>
    <generator>RSSHub</generator>
    <webMaster>[email protected] (RSSHub)</webMaster>
    <language>en</language>
    <lastBuildDate>Sun, 20 Oct 2024 03:15:46 GMT</lastBuildDate>
    <ttl>5</ttl>
    <item>
      <title>Leveraging model distillation to fine-tune a model</title>
      <description>OpenAI recently released Distillation which allows to leverage the outputs of a (large) model to fine-tune another (smaller) model. This can significantly reduce the price and the latency for specific tasks as you move to a smaller model. In this cookbook we&#39;ll look at a dataset, distill the output of gpt-4o to gpt-4o-mini and show how we can get significantly better results than on a generic, non-distilled, 4o-mini.
        We&#39;ll also leverage Structured Outputs for a classification problem using a list of enum. We&#39;ll see how fine-tuned model can benefit from structured output and how it will impact the performance. We&#39;ll show that Structured Ouputs work with all of those models, including the distilled one.
        We&#39;ll first analyze the dataset, get the output of both 4o and 4o mini, highlighting the difference in performance of both models, then proceed to the distillation and analyze the performance of this distilled model.
        Prerequisites
        Let&#39;s install and load dependencies.
        Make sure your OpenAI API key is defined in your environment as &quot;OPENAI_API_KEY&quot; and it&#39;ll be loaded by the client directly.
        Loading and understanding the dataset
        For this cookbook, we&#39;ll load the data from the following Kaggle challenge: https://www.kaggle.com/datasets/zynicide/wine-reviews.
        This dataset has a large number of rows and you&#39;re free to run this cookbook on the whole data, but as a biaised french wine-lover, I&#39;ll narrow down the dataset to only French wine to focus on less rows and grape varieties.
        We&#39;re looking at a classification problem where we&#39;d like to guess the grape variety based on all other criterias available, including description, subregion and province that we&#39;ll include in the prompt. It gives a lot of information to the model, you&#39;re free to also remove some information that can help significantly the model such as the region in which it was produced to see if it does a good job at finding the grape.
        Let&#39;s filter the grape varieties that have less than 5 occurences in reviews.
        Let&#39;s proceed with a subset of 500 random rows from this dataset.
        Let&#39;s retrieve all grape varieties to include them in the prompt and in our structured outputs enum list.
        Generating the prompt
        Let&#39;s build out a function to generate our prompt and try it for the first wine of our list.
        To get a understanding of the cost before running the queries, you can leverage tiktoken to understand the number of tokens we&#39;ll send and the cost associated to run this. This will only give you an estimate for to run the completions, not the fine-tuning process (used later in this cookbook when running the distillation), which depends on other factors such as the number of epochs, training set etc.
        Preparing functions to Store Completions
        As we&#39;re looking at a limited list of response (enumerate list of grape varieties), let&#39;s leverage structured outputs so we make sure the model will answer from this list. This also allows us to compare the model&#39;s answer directly with the grape variety and have a deterministic answer (compared to a model that could answer &quot;I think the grape is Pinot Noir&quot; instead of just &quot;Pinot noir&quot;), on top of improving the performance to avoid grape varieties not in our dataset.
        If you want to know more on Structured Outputs you can read this cookbook and this documentation guide.
        To distill a model, you need to store all completions from a model, allowing you to give it as a reference to the smaller model to fine-tune it. We&#39;re therefore adding a store=True parameter to our client.chat.completions.create method so we can store those completions from gpt-4o.
        We&#39;re going to store all completions (even 4o-mini and our future fine-tuned model) so we are able to run Evals from OpenAI platform directly.
        When storing those completions, it&#39;s useful to store them with a metadata tag, that will allow filtering from the OpenAI platform to run distillation &amp;amp; evals on the specific set of completions you&#39;d like to run those.
        Parallel processing
        As we&#39;ll run this on a large number of rows, let&#39;s make sure we run those completions in parallel and use concurrent futures for this. We&#39;ll iterate on our dataframe and output progress every 20 rows. We&#39;ll store the completion from the model we run the completion for in the same dataframe using the column name {model}-variety.
        Let&#39;s try out our call model function before processing the whole dataframe and check the output.
        Great! We confirmed we can get a grape variety as an output, let&#39;s now process the dataset with both gpt-4o and gpt-4o-mini and compare the results.
        Comparing gpt-4o and gpt-4o-mini
        Now that we&#39;ve got all chat completions for those two models ; let&#39;s compare them against the expected grape variety and assess their accuracy at finding it. We&#39;ll do this directly in python here as we&#39;ve got a simple string check to run, but if your task involves more complex evals you can leverage OpenAI Evals or our open-source eval framework.
        We can see that gpt-4o is better a finding grape variety than 4o-mini (12.80% higher or almost 20% relatively to 4o-mini!). Now I&#39;m wondering if we&#39;re making gpt-4o drink wine during training!
        Distilling gpt-4o outputs to gpt-4o-mini
        Let&#39;s assume we&#39;d like to run this prediction often, we want completions to be faster and cheaper, but keep that level of accuracy. That&#39;d be great to be able to distill 4o accuracy to 4o-mini, wouldn&#39;t it? Let&#39;s do it!
        We&#39;ll now go to OpenAI Stored completions page: https://platform.openai.com/chat-completions.
        Let&#39;s select the model gpt-4o (make sure to do this, you don&#39;t want to distill the outputs of 4o-mini that we ran). Let&#39;s also select the metadata distillation: wine-distillation to get only stored completions ran from this cookbook.
        Once you&#39;ve selected completions, you can click on &quot;Distill&quot; on the top right corner to fine-tune a model based on those completions. Once we&#39;ve done that, a file to run the fine-tuning process will automatically be created. Let&#39;s then select gpt-4o-mini as the base model, keep the default parameters (but you&#39;re free to change them or iterate with it to improve performance).
        Once the fine-tuning job is starting, you can retrieve the fine tuning job ID from the fine-tuning page, we&#39;ll use it to monitor status of the fine-tuned job as well as retrieving the fine-tuned model id once done.
        Running completions for the distilled model
        Now that we&#39;ve got our model fine-tuned, we can use this model to run completions and compare accuracy with both gpt4o and gpt4o-mini.
        Let&#39;s grab a different subset of french wines (as we restricted the outputs to french grape varieties, without outliers, we&#39;ll need to focus our validation dataset to this too). Let&#39;s run this on 300 entries for each models.
        Let&#39;s compare accuracy of models
        That&#39;s almost a 22% relative improvement over the non-distilled gpt-4o-mini! 🎉
        Our fine-tuned model performs way better than gpt-4o-mini, while having the same base model. We&#39;ll be able to use this model to run inferences at a lower cost and lower latency for future grape variety prediction.
      </description>
      <link>https://cookbook.openai.com/examples/leveraging_model_distillation_to_fine-tune_a_model</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/leveraging_model_distillation_to_fine-tune_a_model</guid>
      <pubDate>Tue, 15 Oct 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Fine-tuning</category>
    </item>
    <item>
      <title>Orchestrating Agents: Routines and Handoffs</title>
      <description>When working with language models, quite often all you need for solid performance is a good prompt and the right tools. However, when dealing with many unique flows, things may get hairy. This cookbook will walk through one way to tackle this.
        We&#39;ll introduce the notion of routines and handoffs, then walk through the implementation and show how they can be used to orchestrate multiple agents in a simple, powerful, and controllable way.
        Finally, we provide a sample repo, Swarm, that implements these ideas along with examples.
        Let&#39;s start by setting up our imports.
        Routines
        The notion of a &quot;routine&quot; is not strictly defined, and instead meant to capture the idea of a set of steps. Conretely, let&#39;s define a routine to be a list of instructions in natural langauge (which we&#39;ll represent with a system prompt), along with the tools necessary to complete them.
        Let&#39;s take a look at an example. Below, we&#39;ve defined a routine for a customer service agent instructing it to triage the user issue, then either suggest a fix or provide a refund. We&#39;ve also defined the necessary functions execute_refund and look_up_item. We can call this a customer service routine, agent, assistant, etc –&amp;nbsp;however the idea itself is the same: a set of steps and the tools to execute them.
        The main power of routines is their simplicity and robustness. Notice that these instructions contain conditionals much like a state machine or branching in code. LLMs can actually handle these cases quite robustly for small and medium sized routine, with the added benefit of having &quot;soft&quot; adherance –&amp;nbsp;the LLM can naturally steer the conversation without getting stuck in dead-ends.
        Executing Routines
        To execute a routine, let&#39;s implement a simple loop that:
        Gets user input.
        Appends user message to messages.
        Calls the model.
        Appends model response to messages.
        As you can see, this currently ignores function calls, so let&#39;s add that.
        Models require functions to be formatted as a function schema. For convenience, we can define a helper function that turns python functions into the corresponding function schema.
        For example:
        Now, we can use this function to pass the tools to the model when we call it.
        Finally, when the model calls a tool we need to execute the corresponding function and provide the result back to the model.
        We can do this by mapping the name of the tool to the python function in a tool_map, then looking it up in execute_tool_call and calling it. Finally we add the result to the conversation.
        In practice, we&#39;ll also want to let the model use the result to produce another response. That response might also contain a tool call, so we can just run this in a loop until there are no more tool calls.
        If we put everything together, it will look something like this:
        Now that we have a routine, let&#39;s say we want to add more steps and more tools. We can up to a point, but eventually if we try growing the routine with too many different tasks it may start to struggle. This is where we can leverage the notion of multiple routines – given a user request, we can load the right routine with the appropriate steps and tools to address it.
        Dynamically swapping system instructions and tools may seem daunting. However, if we view &quot;routines&quot; as &quot;agents&quot;, then this notion of handoffs allow us to represent these swaps simply –&amp;nbsp;as one agent handing off a conversation to another.
        Handoffs
        Let&#39;s define a handoff as an agent (or routine) handing off an active conversation to another agent, much like when you get transfered to someone else on a phone call. Except in this case, the agents have complete knowledge of your prior conversation!
        To see handoffs in action, let&#39;s start by defining a basic class for an Agent.
        Now to make our code support it, we can change run_full_turn to take an Agent instead of separate system_message and tools:
        We can now run multiple agents easily:
        Great! But we did the handoff manually here –&amp;nbsp;we want the agents themselves to decide when to perform a handoff. A simple, but surprisingly effective way to do this is by giving them a transfer_to_XXX function, where XXX is some agent. The model is smart enough to know to call this function when it makes sense to make a handoff!
        Handoff Functions
        Now that agent can express the intent to make a handoff, we must make it actually happen. There&#39;s many ways to do this, but there&#39;s one particularly clean way.
        For the agent functions we&#39;ve defined so far, like execute_refund or place_order they return a string, which will be provided to the model. What if instead, we return an Agent object to indate which agent we want to transfer to? Like so:
        We can then update our code to check the return type of a function response, and if it&#39;s an Agent, update the agent in use! Additionally, now run_full_turn will need to return the latest agent in use in case there are handoffs. (We can do this in a Response class to keep things neat.)
        Now for the updated run_full_turn:
        Let&#39;s look at an example with more Agents.
        Finally, we can run this in a loop (this won&#39;t run in python notebooks, so you can try this in a separate python file):
        Swarm
        As a proof of concept, we&#39;ve packaged these ideas into a sample library called Swarm. It is meant as an example only, and should not be directly used in production. However, feel free to take the ideas and code to build your own!
      </description>
      <link>https://cookbook.openai.com/examples/orchestrating_agents</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/orchestrating_agents</guid>
      <pubDate>Wed, 09 Oct 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Functions</category>
    </item>
    <item>
      <title>Prompt Caching 101</title>
      <description>OpenAI offers discounted prompt caching for prompts exceeding 1024 tokens, resulting in up to an 80% reduction in latency for longer prompts over 10,000 tokens. By caching repetitive information across LLM API requests, you can greatly reduce both latency and costs. Prompt caching is scoped at the organization level, meaning only members of the same organization can access shared caches. Additionally, caching is eligible for zero data retention, as no data is stored during the process.
        Prompt caching automatically activates for prompts longer than 1024 tokens-- you don&#39;t have to change anything in your completions request. When an API request is made, the system first checks if the beginning portion (prefix) of the prompt has already been cached. If a match is found (cache hit), the cached prompt is used, leading to reduced latency and costs. If there&#39;s no match, the system processes the full prompt from scratch and caches the prefix for future use.
        With these benefits in mind, some of the key use cases where prompt caching can be especially advantageous are:
        Agents using tools and structured outputs: Cache the extended list of tools and schemas.
        Coding and writing assistants: Insert large sections or summaries of codebases and workspaces directly in prompts.
        Chatbots: Cache static portions of multi-turn conversations to maintain context efficiently over extended dialogues.
        In this cookbook, we&#39;ll go through a couple examples of caching tools and images. Recall that in general, you&#39;ll want to put static content like instructions and examples at the beginning of your prompt, and variable content, such as user-specific information, at the end. This also applies to images and tools, which must be identical even in their ordering between requests. All requests, including those with fewer than 1024 tokens, will display a cached_tokens field of the usage.prompt_tokens_details chat completions object indicating how many of the prompt tokens were a cache hit. For requests under 1024 tokens, cached_tokens will be zero. Caching discounts are based on the actual number of tokens processed, including those used for images, which also count toward your rate limits.
        Example 1: Caching tools and multi-turn conversations
        In this example, we define tools and interactions for a customer support assistant, capable of handling tasks such as checking delivery dates, canceling orders, and updating payment methods. The assistant processes two separate messages, first responding to an initial query, followed by a delayed response to a follow-up query.
        When caching tools, it is important that the tool definitions and their order remain identical for them to be included in the prompt prefix. To cache message histories in a multi-turn conversation, append new elements to the end of the messages array. In the response object and the output below, for the second completion run2, you can see that the cached_tokens value is greater than zero, indicating successful caching.
        Example 2: Images
        In our second example we include multiple image URLs of grocery items in the messages array, along with a user query, run three times with delays. Images—whether linked or encoded in base64 within user messages—qualify for caching. Make sure the detail parameter remains consistent, as it affects how images are tokenized. Note that GPT-4o-mini adds extra tokens to cover image processing costs, even though it uses a low-cost token model for text. Caching discounts are based on the actual number of tokens processed, including those used for images, which also count toward your rate limits.
        The output for this example shows that a cache was hit for the second run, however it was not hit for the third run because of a different first url (eggs_url instead of veggie_url), even though the user query is the same.
        Overall tips
        To get the most out of prompt caching, consider following these best practices:
        Place static or frequently reused content at the beginning of prompts: This helps ensure better cache efficiency by keeping dynamic data towards the end of the prompt.
        Maintain consistent usage patterns: Prompts that aren&#39;t used regularly are automatically removed from the cache. To prevent cache evictions, maintain consistent usage of prompts.
        Monitor key metrics: Regularly track cache hit rates, latency, and the proportion of cached tokens. Use these insights to fine-tune your caching strategy and maximize performance.
        By implementing these practices, you can take full advantage of prompt caching, ensuring that your applications are both responsive and cost-efficient. A well-managed caching strategy will significantly reduce processing times, lower costs, and help maintain smooth user experiences.
      </description>
      <link>https://cookbook.openai.com/examples/prompt_caching101</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/prompt_caching101</guid>
      <pubDate>Mon, 30 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
    </item>
    <item>
      <title>Using chained calls for o1 structured outputs</title>
      <description>The initially released versions (September 2024) of o1 reasoning models have advanced capabilities but do not have structured outputs support.
        This means that requests with o1 don&#39;t have reliable type-safety and rely on the prompt itself to return a useful JSON.
        In this guide, we&#39;ll explore two methods to prompt o1 models, specifically o1-preview, to return a valid JSON format when using the OpenAI API.
        Prompting
        The simplest way to return a JSON response using o1-preview is to explicitly prompt it.
        Let&#39;s run through an example of:
        Fetching a wikipedia page of companies
        Determining which could benefit the most from AI capabilities
        Returning them in a JSON format, which could then be ingested by other systems
        Note that the response is already quite good - it returns the JSON with the appropriate responses. However, it runs into the same pitfalls as existing use-cases of prompt-only JSON inference:
        You must manually process this JSON into your type-safe structure
        Model refusals are not explicitly returned from the API as a separate structure
        Structured Outputs
        Let&#39;s now do this with structured outputs. To enable this functionality, we’ll link the o1-preview response with a follow-up request to gpt-4o-mini, which can effectively process the data returned from the initial o1-preview response.
        Conclusion
        Structured outputs allow your code to have reliable type-safety and simpler prompting. In addition, it allows you to re-use your object schemas for easier integration into your existing workflows.
        The o1 class of models currently doesn&#39;t have structured outputs support, but we can re-use existing structured outputs functionality from gpt-4o-mini by chaining two requests together. This flow currently requires two calls, but the second gpt-4o-mini call cost should be minimal compared to the o1-preview/o1-mini calls.
      </description>
      <link>https://cookbook.openai.com/examples/o1/using_chained_calls_for_o1_structured_outputs</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/o1/using_chained_calls_for_o1_structured_outputs</guid>
      <pubDate>Wed, 25 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Reasoning</category>
    </item>
    <item>
      <title>Building a Bring Your Own Browser (BYOB) Tool for Web Browsing and Summarization</title>
      <description>Disclaimer: This cookbook is for educational purposes only. Ensure that you comply with all applicable laws and service terms when using web search and scraping technologies. This cookbook will restrict the search to openai.com domain to retrieve the public information to illustrate the concepts.
        Large Language Models (LLMs) such as GPT-4o have a knowledge cutoff date, which means they lack information about events that occurred after that point. In scenarios where the most recent data is essential, it&#39;s necessary to provide LLMs with access to current web information to ensure accurate and relevant responses.
        In this guide, we will build a Bring Your Own Browser (BYOB) tool using Python to overcome this limitation. Our goal is to create a system that provides up-to-date answers in your application, including the most recent developments such as the latest product launches by OpenAI. By integrating web search capabilities with an LLM, we&#39;ll enable the model to generate responses based on the latest information available online.
        While you can use any publicly available search APIs, we&#39;ll utilize Google&#39;s Custom Search API to perform web searches. The retrieved information from the search results will be processed and passed to the LLM to generate the final response through Retrieval-Augmented Generation (RAG).
        Bring Your Own Browser (BYOB) tools allow users to perform web browsing tasks programmatically. In this notebook, we&#39;ll create a BYOB tool that:
        #1. Set Up a Search Engine: Use a public search API, such as Google&#39;s Custom Search API, to perform web searches and obtain a list of relevant search results.
        #2. Build a Search Dictionary: Collect the title, URL, and a summary of each web page from the search results to create a structured dictionary of information.
        #3. Generate a RAG Response: Implement Retrieval-Augmented Generation (RAG) by passing the gathered information to the LLM, which then generates a final response to the user&#39;s query.
        Use Case
        In this cookbook, we&#39;ll take the example of a user who wants to list recent product launches by OpenAI in chronological order. Because the current GPT-4o model has a knowledge cutoff date, it is not expected that the model will know about recent product launches such as the o1-preview model launched in September 2024.
        Given the knowledge cutoff, as expected the model does not know about the recent product launches by OpenAI.
        Setting up a BYOB tool
        To provide the model with recent events information, we&#39;ll follow these steps:
        Step 1: Set Up a Search Engine to Provide Web Search Results
        Step 2: Build a Search Dictionary with Titles, URLs, and Summaries of Web Pages
        Step 3: Pass the information to the model to generate a RAG Response to the User Query
        Before we begin, ensure you have the following: Python 3.12 or later installed on your machine. You will also need a Google Custom Search API key and Custom Search Engine ID (CSE ID). Necessary Python packages installed: requests, beautifulsoup4, openai. And ensure the OPENAI_API_KEY is set up as an environment variable.
        Step 1: Set Up a Search Engine to Provide Web Search Results
        You can use any publicly available web search APIs to perform this task. We will configure a custom search engine using Google&#39;s Custom Search API. This engine will fetch a list of relevant web pages based on the user&#39;s query, focusing on obtaining the most recent and pertinent results.
        a. Configure Search API key and Function: Acquire a Google API key and a Custom Search Engine ID (CSE ID) from the Google Developers Console. You can navigate to this Programmable Search Engine Link to set up an API key as well as Custom Search Engine ID (CSE ID).
        The search function below sets up the search based on search term, the API and CSE ID keys, as well as number of search results to return. We&#39;ll introduce a parameter site_filter to restrict the output to only openai.com
        b. Identify the search terms for search engine: Before we can retrieve specific results from a 3rd Party API, we may need to use Query Expansion to identify specific terms our browser search API should retrieve. Query expansion is a process where we broaden the original user query by adding related terms, synonyms, or variations. This technique is essential because search engines, like Google&#39;s Custom Search API, are often better at matching a range of related terms rather than just the natural language prompt used by a user.
        For example, searching with only the raw query &quot;List the latest OpenAI product launches in chronological order from latest to oldest in the past 2 years&quot; may return fewer and less relevant results than a more specific and direct search on a succinct phrase such as &quot;Latest OpenAI product launches&quot;. In the code below, we will use the user&#39;s original search_query to produce a more specific search term to use with the Google API to retrieve the results.
        c. Invoke the search function: Now that we have the search term, we will invoke the search function to retrieve the results from Google search API. The results only have the link of the web page and a snippet at this point. In the next step, we will retrieve more information from the webpage and summarize it in a dictionary to pass to the model.
        Step 2: Build a Search Dictionary with Titles, URLs, and Summaries of Web Pages
        After obtaining the search results, we&#39;ll extract and organize the relevant information, so it can be passed to the LLM for final output.
        a. Scrape Web Page Content: For each URL in the search results, retrieve the web page to extract textual content while filtering out non-relevant data like scripts and advertisements as demonstrated in function retrieve_content.
        b. Summarize Content: Use an LLM to generate concise summaries of the scraped content, focusing on information pertinent to the user&#39;s query. Model can be provided the original search text, so it can focus on summarizing the content for the search intent as outlined in function summarize_content.
        c. Create a Structured Dictionary: Organize the data into a dictionary or a DataFrame containing the title, link, and summary for each web page. This structure can be passed on to the LLM to generate the summary with the appropriate citations.
        We retrieved the most recent results. (Note these will vary depending on when you execute this script.)
        Step 3: Pass the information to the model to generate a RAG Response to the User Query
        With the search data organized in a JSON data structure, we will pass this information to the LLM with the original user query to generate the final response. Now, the LLM response includes information beyond its original knowledge cutoff, providing current insights.
        Conclusion
        Large Language Models (LLMs) have a knowledge cutoff and may not be aware of recent events. To provide them with the latest information, you can build a Bring Your Own Browser (BYOB) tool using Python. This tool retrieves current web data and feeds it to the LLM, enabling up-to-date responses.
        The process involves three main steps:
        #1 Set Up a Search Engine: Use a public search API, like Google&#39;s Custom Search API, to perform web searches and obtain a list of relevant search results.
        #2 Build a Search Dictionary: Collect the title, URL, and a summary of each web page from the search results to create a structured dictionary of information.
        #3. Generate a RAG Response: Implement Retrieval-Augmented Generation (RAG) by passing the gathered information to the LLM, which then generates a final response to the user&#39;s query.
        By following these steps, you enhance the LLMs ability to provide up-to-date answers in your application that include the most recent developments, such as the latest product launches by OpenAI.
      </description>
      <link>https://cookbook.openai.com/examples/third_party/web_search_with_google_api_bring_your_own_browser_tool</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/third_party/web_search_with_google_api_bring_your_own_browser_tool</guid>
      <pubDate>Wed, 25 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
    </item>
    <item>
      <title>GPT Actions library - Canvas Learning Management System</title>
      <description>Table of Contents
        General App Information - Overview of Canvas LMS, its functionality, and the role of ChatGPT&#39;s Custom Actions to enhance educational experiences through AI integration.
        Authentication from ChatGPT to Canvas - Explanation of authentication methods (OAuth and User Generated Access Tokens) for connecting ChatGPT to Canvas, with detailed instructions for setting up each option.
        Sample Use Case: Student Course Assistant - Detailed example of using ChatGPT to assist students with course navigation, exam preparation, and personalized feedback, including specific API calls and workflows.
        Other Use Cases for Consideration - Additional potential integrations using the Canvas API, such as classroom analytics and report generation.
        Congratulations
        General App Information
        Canvas is a widely-used Learning Management System (LMS) designed to support online learning and teaching. It offers a robust set of tools for course management, content delivery, assessments, and student collaboration. Through the Canvas REST API, Canvas allows for extensive customization and integration with third-party applications, including AI-powered tools like ChatGPT.
        ChatGPT’s Custom Actions with Canvas enable educators to leverage AI to enhance course content, automate tasks, and provide personalized learning journeys for students. Examples include virtual teaching assistants based on active courses, as the capabilities are well-suited for pulling information in from Canvas to create an educational dialogue. ChatGPT with Custom Actions is not meant for automating the entire Canvas experience nor act as a replacement to many of its capabilities better suited for completion in the Canvas app.
        Authentication from ChatGPT to Canvas
        For a general overview on Authentication in Custom Actions, see the Action authentication documentation.
        There are two options for authentication in Canvas: 1) OAuth and 2) User Generated Access Tokens.
        For large-scale deployments, it is required to use OAuth for Action Authentication.
        If the user is considering a single-user deployment or does not have access to Admin Settings, they may consider User Generated Access Tokens. Be aware that any request made by the action will be made using the token the user generated, so Canvas will register all requests as the user&#39;s activity and use the user&#39;s permissions to complete them.
        Implementing OAuth for Canvas
        While this Canvas Cookbook does not use OAuth, any deployment with more than one user must use it. See OAuth for Canvas Documentation for a detailed walkthrough.
        Here are some things to keep in mind while implementing OAuth in a Canvas Custom Action:
        Access to Canvas’ Admin settings is required for OAuth in order to retrieve a Client ID and Client Secret.
        The Authorization URL will look like (make sure to update the Canvas Install URL): https:///login/oauth2/auth
        The Token URL will look like (make sure to update the Canvas Install URL): ttps:///login/oauth2/token
        Scopes may not need to be defined in the Custom Action. If the developer key does not require scopes and no scope parameter is specified, the access token will have access to all scopes. If the developer key does require scopes and no scope parameter is specified, Canvas will respond with &quot;invalid_scope.&quot; More information on developer keys here and endpoints here.
        Token Exchange Method is Default (POST Request)
        Canvas uses the term redirect_uri where ChatGPT uses the term Callback URL for URL to complete the redirect process after successful authentication.
        Implementing authentication with User Generated Access Tokens
        In some cases, it may be appropriate to use User Generated Access Tokens for Custom Action authentication with Canvas. Here are the steps to follow to do so:
        Proceed to Canvas Account Settings shown here:
        Scroll down to the List of Tokens shown here:
        Generate a New Token, and store this token. It will not be accessible later.
        Sample Use Case: Student Course Assistant
        Overview
        Assists students in navigating and understanding their courses by providing detailed information, generating personalized practice exams, and offering constructive feedback to enhance learning.
        Considerations
        Some information like the Syllabus is returned as an HTML page when requested by the API. This renders it impossible to show in ChatGPT. Instead, reference course description, modules, and the assignments to guide the user.
        Requests can be modified to retrieve specific pieces of information using the include[] query parameter. If you need to request specific information about a course, provide an example in the GPT instructions.
        GPT Instructions
        There can be multiple ways to write these instructions. See here for guidance on Prompt Engineering strategies and best practices.
        # **Context:** You support college students by providing detailed information about their courses hosted on the Canvas Learning Management System. You help them understand course content, generate practice exams based on provided materials, and offer insightful feedback to aid their learning journey. Assume the students are familiar with basic academic terminologies.
        # **Instructions:**
        ## Scenarios
        ### - When the user asks for information about a specific course, follow this 5 step process:
        1. Ask the user to specify the course they want assistance with and the particular area of focus (e.g., overall course overview, specific module).
        2. If you do not know the Course ID for the course requested, use the listYourCourses to find the right course and corresponding ID in Canvas. If none of the courses listed returned courses that seem to match the course request, use the searchCourses to see if there are any similarly named course.
        3. Retrieve the course information from Canvas using the getSingleCourse API call and the listModules API call.
        4. Ask the user which module(s) they would like to focus on and use the listModuleItems to retrieve the requested module items. For any assignments, share links to them.
        5. Ask if the user needs more information or if they need to prepare for an exam.
        ### When a user asks to take a practice test or practice exam for a specific course, follow this 6 step process:
        1. Ask how many questions
        2. Ask which chapters or topics they want to be tested on, provide a couple examples from the course modules in Canvas.
        3. Ask 1 question at a time, be sure the questions are multiple choice (do not generate the next question until the question is answered)
        4. When the user answers, tell them if its right or wrong and give a description for the correct answer
        5. Ask the user if they want to export the test results and write the code to create the PDF
        6. Offer additional resources and study tips tailored to the user&#39;s needs and progress, and inquire if they require further assistance with other courses or topics.
        ### When a user asks to create a study guide
        - Format the generated study guide in a table
        OpenAPI Schema
        API Calls Featured
        [GET] listYourCourses
        [GET] getSingleCourse
        [GET] listModules
        [GET] listModuleItems
        [GET] searchCourses
        Below was generated with a combination of Canvas API Reference and the ActionsGPT.
        openapi: 3.1.0
        info:
        title: Canvas API
        description: API for interacting with Canvas LMS, including courses, modules, module items, and search functionalities.
        version: 1.0.0
        servers:
        - url: https://canvas.instructure.com/api/v1
        description: Canvas LMS API server
        variables:
        domain:
        default: canvas.instructure.com
        description: The domain of your Canvas instance
        paths:
        /courses:
        get:
        operationId: listYourCourses
        summary: List your courses
        description: Retrieves a paginated list of active courses for the current user.
        parameters:
        - name: enrollment_type
        in: query
        description: Filter by enrollment type (e.g., &quot;teacher&quot;, &quot;student&quot;).
        schema:
        type: string
        - name: enrollment_role
        in: query
        description: Filter by role type. Requires admin permissions.
        schema:
        type: string
        - name: enrollment_state
        in: query
        description: Filter by enrollment state (e.g., &quot;active&quot;, &quot;invited&quot;).
        schema:
        type: string
        - name: exclude_blueprint_courses
        in: query
        description: Exclude Blueprint courses if true.
        schema:
        type: boolean
        - name: include
        in: query
        description: Array of additional information to include (e.g., &quot;term&quot;, &quot;teachers&quot;).
        schema:
        type: array
        items:
        type: string
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of courses.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the course.
        name:
        type: string
        description: The name of the course.
        account_id:
        type: integer
        description: The ID of the account associated with the course.
        enrollment_term_id:
        type: integer
        description: The ID of the term associated with the course.
        start_at:
        type: string
        format: date-time
        description: The start date of the course.
        end_at:
        type: string
        format: date-time
        description: The end date of the course.
        course_code:
        type: string
        description: The course code.
        state:
        type: string
        description: The current state of the course (e.g., &quot;unpublished&quot;, &quot;available&quot;).
        &#39;400&#39;:
        description: Bad request, possibly due to invalid query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        /courses/{course_id}:
        get:
        operationId: getSingleCourse
        summary: Get a single course
        description: Retrieves the details of a specific course by its ID.
        parameters:
        - name: course_id
        in: path
        required: true
        description: The ID of the course.
        schema:
        type: integer
        - name: include
        in: query
        description: Array of additional information to include (e.g., &quot;term&quot;, &quot;teachers&quot;).
        schema:
        type: array
        items:
        type: string
        responses:
        &#39;200&#39;:
        description: A single course object.
        content:
        application/json:
        schema:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the course.
        name:
        type: string
        description: The name of the course.
        account_id:
        type: integer
        description: The ID of the account associated with the course.
        enrollment_term_id:
        type: integer
        description: The ID of the term associated with the course.
        start_at:
        type: string
        format: date-time
        description: The start date of the course.
        end_at:
        type: string
        format: date-time
        description: The end date of the course.
        course_code:
        type: string
        description: The course code.
        state:
        type: string
        description: The current state of the course (e.g., &quot;unpublished&quot;, &quot;available&quot;).
        is_public:
        type: boolean
        description: Whether the course is public.
        syllabus_body:
        type: string
        description: The syllabus content of the course.
        term:
        type: object
        description: The term associated with the course.
        properties:
        id:
        type: integer
        name:
        type: string
        start_at:
        type: string
        format: date-time
        end_at:
        type: string
        format: date-time
        &#39;400&#39;:
        description: Bad request, possibly due to an invalid course ID or query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: Course not found, possibly due to an invalid course ID.
        /courses/{course_id}/modules:
        get:
        operationId: listModules
        summary: List modules in a course
        description: Retrieves the list of modules for a given course in Canvas.
        parameters:
        - name: course_id
        in: path
        required: true
        description: The ID of the course.
        schema:
        type: integer
        - name: include
        in: query
        description: Include additional information such as items in the response.
        schema:
        type: array
        items:
        type: string
        example: [&quot;items&quot;]
        - name: search_term
        in: query
        description: The partial title of the module to match and return.
        schema:
        type: string
        - name: student_id
        in: query
        description: Return module completion information for the student with this ID.
        schema:
        type: integer
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of modules in the course.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the module.
        name:
        type: string
        description: The name of the module.
        items_count:
        type: integer
        description: The number of items in the module.
        state:
        type: string
        description: The state of the module (e.g., &quot;active&quot;, &quot;locked&quot;).
        &#39;400&#39;:
        description: Bad request, possibly due to an invalid course ID or query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: Course not found, possibly due to an invalid course ID.
        /courses/{course_id}/modules/{module_id}/items:
        get:
        operationId: listModuleItems
        summary: List items in a module
        description: Retrieves the list of items within a specific module in a Canvas course.
        parameters:
        - name: course_id
        in: path
        required: true
        description: The ID of the course.
        schema:
        type: integer
        - name: module_id
        in: path
        required: true
        description: The ID of the module.
        schema:
        type: integer
        - name: include
        in: query
        description: Include additional information in the response, such as content details.
        schema:
        type: array
        items:
        type: string
        example: [&quot;content_details&quot;]
        - name: student_id
        in: query
        description: Return completion information for the student with this ID.
        schema:
        type: integer
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of items in the module.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the module item.
        title:
        type: string
        description: The title of the module item.
        type:
        type: string
        description: The type of the module item (e.g., &quot;Assignment&quot;, &quot;File&quot;).
        position:
        type: integer
        description: The position of the item within the module.
        indent:
        type: integer
        description: The level of indentation of the item in the module.
        completion_requirement:
        type: object
        description: The completion requirement for the item.
        properties:
        type:
        type: string
        min_score:
        type: integer
        content_id:
        type: integer
        description: The ID of the associated content item (e.g., assignment, file).
        state:
        type: string
        description: The state of the item (e.g., &quot;active&quot;, &quot;locked&quot;).
        &#39;400&#39;:
        description: Bad request, possibly due to an invalid module ID or query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: Module or course not found, possibly due to an invalid module or course ID.
        /search/all_courses:
        get:
        operationId: searchCourses
        summary: Search for courses
        description: Searches for public courses in Canvas.
        parameters:
        - name: search
        in: query
        description: The search term to filter courses.
        schema:
        type: string
        - name: public_only
        in: query
        description: If true, only returns public courses.
        schema:
        type: boolean
        - name: open_enrollment_only
        in: query
        description: If true, only returns courses with open enrollment.
        schema:
        type: boolean
        - name: enrollment_type
        in: query
        description: Filter by enrollment type (e.g., &quot;teacher&quot;, &quot;student&quot;).
        schema:
        type: string
        - name: sort
        in: query
        description: Sort the results by &quot;asc&quot; or &quot;desc&quot; order.
        schema:
        type: string
        enum:
        - asc
        - desc
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of courses matching the search criteria.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the course.
        name:
        type: string
        description: The name of the course.
        account_id:
        type: integer
        description: The ID of the account associated with the course.
        enrollment_term_id:
        type: integer
        description: The ID of the term associated with the course.
        start_at:
        type: string
        format: date-time
        description: The start date of the course.
        end_at:
        type: string
        format: date-time
        description: The end date of the course.
        course_code:
        type: string
        description: The course code.
        state:
        type: string
        description: The current state of the course (e.g., &quot;unpublished&quot;, &quot;available&quot;).
        is_public:
        type: boolean
        description: Whether the course is public.
        term:
        type: object
        description: The term associated with the course.
        properties:
        id:
        type: integer
        name:
        type: string
        start_at:
        type: string
        format: date-time
        end_at:
        type: string
        format: date-time
        &#39;400&#39;:
        description: Bad request, possibly due to invalid query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: No courses found matching the criteria.
        Sample Conversation Starters
        Help me take a practice exam.
        Give an overview of one of my courses.
        List all of my courses.
        GPT Capabilities
        [On] Web Browsing
        [On] DALL·E Image Generation
        [On] Code Interpreter &amp;amp; Data Analysis
        Other Use Cases for Consideration
        Below is a non-exhaustive list of additional use cases that could be explored using the Canvas API. The basic outline for each is provided, but the GPT Instructions and specific API calls referenced are intentionally left to you as the user to decide what works best for your needs.
        Classroom Analytics and Reports
        Use Case: Empowers teachers with comprehensive analytics and performance reports on student engagement, grades, and participation. By leveraging this data, teachers can make informed decisions to tailor their course delivery, identify at-risk students, and enhance overall classroom effectiveness.
        API Resources:
        Analytics and Quiz Statistics: Retrieve detailed data on student participation, grades, and course-level statistics.
        Quiz Reports: Generate and view various reports to analyze overall class performance and track progress over time.
        Review and Improvement Guidance for Graded Assignments
        Use Case: Provide students with a tool to review their graded assignments, analyze their performance, and receive targeted guidance on how to improve in areas where they have knowledge gaps. The tool can highlight specific questions or sections where the student struggled and suggest additional resources or practice materials to help them improve.
        API Resources:
        Submissions and Quiz Submissions: Retrieve the student’s submissions and associated grades.
        Assignments: Retrieve detailed information about the assignment, including rubrics and grading criteria.
        Rubric Assessments: Access detailed feedback and rubric assessments
        Modules: Suggest additional learning modules that target the student’s weak areas using the List modules API.
        Quizzes: Recommend practice quizzes to help the student improve on specific knowledge gaps
        Congratulations!
        You’ve successfully created a Custom GPT with a working Custom Action using Canvas LMS. You should be able to have a conversation that looks similar to the screenshot below. Great job and keep going!
      </description>
      <link>https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_canvas</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_canvas</guid>
      <pubDate>Mon, 16 Sep 2024 16:00:00 GMT</pubDate>
      <category>ChatGPT</category>
      <category>GPT actions library</category>
    </item>
    <item>
      <title>Using reasoning for data validation</title>
      <description>In this guide, we’ll explore how to use the o1 model, specifically o1-preview, to perform data validation through reasoning. We’ll walk through a practical example involving a synthetic medical dataset and demonstrate how to assess the model’s accuracy in identifying issues within the data.
        Overview
        Data validation is a critical step in ensuring the quality and reliability of datasets, especially in sensitive fields like healthcare. Traditional validation methods often rely on predefined rules and patterns. However, advanced models like o1 can understand context and reason about data, offering a more flexible and intelligent approach to validation.
        In this tutorial, we will:
        Generate a synthetic dataset of medical data that contains inconsistencies.
        Define a function that takes in a row of data and validates its accuracy
        Run the validation process and compute accuracy metrics.
        Analyze and interpret the results.
        Synthetic Data Generation
        We will use a lot of the principles described in the Synthetic Data Generation cookbook to create the foundation of our dataset.
        We will prompt the model to generate sets of medical data for our use case. We have provide detailed instructions to the model on how to create the dataset, what format to follow, and how to fill it with inaccuracies. We also provide a few rows of sample data to get the model started.
        Each row in the dataset will have the following fields:
        Patient ID: A randomly generated patient id
        Date of Birth: Date of birth of the patient
        Gender: M/F
        Medical History: Past diagnoses
        Current Medications: Medication the patient is taking
        Allergies: Identified allergies
        Lab Results (Glucose mg/dL)
        Diagnoses: Current diagnosis
        Treatment Plan: Current treatment plan
        Is Valid: Whether or not the current row of data is valid (True/False)
        Issue: If the row of data is not valid, what the issue is
        Some examples of inaccuracies that may be present in the data are:
        Prescribing medications that the patient is allergic to
        Current medications do not match medical history
        Treatment plan does not match diagnosis
        Data Validation
        Now that we have our dataset prepared, we will prompt the reasoning model to review each row of data and determine whether or not it contains an issue. We will ask the model to output whether or not there is an issue in the data and then offer an explanation of the issue.
        Once we have the model determine its list of invalid data, we will pass those results on to a model grader to assess two metrics:
        Accuracy of the model&#39;s ability correctly identify issues with the data
        For the subset of data that issues have been correctly identified, what is the accuracy of the model in identifying the issue at hand
        Given that this task is much more narrow, we can use the faster gpt-4o model to calculate the accuracy.
        REMINDER: Given that these models are still in beta, rate limits will be significantly reduced. Please adjust the number of concurrent workers accordingly.
        Now that we have the model&#39;s results, we can compare it against the source of truth and determine the system&#39;s accuracy
        Issue Identification
        We will now determine the model&#39;s ability to accurately classify the issue in the data
        Below we&#39;ll display the subset of rows that we correctly identified contained an issue. For each row, we&#39;ll show the predicted vs. true issue and whether or not there is a match
        Conclusion
        We can see from the results here that we&#39;re able to generate a high precision/recall for issue identification as well as decent accuracy for pinpointing the exact issue in the data.
        This should help streamline data validation for eval sets across a variety of domains.
      </description>
      <link>https://cookbook.openai.com/examples/o1/using_reasoning_for_data_validation</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/o1/using_reasoning_for_data_validation</guid>
      <pubDate>Wed, 11 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Reasoning</category>
    </item>
    <item>
      <title>Using reasoning for routine generation</title>
      <description>When developing customer service solutions, one of the initial steps involves transforming knowledge base articles into a set of routines that an LLM can comprehend and follow. A routine, in this context, refers to a set of step-by-step instructions designed specifically for the LLM to execute efficiently. Each routine is carefully structured so that a step corresponds to a clear action. Actions can include responding to a user, triggering a function call, or retrieving additional relevant knowledge.
        Most internal knowledge base articles are complex and structured for human interpretation. They often include intricate diagrams, multi-step processes, and decision trees that pose challenges for LLM-based solutions to reason through in a meaningful way. By breaking down these documents into routines, each instruction can be simplified and formatted in a way that guides the LLM through a series of small, manageable tasks. This granular approach reduces ambiguity, allowing the LLM to process the information methodically and reducing the risk of hallucination or deviation from the expected path.
        Converting these knowledge base articles into routines can be time-consuming and challenging, especially for companies attempting to build an automated pipeline. Each routine must account for various user scenarios, where actions need to be clearly defined. For instance, when a function call is necessary, the routine must specify the exact information to retrieve or the action to execute—whether it’s triggering an API, retrieving external data, or pulling in additional context. While automating this process with traditional GPT-class models can significantly reduce the manual effort involved, it often introduces new challenges. Some challenges include designing robust instructions that are specific enough for the LLM to follow consistently, capturing unique edge cases that may arise during customer interactions, providing high-quality few-shot examples to guide the model’s behavior, and in some cases, fine-tuning the model to achieve more reliable or specialized outcomes.
        o1 has demonstrated the capability to efficiently deconstruct these articles and convert them into sets of routines zero-shot, meaning that the LLM can understand and follow the instructions without extensive examples or prior training on similar tasks. This minimizes the prompting effort required, as the routine structure itself provides the necessary guidance for the LLM to complete each step. By breaking down tasks into specific actions and integrating function calls where needed, o1’s approach ensures that even complex workflows can be handled seamlessly by the LLM, leading to more effective and scalable customer service solutions.
        Selecting Knowledge Base Articles
        In this example, we will use a set of publicly available Help Center articles from the OpenAI website and convert them into internal routines that an LLM can execute. Besides transforming the policies into routines, we will also have the model generate functions that allow the LLM to perform actions on behalf of the user. This is necessary to allow the LLM to execute the same actions that human agents have, and access additional information that may not be immediately available just from the policy documentation.
        We will begin by using the following Help Center articles for conversion into routines:
        How do I delete my payment method
        How can I get a Business Associate Agreement (BAA) with OpenAI?
        How can I set up prepaid billing?
        How do I submit a VAT exemption request
        We have our articles stored in an accessible csv. We will take the articles and pass them to o1-preview in parallel and generate the initial routines.
        Our instructions for converting the policy to a routine include:
        Converting the policy from an external facing document to an internal SOP routine
        Breaking down the policy in specific actions and sub-actions
        Outlining specific conditions for moving between steps
        Determing where external knowledge/actions may be required, and defining functions that we could use to get that information
        We&#39;ll store the results of our routines in a dataframe and print them out so we can get an initial look.
        Results
        Upon reviewing the generated routines, we can derive several insights:
        Sample Responses: The model effectively generates sample responses that the LLM can utilize when executing the policy (e.g., “Instruct the user: ‘Confirm and purchase your initial amount of credits.’”).
        Discrete Steps: The model excels at decomposing the problem into discrete actions that the LLM needs to execute. Each instruction is clearly defined and easy to interpret.
        Function Definitions: The routines’ outputs include clearly defined functions to retrieve external information or trigger actions (e.g., rev

github-actions[bot] avatar Oct 20 '24 03:10 github-actions[bot]

Successfully generated as following:

http://localhost:1200/cookbook - Success ✔️
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <title>OpenAI Cookbook</title>
    <link>https://cookbook.openai.com/</link>
    <atom:link href="http://localhost:1200/cookbook" rel="self" type="application/rss+xml"></atom:link>
    <description>OpenAI Cookbook - Powered by RSSHub</description>
    <generator>RSSHub</generator>
    <webMaster>[email protected] (RSSHub)</webMaster>
    <language>en</language>
    <lastBuildDate>Sun, 20 Oct 2024 04:26:29 GMT</lastBuildDate>
    <ttl>5</ttl>
    <item>
      <title>Leveraging model distillation to fine-tune a model</title>
      <description>OpenAI recently released Distillation which allows to leverage the outputs of a (large) model to fine-tune another (smaller) model. This can significantly reduce the price and the latency for specific tasks as you move to a smaller model. In this cookbook we&#39;ll look at a dataset, distill the output of gpt-4o to gpt-4o-mini and show how we can get significantly better results than on a generic, non-distilled, 4o-mini.
        We&#39;ll also leverage Structured Outputs for a classification problem using a list of enum. We&#39;ll see how fine-tuned model can benefit from structured output and how it will impact the performance. We&#39;ll show that Structured Ouputs work with all of those models, including the distilled one.
        We&#39;ll first analyze the dataset, get the output of both 4o and 4o mini, highlighting the difference in performance of both models, then proceed to the distillation and analyze the performance of this distilled model.
        Prerequisites
        Let&#39;s install and load dependencies.
        Make sure your OpenAI API key is defined in your environment as &quot;OPENAI_API_KEY&quot; and it&#39;ll be loaded by the client directly.
        Loading and understanding the dataset
        For this cookbook, we&#39;ll load the data from the following Kaggle challenge: https://www.kaggle.com/datasets/zynicide/wine-reviews.
        This dataset has a large number of rows and you&#39;re free to run this cookbook on the whole data, but as a biaised french wine-lover, I&#39;ll narrow down the dataset to only French wine to focus on less rows and grape varieties.
        We&#39;re looking at a classification problem where we&#39;d like to guess the grape variety based on all other criterias available, including description, subregion and province that we&#39;ll include in the prompt. It gives a lot of information to the model, you&#39;re free to also remove some information that can help significantly the model such as the region in which it was produced to see if it does a good job at finding the grape.
        Let&#39;s filter the grape varieties that have less than 5 occurences in reviews.
        Let&#39;s proceed with a subset of 500 random rows from this dataset.
        Let&#39;s retrieve all grape varieties to include them in the prompt and in our structured outputs enum list.
        Generating the prompt
        Let&#39;s build out a function to generate our prompt and try it for the first wine of our list.
        To get a understanding of the cost before running the queries, you can leverage tiktoken to understand the number of tokens we&#39;ll send and the cost associated to run this. This will only give you an estimate for to run the completions, not the fine-tuning process (used later in this cookbook when running the distillation), which depends on other factors such as the number of epochs, training set etc.
        Preparing functions to Store Completions
        As we&#39;re looking at a limited list of response (enumerate list of grape varieties), let&#39;s leverage structured outputs so we make sure the model will answer from this list. This also allows us to compare the model&#39;s answer directly with the grape variety and have a deterministic answer (compared to a model that could answer &quot;I think the grape is Pinot Noir&quot; instead of just &quot;Pinot noir&quot;), on top of improving the performance to avoid grape varieties not in our dataset.
        If you want to know more on Structured Outputs you can read this cookbook and this documentation guide.
        To distill a model, you need to store all completions from a model, allowing you to give it as a reference to the smaller model to fine-tune it. We&#39;re therefore adding a store=True parameter to our client.chat.completions.create method so we can store those completions from gpt-4o.
        We&#39;re going to store all completions (even 4o-mini and our future fine-tuned model) so we are able to run Evals from OpenAI platform directly.
        When storing those completions, it&#39;s useful to store them with a metadata tag, that will allow filtering from the OpenAI platform to run distillation &amp;amp; evals on the specific set of completions you&#39;d like to run those.
        Parallel processing
        As we&#39;ll run this on a large number of rows, let&#39;s make sure we run those completions in parallel and use concurrent futures for this. We&#39;ll iterate on our dataframe and output progress every 20 rows. We&#39;ll store the completion from the model we run the completion for in the same dataframe using the column name {model}-variety.
        Let&#39;s try out our call model function before processing the whole dataframe and check the output.
        Great! We confirmed we can get a grape variety as an output, let&#39;s now process the dataset with both gpt-4o and gpt-4o-mini and compare the results.
        Comparing gpt-4o and gpt-4o-mini
        Now that we&#39;ve got all chat completions for those two models ; let&#39;s compare them against the expected grape variety and assess their accuracy at finding it. We&#39;ll do this directly in python here as we&#39;ve got a simple string check to run, but if your task involves more complex evals you can leverage OpenAI Evals or our open-source eval framework.
        We can see that gpt-4o is better a finding grape variety than 4o-mini (12.80% higher or almost 20% relatively to 4o-mini!). Now I&#39;m wondering if we&#39;re making gpt-4o drink wine during training!
        Distilling gpt-4o outputs to gpt-4o-mini
        Let&#39;s assume we&#39;d like to run this prediction often, we want completions to be faster and cheaper, but keep that level of accuracy. That&#39;d be great to be able to distill 4o accuracy to 4o-mini, wouldn&#39;t it? Let&#39;s do it!
        We&#39;ll now go to OpenAI Stored completions page: https://platform.openai.com/chat-completions.
        Let&#39;s select the model gpt-4o (make sure to do this, you don&#39;t want to distill the outputs of 4o-mini that we ran). Let&#39;s also select the metadata distillation: wine-distillation to get only stored completions ran from this cookbook.
        Once you&#39;ve selected completions, you can click on &quot;Distill&quot; on the top right corner to fine-tune a model based on those completions. Once we&#39;ve done that, a file to run the fine-tuning process will automatically be created. Let&#39;s then select gpt-4o-mini as the base model, keep the default parameters (but you&#39;re free to change them or iterate with it to improve performance).
        Once the fine-tuning job is starting, you can retrieve the fine tuning job ID from the fine-tuning page, we&#39;ll use it to monitor status of the fine-tuned job as well as retrieving the fine-tuned model id once done.
        Running completions for the distilled model
        Now that we&#39;ve got our model fine-tuned, we can use this model to run completions and compare accuracy with both gpt4o and gpt4o-mini.
        Let&#39;s grab a different subset of french wines (as we restricted the outputs to french grape varieties, without outliers, we&#39;ll need to focus our validation dataset to this too). Let&#39;s run this on 300 entries for each models.
        Let&#39;s compare accuracy of models
        That&#39;s almost a 22% relative improvement over the non-distilled gpt-4o-mini! 🎉
        Our fine-tuned model performs way better than gpt-4o-mini, while having the same base model. We&#39;ll be able to use this model to run inferences at a lower cost and lower latency for future grape variety prediction.
      </description>
      <link>https://cookbook.openai.com/examples/leveraging_model_distillation_to_fine-tune_a_model</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/leveraging_model_distillation_to_fine-tune_a_model</guid>
      <pubDate>Tue, 15 Oct 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Fine-tuning</category>
    </item>
    <item>
      <title>Orchestrating Agents: Routines and Handoffs</title>
      <description>When working with language models, quite often all you need for solid performance is a good prompt and the right tools. However, when dealing with many unique flows, things may get hairy. This cookbook will walk through one way to tackle this.
        We&#39;ll introduce the notion of routines and handoffs, then walk through the implementation and show how they can be used to orchestrate multiple agents in a simple, powerful, and controllable way.
        Finally, we provide a sample repo, Swarm, that implements these ideas along with examples.
        Let&#39;s start by setting up our imports.
        Routines
        The notion of a &quot;routine&quot; is not strictly defined, and instead meant to capture the idea of a set of steps. Conretely, let&#39;s define a routine to be a list of instructions in natural langauge (which we&#39;ll represent with a system prompt), along with the tools necessary to complete them.
        Let&#39;s take a look at an example. Below, we&#39;ve defined a routine for a customer service agent instructing it to triage the user issue, then either suggest a fix or provide a refund. We&#39;ve also defined the necessary functions execute_refund and look_up_item. We can call this a customer service routine, agent, assistant, etc –&amp;nbsp;however the idea itself is the same: a set of steps and the tools to execute them.
        The main power of routines is their simplicity and robustness. Notice that these instructions contain conditionals much like a state machine or branching in code. LLMs can actually handle these cases quite robustly for small and medium sized routine, with the added benefit of having &quot;soft&quot; adherance –&amp;nbsp;the LLM can naturally steer the conversation without getting stuck in dead-ends.
        Executing Routines
        To execute a routine, let&#39;s implement a simple loop that:
        Gets user input.
        Appends user message to messages.
        Calls the model.
        Appends model response to messages.
        As you can see, this currently ignores function calls, so let&#39;s add that.
        Models require functions to be formatted as a function schema. For convenience, we can define a helper function that turns python functions into the corresponding function schema.
        For example:
        Now, we can use this function to pass the tools to the model when we call it.
        Finally, when the model calls a tool we need to execute the corresponding function and provide the result back to the model.
        We can do this by mapping the name of the tool to the python function in a tool_map, then looking it up in execute_tool_call and calling it. Finally we add the result to the conversation.
        In practice, we&#39;ll also want to let the model use the result to produce another response. That response might also contain a tool call, so we can just run this in a loop until there are no more tool calls.
        If we put everything together, it will look something like this:
        Now that we have a routine, let&#39;s say we want to add more steps and more tools. We can up to a point, but eventually if we try growing the routine with too many different tasks it may start to struggle. This is where we can leverage the notion of multiple routines – given a user request, we can load the right routine with the appropriate steps and tools to address it.
        Dynamically swapping system instructions and tools may seem daunting. However, if we view &quot;routines&quot; as &quot;agents&quot;, then this notion of handoffs allow us to represent these swaps simply –&amp;nbsp;as one agent handing off a conversation to another.
        Handoffs
        Let&#39;s define a handoff as an agent (or routine) handing off an active conversation to another agent, much like when you get transfered to someone else on a phone call. Except in this case, the agents have complete knowledge of your prior conversation!
        To see handoffs in action, let&#39;s start by defining a basic class for an Agent.
        Now to make our code support it, we can change run_full_turn to take an Agent instead of separate system_message and tools:
        We can now run multiple agents easily:
        Great! But we did the handoff manually here –&amp;nbsp;we want the agents themselves to decide when to perform a handoff. A simple, but surprisingly effective way to do this is by giving them a transfer_to_XXX function, where XXX is some agent. The model is smart enough to know to call this function when it makes sense to make a handoff!
        Handoff Functions
        Now that agent can express the intent to make a handoff, we must make it actually happen. There&#39;s many ways to do this, but there&#39;s one particularly clean way.
        For the agent functions we&#39;ve defined so far, like execute_refund or place_order they return a string, which will be provided to the model. What if instead, we return an Agent object to indate which agent we want to transfer to? Like so:
        We can then update our code to check the return type of a function response, and if it&#39;s an Agent, update the agent in use! Additionally, now run_full_turn will need to return the latest agent in use in case there are handoffs. (We can do this in a Response class to keep things neat.)
        Now for the updated run_full_turn:
        Let&#39;s look at an example with more Agents.
        Finally, we can run this in a loop (this won&#39;t run in python notebooks, so you can try this in a separate python file):
        Swarm
        As a proof of concept, we&#39;ve packaged these ideas into a sample library called Swarm. It is meant as an example only, and should not be directly used in production. However, feel free to take the ideas and code to build your own!
      </description>
      <link>https://cookbook.openai.com/examples/orchestrating_agents</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/orchestrating_agents</guid>
      <pubDate>Wed, 09 Oct 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Functions</category>
    </item>
    <item>
      <title>Prompt Caching 101</title>
      <description>OpenAI offers discounted prompt caching for prompts exceeding 1024 tokens, resulting in up to an 80% reduction in latency for longer prompts over 10,000 tokens. By caching repetitive information across LLM API requests, you can greatly reduce both latency and costs. Prompt caching is scoped at the organization level, meaning only members of the same organization can access shared caches. Additionally, caching is eligible for zero data retention, as no data is stored during the process.
        Prompt caching automatically activates for prompts longer than 1024 tokens-- you don&#39;t have to change anything in your completions request. When an API request is made, the system first checks if the beginning portion (prefix) of the prompt has already been cached. If a match is found (cache hit), the cached prompt is used, leading to reduced latency and costs. If there&#39;s no match, the system processes the full prompt from scratch and caches the prefix for future use.
        With these benefits in mind, some of the key use cases where prompt caching can be especially advantageous are:
        Agents using tools and structured outputs: Cache the extended list of tools and schemas.
        Coding and writing assistants: Insert large sections or summaries of codebases and workspaces directly in prompts.
        Chatbots: Cache static portions of multi-turn conversations to maintain context efficiently over extended dialogues.
        In this cookbook, we&#39;ll go through a couple examples of caching tools and images. Recall that in general, you&#39;ll want to put static content like instructions and examples at the beginning of your prompt, and variable content, such as user-specific information, at the end. This also applies to images and tools, which must be identical even in their ordering between requests. All requests, including those with fewer than 1024 tokens, will display a cached_tokens field of the usage.prompt_tokens_details chat completions object indicating how many of the prompt tokens were a cache hit. For requests under 1024 tokens, cached_tokens will be zero. Caching discounts are based on the actual number of tokens processed, including those used for images, which also count toward your rate limits.
        Example 1: Caching tools and multi-turn conversations
        In this example, we define tools and interactions for a customer support assistant, capable of handling tasks such as checking delivery dates, canceling orders, and updating payment methods. The assistant processes two separate messages, first responding to an initial query, followed by a delayed response to a follow-up query.
        When caching tools, it is important that the tool definitions and their order remain identical for them to be included in the prompt prefix. To cache message histories in a multi-turn conversation, append new elements to the end of the messages array. In the response object and the output below, for the second completion run2, you can see that the cached_tokens value is greater than zero, indicating successful caching.
        Example 2: Images
        In our second example we include multiple image URLs of grocery items in the messages array, along with a user query, run three times with delays. Images—whether linked or encoded in base64 within user messages—qualify for caching. Make sure the detail parameter remains consistent, as it affects how images are tokenized. Note that GPT-4o-mini adds extra tokens to cover image processing costs, even though it uses a low-cost token model for text. Caching discounts are based on the actual number of tokens processed, including those used for images, which also count toward your rate limits.
        The output for this example shows that a cache was hit for the second run, however it was not hit for the third run because of a different first url (eggs_url instead of veggie_url), even though the user query is the same.
        Overall tips
        To get the most out of prompt caching, consider following these best practices:
        Place static or frequently reused content at the beginning of prompts: This helps ensure better cache efficiency by keeping dynamic data towards the end of the prompt.
        Maintain consistent usage patterns: Prompts that aren&#39;t used regularly are automatically removed from the cache. To prevent cache evictions, maintain consistent usage of prompts.
        Monitor key metrics: Regularly track cache hit rates, latency, and the proportion of cached tokens. Use these insights to fine-tune your caching strategy and maximize performance.
        By implementing these practices, you can take full advantage of prompt caching, ensuring that your applications are both responsive and cost-efficient. A well-managed caching strategy will significantly reduce processing times, lower costs, and help maintain smooth user experiences.
      </description>
      <link>https://cookbook.openai.com/examples/prompt_caching101</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/prompt_caching101</guid>
      <pubDate>Mon, 30 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
    </item>
    <item>
      <title>Using chained calls for o1 structured outputs</title>
      <description>The initially released versions (September 2024) of o1 reasoning models have advanced capabilities but do not have structured outputs support.
        This means that requests with o1 don&#39;t have reliable type-safety and rely on the prompt itself to return a useful JSON.
        In this guide, we&#39;ll explore two methods to prompt o1 models, specifically o1-preview, to return a valid JSON format when using the OpenAI API.
        Prompting
        The simplest way to return a JSON response using o1-preview is to explicitly prompt it.
        Let&#39;s run through an example of:
        Fetching a wikipedia page of companies
        Determining which could benefit the most from AI capabilities
        Returning them in a JSON format, which could then be ingested by other systems
        Note that the response is already quite good - it returns the JSON with the appropriate responses. However, it runs into the same pitfalls as existing use-cases of prompt-only JSON inference:
        You must manually process this JSON into your type-safe structure
        Model refusals are not explicitly returned from the API as a separate structure
        Structured Outputs
        Let&#39;s now do this with structured outputs. To enable this functionality, we’ll link the o1-preview response with a follow-up request to gpt-4o-mini, which can effectively process the data returned from the initial o1-preview response.
        Conclusion
        Structured outputs allow your code to have reliable type-safety and simpler prompting. In addition, it allows you to re-use your object schemas for easier integration into your existing workflows.
        The o1 class of models currently doesn&#39;t have structured outputs support, but we can re-use existing structured outputs functionality from gpt-4o-mini by chaining two requests together. This flow currently requires two calls, but the second gpt-4o-mini call cost should be minimal compared to the o1-preview/o1-mini calls.
      </description>
      <link>https://cookbook.openai.com/examples/o1/using_chained_calls_for_o1_structured_outputs</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/o1/using_chained_calls_for_o1_structured_outputs</guid>
      <pubDate>Wed, 25 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Reasoning</category>
    </item>
    <item>
      <title>Building a Bring Your Own Browser (BYOB) Tool for Web Browsing and Summarization</title>
      <description>Disclaimer: This cookbook is for educational purposes only. Ensure that you comply with all applicable laws and service terms when using web search and scraping technologies. This cookbook will restrict the search to openai.com domain to retrieve the public information to illustrate the concepts.
        Large Language Models (LLMs) such as GPT-4o have a knowledge cutoff date, which means they lack information about events that occurred after that point. In scenarios where the most recent data is essential, it&#39;s necessary to provide LLMs with access to current web information to ensure accurate and relevant responses.
        In this guide, we will build a Bring Your Own Browser (BYOB) tool using Python to overcome this limitation. Our goal is to create a system that provides up-to-date answers in your application, including the most recent developments such as the latest product launches by OpenAI. By integrating web search capabilities with an LLM, we&#39;ll enable the model to generate responses based on the latest information available online.
        While you can use any publicly available search APIs, we&#39;ll utilize Google&#39;s Custom Search API to perform web searches. The retrieved information from the search results will be processed and passed to the LLM to generate the final response through Retrieval-Augmented Generation (RAG).
        Bring Your Own Browser (BYOB) tools allow users to perform web browsing tasks programmatically. In this notebook, we&#39;ll create a BYOB tool that:
        #1. Set Up a Search Engine: Use a public search API, such as Google&#39;s Custom Search API, to perform web searches and obtain a list of relevant search results.
        #2. Build a Search Dictionary: Collect the title, URL, and a summary of each web page from the search results to create a structured dictionary of information.
        #3. Generate a RAG Response: Implement Retrieval-Augmented Generation (RAG) by passing the gathered information to the LLM, which then generates a final response to the user&#39;s query.
        Use Case
        In this cookbook, we&#39;ll take the example of a user who wants to list recent product launches by OpenAI in chronological order. Because the current GPT-4o model has a knowledge cutoff date, it is not expected that the model will know about recent product launches such as the o1-preview model launched in September 2024.
        Given the knowledge cutoff, as expected the model does not know about the recent product launches by OpenAI.
        Setting up a BYOB tool
        To provide the model with recent events information, we&#39;ll follow these steps:
        Step 1: Set Up a Search Engine to Provide Web Search Results
        Step 2: Build a Search Dictionary with Titles, URLs, and Summaries of Web Pages
        Step 3: Pass the information to the model to generate a RAG Response to the User Query
        Before we begin, ensure you have the following: Python 3.12 or later installed on your machine. You will also need a Google Custom Search API key and Custom Search Engine ID (CSE ID). Necessary Python packages installed: requests, beautifulsoup4, openai. And ensure the OPENAI_API_KEY is set up as an environment variable.
        Step 1: Set Up a Search Engine to Provide Web Search Results
        You can use any publicly available web search APIs to perform this task. We will configure a custom search engine using Google&#39;s Custom Search API. This engine will fetch a list of relevant web pages based on the user&#39;s query, focusing on obtaining the most recent and pertinent results.
        a. Configure Search API key and Function: Acquire a Google API key and a Custom Search Engine ID (CSE ID) from the Google Developers Console. You can navigate to this Programmable Search Engine Link to set up an API key as well as Custom Search Engine ID (CSE ID).
        The search function below sets up the search based on search term, the API and CSE ID keys, as well as number of search results to return. We&#39;ll introduce a parameter site_filter to restrict the output to only openai.com
        b. Identify the search terms for search engine: Before we can retrieve specific results from a 3rd Party API, we may need to use Query Expansion to identify specific terms our browser search API should retrieve. Query expansion is a process where we broaden the original user query by adding related terms, synonyms, or variations. This technique is essential because search engines, like Google&#39;s Custom Search API, are often better at matching a range of related terms rather than just the natural language prompt used by a user.
        For example, searching with only the raw query &quot;List the latest OpenAI product launches in chronological order from latest to oldest in the past 2 years&quot; may return fewer and less relevant results than a more specific and direct search on a succinct phrase such as &quot;Latest OpenAI product launches&quot;. In the code below, we will use the user&#39;s original search_query to produce a more specific search term to use with the Google API to retrieve the results.
        c. Invoke the search function: Now that we have the search term, we will invoke the search function to retrieve the results from Google search API. The results only have the link of the web page and a snippet at this point. In the next step, we will retrieve more information from the webpage and summarize it in a dictionary to pass to the model.
        Step 2: Build a Search Dictionary with Titles, URLs, and Summaries of Web Pages
        After obtaining the search results, we&#39;ll extract and organize the relevant information, so it can be passed to the LLM for final output.
        a. Scrape Web Page Content: For each URL in the search results, retrieve the web page to extract textual content while filtering out non-relevant data like scripts and advertisements as demonstrated in function retrieve_content.
        b. Summarize Content: Use an LLM to generate concise summaries of the scraped content, focusing on information pertinent to the user&#39;s query. Model can be provided the original search text, so it can focus on summarizing the content for the search intent as outlined in function summarize_content.
        c. Create a Structured Dictionary: Organize the data into a dictionary or a DataFrame containing the title, link, and summary for each web page. This structure can be passed on to the LLM to generate the summary with the appropriate citations.
        We retrieved the most recent results. (Note these will vary depending on when you execute this script.)
        Step 3: Pass the information to the model to generate a RAG Response to the User Query
        With the search data organized in a JSON data structure, we will pass this information to the LLM with the original user query to generate the final response. Now, the LLM response includes information beyond its original knowledge cutoff, providing current insights.
        Conclusion
        Large Language Models (LLMs) have a knowledge cutoff and may not be aware of recent events. To provide them with the latest information, you can build a Bring Your Own Browser (BYOB) tool using Python. This tool retrieves current web data and feeds it to the LLM, enabling up-to-date responses.
        The process involves three main steps:
        #1 Set Up a Search Engine: Use a public search API, like Google&#39;s Custom Search API, to perform web searches and obtain a list of relevant search results.
        #2 Build a Search Dictionary: Collect the title, URL, and a summary of each web page from the search results to create a structured dictionary of information.
        #3. Generate a RAG Response: Implement Retrieval-Augmented Generation (RAG) by passing the gathered information to the LLM, which then generates a final response to the user&#39;s query.
        By following these steps, you enhance the LLMs ability to provide up-to-date answers in your application that include the most recent developments, such as the latest product launches by OpenAI.
      </description>
      <link>https://cookbook.openai.com/examples/third_party/web_search_with_google_api_bring_your_own_browser_tool</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/third_party/web_search_with_google_api_bring_your_own_browser_tool</guid>
      <pubDate>Wed, 25 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
    </item>
    <item>
      <title>GPT Actions library - Canvas Learning Management System</title>
      <description>Table of Contents
        General App Information - Overview of Canvas LMS, its functionality, and the role of ChatGPT&#39;s Custom Actions to enhance educational experiences through AI integration.
        Authentication from ChatGPT to Canvas - Explanation of authentication methods (OAuth and User Generated Access Tokens) for connecting ChatGPT to Canvas, with detailed instructions for setting up each option.
        Sample Use Case: Student Course Assistant - Detailed example of using ChatGPT to assist students with course navigation, exam preparation, and personalized feedback, including specific API calls and workflows.
        Other Use Cases for Consideration - Additional potential integrations using the Canvas API, such as classroom analytics and report generation.
        Congratulations
        General App Information
        Canvas is a widely-used Learning Management System (LMS) designed to support online learning and teaching. It offers a robust set of tools for course management, content delivery, assessments, and student collaboration. Through the Canvas REST API, Canvas allows for extensive customization and integration with third-party applications, including AI-powered tools like ChatGPT.
        ChatGPT’s Custom Actions with Canvas enable educators to leverage AI to enhance course content, automate tasks, and provide personalized learning journeys for students. Examples include virtual teaching assistants based on active courses, as the capabilities are well-suited for pulling information in from Canvas to create an educational dialogue. ChatGPT with Custom Actions is not meant for automating the entire Canvas experience nor act as a replacement to many of its capabilities better suited for completion in the Canvas app.
        Authentication from ChatGPT to Canvas
        For a general overview on Authentication in Custom Actions, see the Action authentication documentation.
        There are two options for authentication in Canvas: 1) OAuth and 2) User Generated Access Tokens.
        For large-scale deployments, it is required to use OAuth for Action Authentication.
        If the user is considering a single-user deployment or does not have access to Admin Settings, they may consider User Generated Access Tokens. Be aware that any request made by the action will be made using the token the user generated, so Canvas will register all requests as the user&#39;s activity and use the user&#39;s permissions to complete them.
        Implementing OAuth for Canvas
        While this Canvas Cookbook does not use OAuth, any deployment with more than one user must use it. See OAuth for Canvas Documentation for a detailed walkthrough.
        Here are some things to keep in mind while implementing OAuth in a Canvas Custom Action:
        Access to Canvas’ Admin settings is required for OAuth in order to retrieve a Client ID and Client Secret.
        The Authorization URL will look like (make sure to update the Canvas Install URL): https:///login/oauth2/auth
        The Token URL will look like (make sure to update the Canvas Install URL): ttps:///login/oauth2/token
        Scopes may not need to be defined in the Custom Action. If the developer key does not require scopes and no scope parameter is specified, the access token will have access to all scopes. If the developer key does require scopes and no scope parameter is specified, Canvas will respond with &quot;invalid_scope.&quot; More information on developer keys here and endpoints here.
        Token Exchange Method is Default (POST Request)
        Canvas uses the term redirect_uri where ChatGPT uses the term Callback URL for URL to complete the redirect process after successful authentication.
        Implementing authentication with User Generated Access Tokens
        In some cases, it may be appropriate to use User Generated Access Tokens for Custom Action authentication with Canvas. Here are the steps to follow to do so:
        Proceed to Canvas Account Settings shown here:
        Scroll down to the List of Tokens shown here:
        Generate a New Token, and store this token. It will not be accessible later.
        Sample Use Case: Student Course Assistant
        Overview
        Assists students in navigating and understanding their courses by providing detailed information, generating personalized practice exams, and offering constructive feedback to enhance learning.
        Considerations
        Some information like the Syllabus is returned as an HTML page when requested by the API. This renders it impossible to show in ChatGPT. Instead, reference course description, modules, and the assignments to guide the user.
        Requests can be modified to retrieve specific pieces of information using the include[] query parameter. If you need to request specific information about a course, provide an example in the GPT instructions.
        GPT Instructions
        There can be multiple ways to write these instructions. See here for guidance on Prompt Engineering strategies and best practices.
        # **Context:** You support college students by providing detailed information about their courses hosted on the Canvas Learning Management System. You help them understand course content, generate practice exams based on provided materials, and offer insightful feedback to aid their learning journey. Assume the students are familiar with basic academic terminologies.
        # **Instructions:**
        ## Scenarios
        ### - When the user asks for information about a specific course, follow this 5 step process:
        1. Ask the user to specify the course they want assistance with and the particular area of focus (e.g., overall course overview, specific module).
        2. If you do not know the Course ID for the course requested, use the listYourCourses to find the right course and corresponding ID in Canvas. If none of the courses listed returned courses that seem to match the course request, use the searchCourses to see if there are any similarly named course.
        3. Retrieve the course information from Canvas using the getSingleCourse API call and the listModules API call.
        4. Ask the user which module(s) they would like to focus on and use the listModuleItems to retrieve the requested module items. For any assignments, share links to them.
        5. Ask if the user needs more information or if they need to prepare for an exam.
        ### When a user asks to take a practice test or practice exam for a specific course, follow this 6 step process:
        1. Ask how many questions
        2. Ask which chapters or topics they want to be tested on, provide a couple examples from the course modules in Canvas.
        3. Ask 1 question at a time, be sure the questions are multiple choice (do not generate the next question until the question is answered)
        4. When the user answers, tell them if its right or wrong and give a description for the correct answer
        5. Ask the user if they want to export the test results and write the code to create the PDF
        6. Offer additional resources and study tips tailored to the user&#39;s needs and progress, and inquire if they require further assistance with other courses or topics.
        ### When a user asks to create a study guide
        - Format the generated study guide in a table
        OpenAPI Schema
        API Calls Featured
        [GET] listYourCourses
        [GET] getSingleCourse
        [GET] listModules
        [GET] listModuleItems
        [GET] searchCourses
        Below was generated with a combination of Canvas API Reference and the ActionsGPT.
        openapi: 3.1.0
        info:
        title: Canvas API
        description: API for interacting with Canvas LMS, including courses, modules, module items, and search functionalities.
        version: 1.0.0
        servers:
        - url: https://canvas.instructure.com/api/v1
        description: Canvas LMS API server
        variables:
        domain:
        default: canvas.instructure.com
        description: The domain of your Canvas instance
        paths:
        /courses:
        get:
        operationId: listYourCourses
        summary: List your courses
        description: Retrieves a paginated list of active courses for the current user.
        parameters:
        - name: enrollment_type
        in: query
        description: Filter by enrollment type (e.g., &quot;teacher&quot;, &quot;student&quot;).
        schema:
        type: string
        - name: enrollment_role
        in: query
        description: Filter by role type. Requires admin permissions.
        schema:
        type: string
        - name: enrollment_state
        in: query
        description: Filter by enrollment state (e.g., &quot;active&quot;, &quot;invited&quot;).
        schema:
        type: string
        - name: exclude_blueprint_courses
        in: query
        description: Exclude Blueprint courses if true.
        schema:
        type: boolean
        - name: include
        in: query
        description: Array of additional information to include (e.g., &quot;term&quot;, &quot;teachers&quot;).
        schema:
        type: array
        items:
        type: string
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of courses.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the course.
        name:
        type: string
        description: The name of the course.
        account_id:
        type: integer
        description: The ID of the account associated with the course.
        enrollment_term_id:
        type: integer
        description: The ID of the term associated with the course.
        start_at:
        type: string
        format: date-time
        description: The start date of the course.
        end_at:
        type: string
        format: date-time
        description: The end date of the course.
        course_code:
        type: string
        description: The course code.
        state:
        type: string
        description: The current state of the course (e.g., &quot;unpublished&quot;, &quot;available&quot;).
        &#39;400&#39;:
        description: Bad request, possibly due to invalid query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        /courses/{course_id}:
        get:
        operationId: getSingleCourse
        summary: Get a single course
        description: Retrieves the details of a specific course by its ID.
        parameters:
        - name: course_id
        in: path
        required: true
        description: The ID of the course.
        schema:
        type: integer
        - name: include
        in: query
        description: Array of additional information to include (e.g., &quot;term&quot;, &quot;teachers&quot;).
        schema:
        type: array
        items:
        type: string
        responses:
        &#39;200&#39;:
        description: A single course object.
        content:
        application/json:
        schema:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the course.
        name:
        type: string
        description: The name of the course.
        account_id:
        type: integer
        description: The ID of the account associated with the course.
        enrollment_term_id:
        type: integer
        description: The ID of the term associated with the course.
        start_at:
        type: string
        format: date-time
        description: The start date of the course.
        end_at:
        type: string
        format: date-time
        description: The end date of the course.
        course_code:
        type: string
        description: The course code.
        state:
        type: string
        description: The current state of the course (e.g., &quot;unpublished&quot;, &quot;available&quot;).
        is_public:
        type: boolean
        description: Whether the course is public.
        syllabus_body:
        type: string
        description: The syllabus content of the course.
        term:
        type: object
        description: The term associated with the course.
        properties:
        id:
        type: integer
        name:
        type: string
        start_at:
        type: string
        format: date-time
        end_at:
        type: string
        format: date-time
        &#39;400&#39;:
        description: Bad request, possibly due to an invalid course ID or query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: Course not found, possibly due to an invalid course ID.
        /courses/{course_id}/modules:
        get:
        operationId: listModules
        summary: List modules in a course
        description: Retrieves the list of modules for a given course in Canvas.
        parameters:
        - name: course_id
        in: path
        required: true
        description: The ID of the course.
        schema:
        type: integer
        - name: include
        in: query
        description: Include additional information such as items in the response.
        schema:
        type: array
        items:
        type: string
        example: [&quot;items&quot;]
        - name: search_term
        in: query
        description: The partial title of the module to match and return.
        schema:
        type: string
        - name: student_id
        in: query
        description: Return module completion information for the student with this ID.
        schema:
        type: integer
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of modules in the course.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the module.
        name:
        type: string
        description: The name of the module.
        items_count:
        type: integer
        description: The number of items in the module.
        state:
        type: string
        description: The state of the module (e.g., &quot;active&quot;, &quot;locked&quot;).
        &#39;400&#39;:
        description: Bad request, possibly due to an invalid course ID or query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: Course not found, possibly due to an invalid course ID.
        /courses/{course_id}/modules/{module_id}/items:
        get:
        operationId: listModuleItems
        summary: List items in a module
        description: Retrieves the list of items within a specific module in a Canvas course.
        parameters:
        - name: course_id
        in: path
        required: true
        description: The ID of the course.
        schema:
        type: integer
        - name: module_id
        in: path
        required: true
        description: The ID of the module.
        schema:
        type: integer
        - name: include
        in: query
        description: Include additional information in the response, such as content details.
        schema:
        type: array
        items:
        type: string
        example: [&quot;content_details&quot;]
        - name: student_id
        in: query
        description: Return completion information for the student with this ID.
        schema:
        type: integer
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of items in the module.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the module item.
        title:
        type: string
        description: The title of the module item.
        type:
        type: string
        description: The type of the module item (e.g., &quot;Assignment&quot;, &quot;File&quot;).
        position:
        type: integer
        description: The position of the item within the module.
        indent:
        type: integer
        description: The level of indentation of the item in the module.
        completion_requirement:
        type: object
        description: The completion requirement for the item.
        properties:
        type:
        type: string
        min_score:
        type: integer
        content_id:
        type: integer
        description: The ID of the associated content item (e.g., assignment, file).
        state:
        type: string
        description: The state of the item (e.g., &quot;active&quot;, &quot;locked&quot;).
        &#39;400&#39;:
        description: Bad request, possibly due to an invalid module ID or query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: Module or course not found, possibly due to an invalid module or course ID.
        /search/all_courses:
        get:
        operationId: searchCourses
        summary: Search for courses
        description: Searches for public courses in Canvas.
        parameters:
        - name: search
        in: query
        description: The search term to filter courses.
        schema:
        type: string
        - name: public_only
        in: query
        description: If true, only returns public courses.
        schema:
        type: boolean
        - name: open_enrollment_only
        in: query
        description: If true, only returns courses with open enrollment.
        schema:
        type: boolean
        - name: enrollment_type
        in: query
        description: Filter by enrollment type (e.g., &quot;teacher&quot;, &quot;student&quot;).
        schema:
        type: string
        - name: sort
        in: query
        description: Sort the results by &quot;asc&quot; or &quot;desc&quot; order.
        schema:
        type: string
        enum:
        - asc
        - desc
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of courses matching the search criteria.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the course.
        name:
        type: string
        description: The name of the course.
        account_id:
        type: integer
        description: The ID of the account associated with the course.
        enrollment_term_id:
        type: integer
        description: The ID of the term associated with the course.
        start_at:
        type: string
        format: date-time
        description: The start date of the course.
        end_at:
        type: string
        format: date-time
        description: The end date of the course.
        course_code:
        type: string
        description: The course code.
        state:
        type: string
        description: The current state of the course (e.g., &quot;unpublished&quot;, &quot;available&quot;).
        is_public:
        type: boolean
        description: Whether the course is public.
        term:
        type: object
        description: The term associated with the course.
        properties:
        id:
        type: integer
        name:
        type: string
        start_at:
        type: string
        format: date-time
        end_at:
        type: string
        format: date-time
        &#39;400&#39;:
        description: Bad request, possibly due to invalid query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: No courses found matching the criteria.
        Sample Conversation Starters
        Help me take a practice exam.
        Give an overview of one of my courses.
        List all of my courses.
        GPT Capabilities
        [On] Web Browsing
        [On] DALL·E Image Generation
        [On] Code Interpreter &amp;amp; Data Analysis
        Other Use Cases for Consideration
        Below is a non-exhaustive list of additional use cases that could be explored using the Canvas API. The basic outline for each is provided, but the GPT Instructions and specific API calls referenced are intentionally left to you as the user to decide what works best for your needs.
        Classroom Analytics and Reports
        Use Case: Empowers teachers with comprehensive analytics and performance reports on student engagement, grades, and participation. By leveraging this data, teachers can make informed decisions to tailor their course delivery, identify at-risk students, and enhance overall classroom effectiveness.
        API Resources:
        Analytics and Quiz Statistics: Retrieve detailed data on student participation, grades, and course-level statistics.
        Quiz Reports: Generate and view various reports to analyze overall class performance and track progress over time.
        Review and Improvement Guidance for Graded Assignments
        Use Case: Provide students with a tool to review their graded assignments, analyze their performance, and receive targeted guidance on how to improve in areas where they have knowledge gaps. The tool can highlight specific questions or sections where the student struggled and suggest additional resources or practice materials to help them improve.
        API Resources:
        Submissions and Quiz Submissions: Retrieve the student’s submissions and associated grades.
        Assignments: Retrieve detailed information about the assignment, including rubrics and grading criteria.
        Rubric Assessments: Access detailed feedback and rubric assessments
        Modules: Suggest additional learning modules that target the student’s weak areas using the List modules API.
        Quizzes: Recommend practice quizzes to help the student improve on specific knowledge gaps
        Congratulations!
        You’ve successfully created a Custom GPT with a working Custom Action using Canvas LMS. You should be able to have a conversation that looks similar to the screenshot below. Great job and keep going!
      </description>
      <link>https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_canvas</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_canvas</guid>
      <pubDate>Mon, 16 Sep 2024 16:00:00 GMT</pubDate>
      <category>ChatGPT</category>
      <category>GPT actions library</category>
    </item>
    <item>
      <title>Using reasoning for data validation</title>
      <description>In this guide, we’ll explore how to use the o1 model, specifically o1-preview, to perform data validation through reasoning. We’ll walk through a practical example involving a synthetic medical dataset and demonstrate how to assess the model’s accuracy in identifying issues within the data.
        Overview
        Data validation is a critical step in ensuring the quality and reliability of datasets, especially in sensitive fields like healthcare. Traditional validation methods often rely on predefined rules and patterns. However, advanced models like o1 can understand context and reason about data, offering a more flexible and intelligent approach to validation.
        In this tutorial, we will:
        Generate a synthetic dataset of medical data that contains inconsistencies.
        Define a function that takes in a row of data and validates its accuracy
        Run the validation process and compute accuracy metrics.
        Analyze and interpret the results.
        Synthetic Data Generation
        We will use a lot of the principles described in the Synthetic Data Generation cookbook to create the foundation of our dataset.
        We will prompt the model to generate sets of medical data for our use case. We have provide detailed instructions to the model on how to create the dataset, what format to follow, and how to fill it with inaccuracies. We also provide a few rows of sample data to get the model started.
        Each row in the dataset will have the following fields:
        Patient ID: A randomly generated patient id
        Date of Birth: Date of birth of the patient
        Gender: M/F
        Medical History: Past diagnoses
        Current Medications: Medication the patient is taking
        Allergies: Identified allergies
        Lab Results (Glucose mg/dL)
        Diagnoses: Current diagnosis
        Treatment Plan: Current treatment plan
        Is Valid: Whether or not the current row of data is valid (True/False)
        Issue: If the row of data is not valid, what the issue is
        Some examples of inaccuracies that may be present in the data are:
        Prescribing medications that the patient is allergic to
        Current medications do not match medical history
        Treatment plan does not match diagnosis
        Data Validation
        Now that we have our dataset prepared, we will prompt the reasoning model to review each row of data and determine whether or not it contains an issue. We will ask the model to output whether or not there is an issue in the data and then offer an explanation of the issue.
        Once we have the model determine its list of invalid data, we will pass those results on to a model grader to assess two metrics:
        Accuracy of the model&#39;s ability correctly identify issues with the data
        For the subset of data that issues have been correctly identified, what is the accuracy of the model in identifying the issue at hand
        Given that this task is much more narrow, we can use the faster gpt-4o model to calculate the accuracy.
        REMINDER: Given that these models are still in beta, rate limits will be significantly reduced. Please adjust the number of concurrent workers accordingly.
        Now that we have the model&#39;s results, we can compare it against the source of truth and determine the system&#39;s accuracy
        Issue Identification
        We will now determine the model&#39;s ability to accurately classify the issue in the data
        Below we&#39;ll display the subset of rows that we correctly identified contained an issue. For each row, we&#39;ll show the predicted vs. true issue and whether or not there is a match
        Conclusion
        We can see from the results here that we&#39;re able to generate a high precision/recall for issue identification as well as decent accuracy for pinpointing the exact issue in the data.
        This should help streamline data validation for eval sets across a variety of domains.
      </description>
      <link>https://cookbook.openai.com/examples/o1/using_reasoning_for_data_validation</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/o1/using_reasoning_for_data_validation</guid>
      <pubDate>Wed, 11 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Reasoning</category>
    </item>
    <item>
      <title>Using reasoning for routine generation</title>
      <description>When developing customer service solutions, one of the initial steps involves transforming knowledge base articles into a set of routines that an LLM can comprehend and follow. A routine, in this context, refers to a set of step-by-step instructions designed specifically for the LLM to execute efficiently. Each routine is carefully structured so that a step corresponds to a clear action. Actions can include responding to a user, triggering a function call, or retrieving additional relevant knowledge.
        Most internal knowledge base articles are complex and structured for human interpretation. They often include intricate diagrams, multi-step processes, and decision trees that pose challenges for LLM-based solutions to reason through in a meaningful way. By breaking down these documents into routines, each instruction can be simplified and formatted in a way that guides the LLM through a series of small, manageable tasks. This granular approach reduces ambiguity, allowing the LLM to process the information methodically and reducing the risk of hallucination or deviation from the expected path.
        Converting these knowledge base articles into routines can be time-consuming and challenging, especially for companies attempting to build an automated pipeline. Each routine must account for various user scenarios, where actions need to be clearly defined. For instance, when a function call is necessary, the routine must specify the exact information to retrieve or the action to execute—whether it’s triggering an API, retrieving external data, or pulling in additional context. While automating this process with traditional GPT-class models can significantly reduce the manual effort involved, it often introduces new challenges. Some challenges include designing robust instructions that are specific enough for the LLM to follow consistently, capturing unique edge cases that may arise during customer interactions, providing high-quality few-shot examples to guide the model’s behavior, and in some cases, fine-tuning the model to achieve more reliable or specialized outcomes.
        o1 has demonstrated the capability to efficiently deconstruct these articles and convert them into sets of routines zero-shot, meaning that the LLM can understand and follow the instructions without extensive examples or prior training on similar tasks. This minimizes the prompting effort required, as the routine structure itself provides the necessary guidance for the LLM to complete each step. By breaking down tasks into specific actions and integrating function calls where needed, o1’s approach ensures that even complex workflows can be handled seamlessly by the LLM, leading to more effective and scalable customer service solutions.
        Selecting Knowledge Base Articles
        In this example, we will use a set of publicly available Help Center articles from the OpenAI website and convert them into internal routines that an LLM can execute. Besides transforming the policies into routines, we will also have the model generate functions that allow the LLM to perform actions on behalf of the user. This is necessary to allow the LLM to execute the same actions that human agents have, and access additional information that may not be immediately available just from the policy documentation.
        We will begin by using the following Help Center articles for conversion into routines:
        How do I delete my payment method
        How can I get a Business Associate Agreement (BAA) with OpenAI?
        How can I set up prepaid billing?
        How do I submit a VAT exemption request
        We have our articles stored in an accessible csv. We will take the articles and pass them to o1-preview in parallel and generate the initial routines.
        Our instructions for converting the policy to a routine include:
        Converting the policy from an external facing document to an internal SOP routine
        Breaking down the policy in specific actions and sub-actions
        Outlining specific conditions for moving between steps
        Determing where external knowledge/actions may be required, and defining functions that we could use to get that information
        We&#39;ll store the results of our routines in a dataframe and print them out so we can get an initial look.
        Results
        Upon reviewing the generated routines, we can derive several insights:
        Sample Responses: The model effectively generates sample responses that the LLM can utilize when executing the policy (e.g., “Instruct the user: ‘Confirm and purchase your initial amount of credits.’”).
        Discrete Steps: The model excels at decomposing the problem into discrete actions that the LLM needs to execute. Each instruction is clearly defined and easy to interpret.
        Function Definitions: The routines’ outputs include clearly defined functions to retrieve external information or trigger actions (e.g., rev

github-actions[bot] avatar Oct 20 '24 04:10 github-actions[bot]

Successfully generated as following:

http://localhost:1200/cookbook - Success ✔️
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <title>OpenAI Cookbook</title>
    <link>https://cookbook.openai.com/</link>
    <atom:link href="http://localhost:1200/cookbook" rel="self" type="application/rss+xml"></atom:link>
    <description>OpenAI Cookbook - Powered by RSSHub</description>
    <generator>RSSHub</generator>
    <webMaster>[email protected] (RSSHub)</webMaster>
    <language>en</language>
    <lastBuildDate>Sun, 20 Oct 2024 04:38:37 GMT</lastBuildDate>
    <ttl>5</ttl>
    <item>
      <title>Leveraging model distillation to fine-tune a model</title>
      <description>OpenAI recently released Distillation which allows to leverage the outputs of a (large) model to fine-tune another (smaller) model. This can significantly reduce the price and the latency for specific tasks as you move to a smaller model. In this cookbook we&#39;ll look at a dataset, distill the output of gpt-4o to gpt-4o-mini and show how we can get significantly better results than on a generic, non-distilled, 4o-mini.
        We&#39;ll also leverage Structured Outputs for a classification problem using a list of enum. We&#39;ll see how fine-tuned model can benefit from structured output and how it will impact the performance. We&#39;ll show that Structured Ouputs work with all of those models, including the distilled one.
        We&#39;ll first analyze the dataset, get the output of both 4o and 4o mini, highlighting the difference in performance of both models, then proceed to the distillation and analyze the performance of this distilled model.
        Prerequisites
        Let&#39;s install and load dependencies.
        Make sure your OpenAI API key is defined in your environment as &quot;OPENAI_API_KEY&quot; and it&#39;ll be loaded by the client directly.
        Loading and understanding the dataset
        For this cookbook, we&#39;ll load the data from the following Kaggle challenge: https://www.kaggle.com/datasets/zynicide/wine-reviews.
        This dataset has a large number of rows and you&#39;re free to run this cookbook on the whole data, but as a biaised french wine-lover, I&#39;ll narrow down the dataset to only French wine to focus on less rows and grape varieties.
        We&#39;re looking at a classification problem where we&#39;d like to guess the grape variety based on all other criterias available, including description, subregion and province that we&#39;ll include in the prompt. It gives a lot of information to the model, you&#39;re free to also remove some information that can help significantly the model such as the region in which it was produced to see if it does a good job at finding the grape.
        Let&#39;s filter the grape varieties that have less than 5 occurences in reviews.
        Let&#39;s proceed with a subset of 500 random rows from this dataset.
        Let&#39;s retrieve all grape varieties to include them in the prompt and in our structured outputs enum list.
        Generating the prompt
        Let&#39;s build out a function to generate our prompt and try it for the first wine of our list.
        To get a understanding of the cost before running the queries, you can leverage tiktoken to understand the number of tokens we&#39;ll send and the cost associated to run this. This will only give you an estimate for to run the completions, not the fine-tuning process (used later in this cookbook when running the distillation), which depends on other factors such as the number of epochs, training set etc.
        Preparing functions to Store Completions
        As we&#39;re looking at a limited list of response (enumerate list of grape varieties), let&#39;s leverage structured outputs so we make sure the model will answer from this list. This also allows us to compare the model&#39;s answer directly with the grape variety and have a deterministic answer (compared to a model that could answer &quot;I think the grape is Pinot Noir&quot; instead of just &quot;Pinot noir&quot;), on top of improving the performance to avoid grape varieties not in our dataset.
        If you want to know more on Structured Outputs you can read this cookbook and this documentation guide.
        To distill a model, you need to store all completions from a model, allowing you to give it as a reference to the smaller model to fine-tune it. We&#39;re therefore adding a store=True parameter to our client.chat.completions.create method so we can store those completions from gpt-4o.
        We&#39;re going to store all completions (even 4o-mini and our future fine-tuned model) so we are able to run Evals from OpenAI platform directly.
        When storing those completions, it&#39;s useful to store them with a metadata tag, that will allow filtering from the OpenAI platform to run distillation &amp;amp; evals on the specific set of completions you&#39;d like to run those.
        Parallel processing
        As we&#39;ll run this on a large number of rows, let&#39;s make sure we run those completions in parallel and use concurrent futures for this. We&#39;ll iterate on our dataframe and output progress every 20 rows. We&#39;ll store the completion from the model we run the completion for in the same dataframe using the column name {model}-variety.
        Let&#39;s try out our call model function before processing the whole dataframe and check the output.
        Great! We confirmed we can get a grape variety as an output, let&#39;s now process the dataset with both gpt-4o and gpt-4o-mini and compare the results.
        Comparing gpt-4o and gpt-4o-mini
        Now that we&#39;ve got all chat completions for those two models ; let&#39;s compare them against the expected grape variety and assess their accuracy at finding it. We&#39;ll do this directly in python here as we&#39;ve got a simple string check to run, but if your task involves more complex evals you can leverage OpenAI Evals or our open-source eval framework.
        We can see that gpt-4o is better a finding grape variety than 4o-mini (12.80% higher or almost 20% relatively to 4o-mini!). Now I&#39;m wondering if we&#39;re making gpt-4o drink wine during training!
        Distilling gpt-4o outputs to gpt-4o-mini
        Let&#39;s assume we&#39;d like to run this prediction often, we want completions to be faster and cheaper, but keep that level of accuracy. That&#39;d be great to be able to distill 4o accuracy to 4o-mini, wouldn&#39;t it? Let&#39;s do it!
        We&#39;ll now go to OpenAI Stored completions page: https://platform.openai.com/chat-completions.
        Let&#39;s select the model gpt-4o (make sure to do this, you don&#39;t want to distill the outputs of 4o-mini that we ran). Let&#39;s also select the metadata distillation: wine-distillation to get only stored completions ran from this cookbook.
        Once you&#39;ve selected completions, you can click on &quot;Distill&quot; on the top right corner to fine-tune a model based on those completions. Once we&#39;ve done that, a file to run the fine-tuning process will automatically be created. Let&#39;s then select gpt-4o-mini as the base model, keep the default parameters (but you&#39;re free to change them or iterate with it to improve performance).
        Once the fine-tuning job is starting, you can retrieve the fine tuning job ID from the fine-tuning page, we&#39;ll use it to monitor status of the fine-tuned job as well as retrieving the fine-tuned model id once done.
        Running completions for the distilled model
        Now that we&#39;ve got our model fine-tuned, we can use this model to run completions and compare accuracy with both gpt4o and gpt4o-mini.
        Let&#39;s grab a different subset of french wines (as we restricted the outputs to french grape varieties, without outliers, we&#39;ll need to focus our validation dataset to this too). Let&#39;s run this on 300 entries for each models.
        Let&#39;s compare accuracy of models
        That&#39;s almost a 22% relative improvement over the non-distilled gpt-4o-mini! 🎉
        Our fine-tuned model performs way better than gpt-4o-mini, while having the same base model. We&#39;ll be able to use this model to run inferences at a lower cost and lower latency for future grape variety prediction.
      </description>
      <link>https://cookbook.openai.com/examples/leveraging_model_distillation_to_fine-tune_a_model</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/leveraging_model_distillation_to_fine-tune_a_model</guid>
      <pubDate>Tue, 15 Oct 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Fine-tuning</category>
    </item>
    <item>
      <title>Orchestrating Agents: Routines and Handoffs</title>
      <description>When working with language models, quite often all you need for solid performance is a good prompt and the right tools. However, when dealing with many unique flows, things may get hairy. This cookbook will walk through one way to tackle this.
        We&#39;ll introduce the notion of routines and handoffs, then walk through the implementation and show how they can be used to orchestrate multiple agents in a simple, powerful, and controllable way.
        Finally, we provide a sample repo, Swarm, that implements these ideas along with examples.
        Let&#39;s start by setting up our imports.
        Routines
        The notion of a &quot;routine&quot; is not strictly defined, and instead meant to capture the idea of a set of steps. Conretely, let&#39;s define a routine to be a list of instructions in natural langauge (which we&#39;ll represent with a system prompt), along with the tools necessary to complete them.
        Let&#39;s take a look at an example. Below, we&#39;ve defined a routine for a customer service agent instructing it to triage the user issue, then either suggest a fix or provide a refund. We&#39;ve also defined the necessary functions execute_refund and look_up_item. We can call this a customer service routine, agent, assistant, etc –&amp;nbsp;however the idea itself is the same: a set of steps and the tools to execute them.
        The main power of routines is their simplicity and robustness. Notice that these instructions contain conditionals much like a state machine or branching in code. LLMs can actually handle these cases quite robustly for small and medium sized routine, with the added benefit of having &quot;soft&quot; adherance –&amp;nbsp;the LLM can naturally steer the conversation without getting stuck in dead-ends.
        Executing Routines
        To execute a routine, let&#39;s implement a simple loop that:
        Gets user input.
        Appends user message to messages.
        Calls the model.
        Appends model response to messages.
        As you can see, this currently ignores function calls, so let&#39;s add that.
        Models require functions to be formatted as a function schema. For convenience, we can define a helper function that turns python functions into the corresponding function schema.
        For example:
        Now, we can use this function to pass the tools to the model when we call it.
        Finally, when the model calls a tool we need to execute the corresponding function and provide the result back to the model.
        We can do this by mapping the name of the tool to the python function in a tool_map, then looking it up in execute_tool_call and calling it. Finally we add the result to the conversation.
        In practice, we&#39;ll also want to let the model use the result to produce another response. That response might also contain a tool call, so we can just run this in a loop until there are no more tool calls.
        If we put everything together, it will look something like this:
        Now that we have a routine, let&#39;s say we want to add more steps and more tools. We can up to a point, but eventually if we try growing the routine with too many different tasks it may start to struggle. This is where we can leverage the notion of multiple routines – given a user request, we can load the right routine with the appropriate steps and tools to address it.
        Dynamically swapping system instructions and tools may seem daunting. However, if we view &quot;routines&quot; as &quot;agents&quot;, then this notion of handoffs allow us to represent these swaps simply –&amp;nbsp;as one agent handing off a conversation to another.
        Handoffs
        Let&#39;s define a handoff as an agent (or routine) handing off an active conversation to another agent, much like when you get transfered to someone else on a phone call. Except in this case, the agents have complete knowledge of your prior conversation!
        To see handoffs in action, let&#39;s start by defining a basic class for an Agent.
        Now to make our code support it, we can change run_full_turn to take an Agent instead of separate system_message and tools:
        We can now run multiple agents easily:
        Great! But we did the handoff manually here –&amp;nbsp;we want the agents themselves to decide when to perform a handoff. A simple, but surprisingly effective way to do this is by giving them a transfer_to_XXX function, where XXX is some agent. The model is smart enough to know to call this function when it makes sense to make a handoff!
        Handoff Functions
        Now that agent can express the intent to make a handoff, we must make it actually happen. There&#39;s many ways to do this, but there&#39;s one particularly clean way.
        For the agent functions we&#39;ve defined so far, like execute_refund or place_order they return a string, which will be provided to the model. What if instead, we return an Agent object to indate which agent we want to transfer to? Like so:
        We can then update our code to check the return type of a function response, and if it&#39;s an Agent, update the agent in use! Additionally, now run_full_turn will need to return the latest agent in use in case there are handoffs. (We can do this in a Response class to keep things neat.)
        Now for the updated run_full_turn:
        Let&#39;s look at an example with more Agents.
        Finally, we can run this in a loop (this won&#39;t run in python notebooks, so you can try this in a separate python file):
        Swarm
        As a proof of concept, we&#39;ve packaged these ideas into a sample library called Swarm. It is meant as an example only, and should not be directly used in production. However, feel free to take the ideas and code to build your own!
      </description>
      <link>https://cookbook.openai.com/examples/orchestrating_agents</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/orchestrating_agents</guid>
      <pubDate>Wed, 09 Oct 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Functions</category>
    </item>
    <item>
      <title>Prompt Caching 101</title>
      <description>OpenAI offers discounted prompt caching for prompts exceeding 1024 tokens, resulting in up to an 80% reduction in latency for longer prompts over 10,000 tokens. By caching repetitive information across LLM API requests, you can greatly reduce both latency and costs. Prompt caching is scoped at the organization level, meaning only members of the same organization can access shared caches. Additionally, caching is eligible for zero data retention, as no data is stored during the process.
        Prompt caching automatically activates for prompts longer than 1024 tokens-- you don&#39;t have to change anything in your completions request. When an API request is made, the system first checks if the beginning portion (prefix) of the prompt has already been cached. If a match is found (cache hit), the cached prompt is used, leading to reduced latency and costs. If there&#39;s no match, the system processes the full prompt from scratch and caches the prefix for future use.
        With these benefits in mind, some of the key use cases where prompt caching can be especially advantageous are:
        Agents using tools and structured outputs: Cache the extended list of tools and schemas.
        Coding and writing assistants: Insert large sections or summaries of codebases and workspaces directly in prompts.
        Chatbots: Cache static portions of multi-turn conversations to maintain context efficiently over extended dialogues.
        In this cookbook, we&#39;ll go through a couple examples of caching tools and images. Recall that in general, you&#39;ll want to put static content like instructions and examples at the beginning of your prompt, and variable content, such as user-specific information, at the end. This also applies to images and tools, which must be identical even in their ordering between requests. All requests, including those with fewer than 1024 tokens, will display a cached_tokens field of the usage.prompt_tokens_details chat completions object indicating how many of the prompt tokens were a cache hit. For requests under 1024 tokens, cached_tokens will be zero. Caching discounts are based on the actual number of tokens processed, including those used for images, which also count toward your rate limits.
        Example 1: Caching tools and multi-turn conversations
        In this example, we define tools and interactions for a customer support assistant, capable of handling tasks such as checking delivery dates, canceling orders, and updating payment methods. The assistant processes two separate messages, first responding to an initial query, followed by a delayed response to a follow-up query.
        When caching tools, it is important that the tool definitions and their order remain identical for them to be included in the prompt prefix. To cache message histories in a multi-turn conversation, append new elements to the end of the messages array. In the response object and the output below, for the second completion run2, you can see that the cached_tokens value is greater than zero, indicating successful caching.
        Example 2: Images
        In our second example we include multiple image URLs of grocery items in the messages array, along with a user query, run three times with delays. Images—whether linked or encoded in base64 within user messages—qualify for caching. Make sure the detail parameter remains consistent, as it affects how images are tokenized. Note that GPT-4o-mini adds extra tokens to cover image processing costs, even though it uses a low-cost token model for text. Caching discounts are based on the actual number of tokens processed, including those used for images, which also count toward your rate limits.
        The output for this example shows that a cache was hit for the second run, however it was not hit for the third run because of a different first url (eggs_url instead of veggie_url), even though the user query is the same.
        Overall tips
        To get the most out of prompt caching, consider following these best practices:
        Place static or frequently reused content at the beginning of prompts: This helps ensure better cache efficiency by keeping dynamic data towards the end of the prompt.
        Maintain consistent usage patterns: Prompts that aren&#39;t used regularly are automatically removed from the cache. To prevent cache evictions, maintain consistent usage of prompts.
        Monitor key metrics: Regularly track cache hit rates, latency, and the proportion of cached tokens. Use these insights to fine-tune your caching strategy and maximize performance.
        By implementing these practices, you can take full advantage of prompt caching, ensuring that your applications are both responsive and cost-efficient. A well-managed caching strategy will significantly reduce processing times, lower costs, and help maintain smooth user experiences.
      </description>
      <link>https://cookbook.openai.com/examples/prompt_caching101</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/prompt_caching101</guid>
      <pubDate>Mon, 30 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
    </item>
    <item>
      <title>Using chained calls for o1 structured outputs</title>
      <description>The initially released versions (September 2024) of o1 reasoning models have advanced capabilities but do not have structured outputs support.
        This means that requests with o1 don&#39;t have reliable type-safety and rely on the prompt itself to return a useful JSON.
        In this guide, we&#39;ll explore two methods to prompt o1 models, specifically o1-preview, to return a valid JSON format when using the OpenAI API.
        Prompting
        The simplest way to return a JSON response using o1-preview is to explicitly prompt it.
        Let&#39;s run through an example of:
        Fetching a wikipedia page of companies
        Determining which could benefit the most from AI capabilities
        Returning them in a JSON format, which could then be ingested by other systems
        Note that the response is already quite good - it returns the JSON with the appropriate responses. However, it runs into the same pitfalls as existing use-cases of prompt-only JSON inference:
        You must manually process this JSON into your type-safe structure
        Model refusals are not explicitly returned from the API as a separate structure
        Structured Outputs
        Let&#39;s now do this with structured outputs. To enable this functionality, we’ll link the o1-preview response with a follow-up request to gpt-4o-mini, which can effectively process the data returned from the initial o1-preview response.
        Conclusion
        Structured outputs allow your code to have reliable type-safety and simpler prompting. In addition, it allows you to re-use your object schemas for easier integration into your existing workflows.
        The o1 class of models currently doesn&#39;t have structured outputs support, but we can re-use existing structured outputs functionality from gpt-4o-mini by chaining two requests together. This flow currently requires two calls, but the second gpt-4o-mini call cost should be minimal compared to the o1-preview/o1-mini calls.
      </description>
      <link>https://cookbook.openai.com/examples/o1/using_chained_calls_for_o1_structured_outputs</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/o1/using_chained_calls_for_o1_structured_outputs</guid>
      <pubDate>Wed, 25 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Reasoning</category>
    </item>
    <item>
      <title>Building a Bring Your Own Browser (BYOB) Tool for Web Browsing and Summarization</title>
      <description>Disclaimer: This cookbook is for educational purposes only. Ensure that you comply with all applicable laws and service terms when using web search and scraping technologies. This cookbook will restrict the search to openai.com domain to retrieve the public information to illustrate the concepts.
        Large Language Models (LLMs) such as GPT-4o have a knowledge cutoff date, which means they lack information about events that occurred after that point. In scenarios where the most recent data is essential, it&#39;s necessary to provide LLMs with access to current web information to ensure accurate and relevant responses.
        In this guide, we will build a Bring Your Own Browser (BYOB) tool using Python to overcome this limitation. Our goal is to create a system that provides up-to-date answers in your application, including the most recent developments such as the latest product launches by OpenAI. By integrating web search capabilities with an LLM, we&#39;ll enable the model to generate responses based on the latest information available online.
        While you can use any publicly available search APIs, we&#39;ll utilize Google&#39;s Custom Search API to perform web searches. The retrieved information from the search results will be processed and passed to the LLM to generate the final response through Retrieval-Augmented Generation (RAG).
        Bring Your Own Browser (BYOB) tools allow users to perform web browsing tasks programmatically. In this notebook, we&#39;ll create a BYOB tool that:
        #1. Set Up a Search Engine: Use a public search API, such as Google&#39;s Custom Search API, to perform web searches and obtain a list of relevant search results.
        #2. Build a Search Dictionary: Collect the title, URL, and a summary of each web page from the search results to create a structured dictionary of information.
        #3. Generate a RAG Response: Implement Retrieval-Augmented Generation (RAG) by passing the gathered information to the LLM, which then generates a final response to the user&#39;s query.
        Use Case
        In this cookbook, we&#39;ll take the example of a user who wants to list recent product launches by OpenAI in chronological order. Because the current GPT-4o model has a knowledge cutoff date, it is not expected that the model will know about recent product launches such as the o1-preview model launched in September 2024.
        Given the knowledge cutoff, as expected the model does not know about the recent product launches by OpenAI.
        Setting up a BYOB tool
        To provide the model with recent events information, we&#39;ll follow these steps:
        Step 1: Set Up a Search Engine to Provide Web Search Results
        Step 2: Build a Search Dictionary with Titles, URLs, and Summaries of Web Pages
        Step 3: Pass the information to the model to generate a RAG Response to the User Query
        Before we begin, ensure you have the following: Python 3.12 or later installed on your machine. You will also need a Google Custom Search API key and Custom Search Engine ID (CSE ID). Necessary Python packages installed: requests, beautifulsoup4, openai. And ensure the OPENAI_API_KEY is set up as an environment variable.
        Step 1: Set Up a Search Engine to Provide Web Search Results
        You can use any publicly available web search APIs to perform this task. We will configure a custom search engine using Google&#39;s Custom Search API. This engine will fetch a list of relevant web pages based on the user&#39;s query, focusing on obtaining the most recent and pertinent results.
        a. Configure Search API key and Function: Acquire a Google API key and a Custom Search Engine ID (CSE ID) from the Google Developers Console. You can navigate to this Programmable Search Engine Link to set up an API key as well as Custom Search Engine ID (CSE ID).
        The search function below sets up the search based on search term, the API and CSE ID keys, as well as number of search results to return. We&#39;ll introduce a parameter site_filter to restrict the output to only openai.com
        b. Identify the search terms for search engine: Before we can retrieve specific results from a 3rd Party API, we may need to use Query Expansion to identify specific terms our browser search API should retrieve. Query expansion is a process where we broaden the original user query by adding related terms, synonyms, or variations. This technique is essential because search engines, like Google&#39;s Custom Search API, are often better at matching a range of related terms rather than just the natural language prompt used by a user.
        For example, searching with only the raw query &quot;List the latest OpenAI product launches in chronological order from latest to oldest in the past 2 years&quot; may return fewer and less relevant results than a more specific and direct search on a succinct phrase such as &quot;Latest OpenAI product launches&quot;. In the code below, we will use the user&#39;s original search_query to produce a more specific search term to use with the Google API to retrieve the results.
        c. Invoke the search function: Now that we have the search term, we will invoke the search function to retrieve the results from Google search API. The results only have the link of the web page and a snippet at this point. In the next step, we will retrieve more information from the webpage and summarize it in a dictionary to pass to the model.
        Step 2: Build a Search Dictionary with Titles, URLs, and Summaries of Web Pages
        After obtaining the search results, we&#39;ll extract and organize the relevant information, so it can be passed to the LLM for final output.
        a. Scrape Web Page Content: For each URL in the search results, retrieve the web page to extract textual content while filtering out non-relevant data like scripts and advertisements as demonstrated in function retrieve_content.
        b. Summarize Content: Use an LLM to generate concise summaries of the scraped content, focusing on information pertinent to the user&#39;s query. Model can be provided the original search text, so it can focus on summarizing the content for the search intent as outlined in function summarize_content.
        c. Create a Structured Dictionary: Organize the data into a dictionary or a DataFrame containing the title, link, and summary for each web page. This structure can be passed on to the LLM to generate the summary with the appropriate citations.
        We retrieved the most recent results. (Note these will vary depending on when you execute this script.)
        Step 3: Pass the information to the model to generate a RAG Response to the User Query
        With the search data organized in a JSON data structure, we will pass this information to the LLM with the original user query to generate the final response. Now, the LLM response includes information beyond its original knowledge cutoff, providing current insights.
        Conclusion
        Large Language Models (LLMs) have a knowledge cutoff and may not be aware of recent events. To provide them with the latest information, you can build a Bring Your Own Browser (BYOB) tool using Python. This tool retrieves current web data and feeds it to the LLM, enabling up-to-date responses.
        The process involves three main steps:
        #1 Set Up a Search Engine: Use a public search API, like Google&#39;s Custom Search API, to perform web searches and obtain a list of relevant search results.
        #2 Build a Search Dictionary: Collect the title, URL, and a summary of each web page from the search results to create a structured dictionary of information.
        #3. Generate a RAG Response: Implement Retrieval-Augmented Generation (RAG) by passing the gathered information to the LLM, which then generates a final response to the user&#39;s query.
        By following these steps, you enhance the LLMs ability to provide up-to-date answers in your application that include the most recent developments, such as the latest product launches by OpenAI.
      </description>
      <link>https://cookbook.openai.com/examples/third_party/web_search_with_google_api_bring_your_own_browser_tool</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/third_party/web_search_with_google_api_bring_your_own_browser_tool</guid>
      <pubDate>Wed, 25 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
    </item>
    <item>
      <title>GPT Actions library - Canvas Learning Management System</title>
      <description>Table of Contents
        General App Information - Overview of Canvas LMS, its functionality, and the role of ChatGPT&#39;s Custom Actions to enhance educational experiences through AI integration.
        Authentication from ChatGPT to Canvas - Explanation of authentication methods (OAuth and User Generated Access Tokens) for connecting ChatGPT to Canvas, with detailed instructions for setting up each option.
        Sample Use Case: Student Course Assistant - Detailed example of using ChatGPT to assist students with course navigation, exam preparation, and personalized feedback, including specific API calls and workflows.
        Other Use Cases for Consideration - Additional potential integrations using the Canvas API, such as classroom analytics and report generation.
        Congratulations
        General App Information
        Canvas is a widely-used Learning Management System (LMS) designed to support online learning and teaching. It offers a robust set of tools for course management, content delivery, assessments, and student collaboration. Through the Canvas REST API, Canvas allows for extensive customization and integration with third-party applications, including AI-powered tools like ChatGPT.
        ChatGPT’s Custom Actions with Canvas enable educators to leverage AI to enhance course content, automate tasks, and provide personalized learning journeys for students. Examples include virtual teaching assistants based on active courses, as the capabilities are well-suited for pulling information in from Canvas to create an educational dialogue. ChatGPT with Custom Actions is not meant for automating the entire Canvas experience nor act as a replacement to many of its capabilities better suited for completion in the Canvas app.
        Authentication from ChatGPT to Canvas
        For a general overview on Authentication in Custom Actions, see the Action authentication documentation.
        There are two options for authentication in Canvas: 1) OAuth and 2) User Generated Access Tokens.
        For large-scale deployments, it is required to use OAuth for Action Authentication.
        If the user is considering a single-user deployment or does not have access to Admin Settings, they may consider User Generated Access Tokens. Be aware that any request made by the action will be made using the token the user generated, so Canvas will register all requests as the user&#39;s activity and use the user&#39;s permissions to complete them.
        Implementing OAuth for Canvas
        While this Canvas Cookbook does not use OAuth, any deployment with more than one user must use it. See OAuth for Canvas Documentation for a detailed walkthrough.
        Here are some things to keep in mind while implementing OAuth in a Canvas Custom Action:
        Access to Canvas’ Admin settings is required for OAuth in order to retrieve a Client ID and Client Secret.
        The Authorization URL will look like (make sure to update the Canvas Install URL): https:///login/oauth2/auth
        The Token URL will look like (make sure to update the Canvas Install URL): ttps:///login/oauth2/token
        Scopes may not need to be defined in the Custom Action. If the developer key does not require scopes and no scope parameter is specified, the access token will have access to all scopes. If the developer key does require scopes and no scope parameter is specified, Canvas will respond with &quot;invalid_scope.&quot; More information on developer keys here and endpoints here.
        Token Exchange Method is Default (POST Request)
        Canvas uses the term redirect_uri where ChatGPT uses the term Callback URL for URL to complete the redirect process after successful authentication.
        Implementing authentication with User Generated Access Tokens
        In some cases, it may be appropriate to use User Generated Access Tokens for Custom Action authentication with Canvas. Here are the steps to follow to do so:
        Proceed to Canvas Account Settings shown here:
        Scroll down to the List of Tokens shown here:
        Generate a New Token, and store this token. It will not be accessible later.
        Sample Use Case: Student Course Assistant
        Overview
        Assists students in navigating and understanding their courses by providing detailed information, generating personalized practice exams, and offering constructive feedback to enhance learning.
        Considerations
        Some information like the Syllabus is returned as an HTML page when requested by the API. This renders it impossible to show in ChatGPT. Instead, reference course description, modules, and the assignments to guide the user.
        Requests can be modified to retrieve specific pieces of information using the include[] query parameter. If you need to request specific information about a course, provide an example in the GPT instructions.
        GPT Instructions
        There can be multiple ways to write these instructions. See here for guidance on Prompt Engineering strategies and best practices.
        # **Context:** You support college students by providing detailed information about their courses hosted on the Canvas Learning Management System. You help them understand course content, generate practice exams based on provided materials, and offer insightful feedback to aid their learning journey. Assume the students are familiar with basic academic terminologies.
        # **Instructions:**
        ## Scenarios
        ### - When the user asks for information about a specific course, follow this 5 step process:
        1. Ask the user to specify the course they want assistance with and the particular area of focus (e.g., overall course overview, specific module).
        2. If you do not know the Course ID for the course requested, use the listYourCourses to find the right course and corresponding ID in Canvas. If none of the courses listed returned courses that seem to match the course request, use the searchCourses to see if there are any similarly named course.
        3. Retrieve the course information from Canvas using the getSingleCourse API call and the listModules API call.
        4. Ask the user which module(s) they would like to focus on and use the listModuleItems to retrieve the requested module items. For any assignments, share links to them.
        5. Ask if the user needs more information or if they need to prepare for an exam.
        ### When a user asks to take a practice test or practice exam for a specific course, follow this 6 step process:
        1. Ask how many questions
        2. Ask which chapters or topics they want to be tested on, provide a couple examples from the course modules in Canvas.
        3. Ask 1 question at a time, be sure the questions are multiple choice (do not generate the next question until the question is answered)
        4. When the user answers, tell them if its right or wrong and give a description for the correct answer
        5. Ask the user if they want to export the test results and write the code to create the PDF
        6. Offer additional resources and study tips tailored to the user&#39;s needs and progress, and inquire if they require further assistance with other courses or topics.
        ### When a user asks to create a study guide
        - Format the generated study guide in a table
        OpenAPI Schema
        API Calls Featured
        [GET] listYourCourses
        [GET] getSingleCourse
        [GET] listModules
        [GET] listModuleItems
        [GET] searchCourses
        Below was generated with a combination of Canvas API Reference and the ActionsGPT.
        openapi: 3.1.0
        info:
        title: Canvas API
        description: API for interacting with Canvas LMS, including courses, modules, module items, and search functionalities.
        version: 1.0.0
        servers:
        - url: https://canvas.instructure.com/api/v1
        description: Canvas LMS API server
        variables:
        domain:
        default: canvas.instructure.com
        description: The domain of your Canvas instance
        paths:
        /courses:
        get:
        operationId: listYourCourses
        summary: List your courses
        description: Retrieves a paginated list of active courses for the current user.
        parameters:
        - name: enrollment_type
        in: query
        description: Filter by enrollment type (e.g., &quot;teacher&quot;, &quot;student&quot;).
        schema:
        type: string
        - name: enrollment_role
        in: query
        description: Filter by role type. Requires admin permissions.
        schema:
        type: string
        - name: enrollment_state
        in: query
        description: Filter by enrollment state (e.g., &quot;active&quot;, &quot;invited&quot;).
        schema:
        type: string
        - name: exclude_blueprint_courses
        in: query
        description: Exclude Blueprint courses if true.
        schema:
        type: boolean
        - name: include
        in: query
        description: Array of additional information to include (e.g., &quot;term&quot;, &quot;teachers&quot;).
        schema:
        type: array
        items:
        type: string
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of courses.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the course.
        name:
        type: string
        description: The name of the course.
        account_id:
        type: integer
        description: The ID of the account associated with the course.
        enrollment_term_id:
        type: integer
        description: The ID of the term associated with the course.
        start_at:
        type: string
        format: date-time
        description: The start date of the course.
        end_at:
        type: string
        format: date-time
        description: The end date of the course.
        course_code:
        type: string
        description: The course code.
        state:
        type: string
        description: The current state of the course (e.g., &quot;unpublished&quot;, &quot;available&quot;).
        &#39;400&#39;:
        description: Bad request, possibly due to invalid query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        /courses/{course_id}:
        get:
        operationId: getSingleCourse
        summary: Get a single course
        description: Retrieves the details of a specific course by its ID.
        parameters:
        - name: course_id
        in: path
        required: true
        description: The ID of the course.
        schema:
        type: integer
        - name: include
        in: query
        description: Array of additional information to include (e.g., &quot;term&quot;, &quot;teachers&quot;).
        schema:
        type: array
        items:
        type: string
        responses:
        &#39;200&#39;:
        description: A single course object.
        content:
        application/json:
        schema:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the course.
        name:
        type: string
        description: The name of the course.
        account_id:
        type: integer
        description: The ID of the account associated with the course.
        enrollment_term_id:
        type: integer
        description: The ID of the term associated with the course.
        start_at:
        type: string
        format: date-time
        description: The start date of the course.
        end_at:
        type: string
        format: date-time
        description: The end date of the course.
        course_code:
        type: string
        description: The course code.
        state:
        type: string
        description: The current state of the course (e.g., &quot;unpublished&quot;, &quot;available&quot;).
        is_public:
        type: boolean
        description: Whether the course is public.
        syllabus_body:
        type: string
        description: The syllabus content of the course.
        term:
        type: object
        description: The term associated with the course.
        properties:
        id:
        type: integer
        name:
        type: string
        start_at:
        type: string
        format: date-time
        end_at:
        type: string
        format: date-time
        &#39;400&#39;:
        description: Bad request, possibly due to an invalid course ID or query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: Course not found, possibly due to an invalid course ID.
        /courses/{course_id}/modules:
        get:
        operationId: listModules
        summary: List modules in a course
        description: Retrieves the list of modules for a given course in Canvas.
        parameters:
        - name: course_id
        in: path
        required: true
        description: The ID of the course.
        schema:
        type: integer
        - name: include
        in: query
        description: Include additional information such as items in the response.
        schema:
        type: array
        items:
        type: string
        example: [&quot;items&quot;]
        - name: search_term
        in: query
        description: The partial title of the module to match and return.
        schema:
        type: string
        - name: student_id
        in: query
        description: Return module completion information for the student with this ID.
        schema:
        type: integer
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of modules in the course.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the module.
        name:
        type: string
        description: The name of the module.
        items_count:
        type: integer
        description: The number of items in the module.
        state:
        type: string
        description: The state of the module (e.g., &quot;active&quot;, &quot;locked&quot;).
        &#39;400&#39;:
        description: Bad request, possibly due to an invalid course ID or query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: Course not found, possibly due to an invalid course ID.
        /courses/{course_id}/modules/{module_id}/items:
        get:
        operationId: listModuleItems
        summary: List items in a module
        description: Retrieves the list of items within a specific module in a Canvas course.
        parameters:
        - name: course_id
        in: path
        required: true
        description: The ID of the course.
        schema:
        type: integer
        - name: module_id
        in: path
        required: true
        description: The ID of the module.
        schema:
        type: integer
        - name: include
        in: query
        description: Include additional information in the response, such as content details.
        schema:
        type: array
        items:
        type: string
        example: [&quot;content_details&quot;]
        - name: student_id
        in: query
        description: Return completion information for the student with this ID.
        schema:
        type: integer
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of items in the module.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the module item.
        title:
        type: string
        description: The title of the module item.
        type:
        type: string
        description: The type of the module item (e.g., &quot;Assignment&quot;, &quot;File&quot;).
        position:
        type: integer
        description: The position of the item within the module.
        indent:
        type: integer
        description: The level of indentation of the item in the module.
        completion_requirement:
        type: object
        description: The completion requirement for the item.
        properties:
        type:
        type: string
        min_score:
        type: integer
        content_id:
        type: integer
        description: The ID of the associated content item (e.g., assignment, file).
        state:
        type: string
        description: The state of the item (e.g., &quot;active&quot;, &quot;locked&quot;).
        &#39;400&#39;:
        description: Bad request, possibly due to an invalid module ID or query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: Module or course not found, possibly due to an invalid module or course ID.
        /search/all_courses:
        get:
        operationId: searchCourses
        summary: Search for courses
        description: Searches for public courses in Canvas.
        parameters:
        - name: search
        in: query
        description: The search term to filter courses.
        schema:
        type: string
        - name: public_only
        in: query
        description: If true, only returns public courses.
        schema:
        type: boolean
        - name: open_enrollment_only
        in: query
        description: If true, only returns courses with open enrollment.
        schema:
        type: boolean
        - name: enrollment_type
        in: query
        description: Filter by enrollment type (e.g., &quot;teacher&quot;, &quot;student&quot;).
        schema:
        type: string
        - name: sort
        in: query
        description: Sort the results by &quot;asc&quot; or &quot;desc&quot; order.
        schema:
        type: string
        enum:
        - asc
        - desc
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of courses matching the search criteria.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the course.
        name:
        type: string
        description: The name of the course.
        account_id:
        type: integer
        description: The ID of the account associated with the course.
        enrollment_term_id:
        type: integer
        description: The ID of the term associated with the course.
        start_at:
        type: string
        format: date-time
        description: The start date of the course.
        end_at:
        type: string
        format: date-time
        description: The end date of the course.
        course_code:
        type: string
        description: The course code.
        state:
        type: string
        description: The current state of the course (e.g., &quot;unpublished&quot;, &quot;available&quot;).
        is_public:
        type: boolean
        description: Whether the course is public.
        term:
        type: object
        description: The term associated with the course.
        properties:
        id:
        type: integer
        name:
        type: string
        start_at:
        type: string
        format: date-time
        end_at:
        type: string
        format: date-time
        &#39;400&#39;:
        description: Bad request, possibly due to invalid query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: No courses found matching the criteria.
        Sample Conversation Starters
        Help me take a practice exam.
        Give an overview of one of my courses.
        List all of my courses.
        GPT Capabilities
        [On] Web Browsing
        [On] DALL·E Image Generation
        [On] Code Interpreter &amp;amp; Data Analysis
        Other Use Cases for Consideration
        Below is a non-exhaustive list of additional use cases that could be explored using the Canvas API. The basic outline for each is provided, but the GPT Instructions and specific API calls referenced are intentionally left to you as the user to decide what works best for your needs.
        Classroom Analytics and Reports
        Use Case: Empowers teachers with comprehensive analytics and performance reports on student engagement, grades, and participation. By leveraging this data, teachers can make informed decisions to tailor their course delivery, identify at-risk students, and enhance overall classroom effectiveness.
        API Resources:
        Analytics and Quiz Statistics: Retrieve detailed data on student participation, grades, and course-level statistics.
        Quiz Reports: Generate and view various reports to analyze overall class performance and track progress over time.
        Review and Improvement Guidance for Graded Assignments
        Use Case: Provide students with a tool to review their graded assignments, analyze their performance, and receive targeted guidance on how to improve in areas where they have knowledge gaps. The tool can highlight specific questions or sections where the student struggled and suggest additional resources or practice materials to help them improve.
        API Resources:
        Submissions and Quiz Submissions: Retrieve the student’s submissions and associated grades.
        Assignments: Retrieve detailed information about the assignment, including rubrics and grading criteria.
        Rubric Assessments: Access detailed feedback and rubric assessments
        Modules: Suggest additional learning modules that target the student’s weak areas using the List modules API.
        Quizzes: Recommend practice quizzes to help the student improve on specific knowledge gaps
        Congratulations!
        You’ve successfully created a Custom GPT with a working Custom Action using Canvas LMS. You should be able to have a conversation that looks similar to the screenshot below. Great job and keep going!
      </description>
      <link>https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_canvas</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_canvas</guid>
      <pubDate>Mon, 16 Sep 2024 16:00:00 GMT</pubDate>
      <category>ChatGPT</category>
      <category>GPT actions library</category>
    </item>
    <item>
      <title>Using reasoning for data validation</title>
      <description>In this guide, we’ll explore how to use the o1 model, specifically o1-preview, to perform data validation through reasoning. We’ll walk through a practical example involving a synthetic medical dataset and demonstrate how to assess the model’s accuracy in identifying issues within the data.
        Overview
        Data validation is a critical step in ensuring the quality and reliability of datasets, especially in sensitive fields like healthcare. Traditional validation methods often rely on predefined rules and patterns. However, advanced models like o1 can understand context and reason about data, offering a more flexible and intelligent approach to validation.
        In this tutorial, we will:
        Generate a synthetic dataset of medical data that contains inconsistencies.
        Define a function that takes in a row of data and validates its accuracy
        Run the validation process and compute accuracy metrics.
        Analyze and interpret the results.
        Synthetic Data Generation
        We will use a lot of the principles described in the Synthetic Data Generation cookbook to create the foundation of our dataset.
        We will prompt the model to generate sets of medical data for our use case. We have provide detailed instructions to the model on how to create the dataset, what format to follow, and how to fill it with inaccuracies. We also provide a few rows of sample data to get the model started.
        Each row in the dataset will have the following fields:
        Patient ID: A randomly generated patient id
        Date of Birth: Date of birth of the patient
        Gender: M/F
        Medical History: Past diagnoses
        Current Medications: Medication the patient is taking
        Allergies: Identified allergies
        Lab Results (Glucose mg/dL)
        Diagnoses: Current diagnosis
        Treatment Plan: Current treatment plan
        Is Valid: Whether or not the current row of data is valid (True/False)
        Issue: If the row of data is not valid, what the issue is
        Some examples of inaccuracies that may be present in the data are:
        Prescribing medications that the patient is allergic to
        Current medications do not match medical history
        Treatment plan does not match diagnosis
        Data Validation
        Now that we have our dataset prepared, we will prompt the reasoning model to review each row of data and determine whether or not it contains an issue. We will ask the model to output whether or not there is an issue in the data and then offer an explanation of the issue.
        Once we have the model determine its list of invalid data, we will pass those results on to a model grader to assess two metrics:
        Accuracy of the model&#39;s ability correctly identify issues with the data
        For the subset of data that issues have been correctly identified, what is the accuracy of the model in identifying the issue at hand
        Given that this task is much more narrow, we can use the faster gpt-4o model to calculate the accuracy.
        REMINDER: Given that these models are still in beta, rate limits will be significantly reduced. Please adjust the number of concurrent workers accordingly.
        Now that we have the model&#39;s results, we can compare it against the source of truth and determine the system&#39;s accuracy
        Issue Identification
        We will now determine the model&#39;s ability to accurately classify the issue in the data
        Below we&#39;ll display the subset of rows that we correctly identified contained an issue. For each row, we&#39;ll show the predicted vs. true issue and whether or not there is a match
        Conclusion
        We can see from the results here that we&#39;re able to generate a high precision/recall for issue identification as well as decent accuracy for pinpointing the exact issue in the data.
        This should help streamline data validation for eval sets across a variety of domains.
      </description>
      <link>https://cookbook.openai.com/examples/o1/using_reasoning_for_data_validation</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/o1/using_reasoning_for_data_validation</guid>
      <pubDate>Wed, 11 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Reasoning</category>
    </item>
    <item>
      <title>Using reasoning for routine generation</title>
      <description>When developing customer service solutions, one of the initial steps involves transforming knowledge base articles into a set of routines that an LLM can comprehend and follow. A routine, in this context, refers to a set of step-by-step instructions designed specifically for the LLM to execute efficiently. Each routine is carefully structured so that a step corresponds to a clear action. Actions can include responding to a user, triggering a function call, or retrieving additional relevant knowledge.
        Most internal knowledge base articles are complex and structured for human interpretation. They often include intricate diagrams, multi-step processes, and decision trees that pose challenges for LLM-based solutions to reason through in a meaningful way. By breaking down these documents into routines, each instruction can be simplified and formatted in a way that guides the LLM through a series of small, manageable tasks. This granular approach reduces ambiguity, allowing the LLM to process the information methodically and reducing the risk of hallucination or deviation from the expected path.
        Converting these knowledge base articles into routines can be time-consuming and challenging, especially for companies attempting to build an automated pipeline. Each routine must account for various user scenarios, where actions need to be clearly defined. For instance, when a function call is necessary, the routine must specify the exact information to retrieve or the action to execute—whether it’s triggering an API, retrieving external data, or pulling in additional context. While automating this process with traditional GPT-class models can significantly reduce the manual effort involved, it often introduces new challenges. Some challenges include designing robust instructions that are specific enough for the LLM to follow consistently, capturing unique edge cases that may arise during customer interactions, providing high-quality few-shot examples to guide the model’s behavior, and in some cases, fine-tuning the model to achieve more reliable or specialized outcomes.
        o1 has demonstrated the capability to efficiently deconstruct these articles and convert them into sets of routines zero-shot, meaning that the LLM can understand and follow the instructions without extensive examples or prior training on similar tasks. This minimizes the prompting effort required, as the routine structure itself provides the necessary guidance for the LLM to complete each step. By breaking down tasks into specific actions and integrating function calls where needed, o1’s approach ensures that even complex workflows can be handled seamlessly by the LLM, leading to more effective and scalable customer service solutions.
        Selecting Knowledge Base Articles
        In this example, we will use a set of publicly available Help Center articles from the OpenAI website and convert them into internal routines that an LLM can execute. Besides transforming the policies into routines, we will also have the model generate functions that allow the LLM to perform actions on behalf of the user. This is necessary to allow the LLM to execute the same actions that human agents have, and access additional information that may not be immediately available just from the policy documentation.
        We will begin by using the following Help Center articles for conversion into routines:
        How do I delete my payment method
        How can I get a Business Associate Agreement (BAA) with OpenAI?
        How can I set up prepaid billing?
        How do I submit a VAT exemption request
        We have our articles stored in an accessible csv. We will take the articles and pass them to o1-preview in parallel and generate the initial routines.
        Our instructions for converting the policy to a routine include:
        Converting the policy from an external facing document to an internal SOP routine
        Breaking down the policy in specific actions and sub-actions
        Outlining specific conditions for moving between steps
        Determing where external knowledge/actions may be required, and defining functions that we could use to get that information
        We&#39;ll store the results of our routines in a dataframe and print them out so we can get an initial look.
        Results
        Upon reviewing the generated routines, we can derive several insights:
        Sample Responses: The model effectively generates sample responses that the LLM can utilize when executing the policy (e.g., “Instruct the user: ‘Confirm and purchase your initial amount of credits.’”).
        Discrete Steps: The model excels at decomposing the problem into discrete actions that the LLM needs to execute. Each instruction is clearly defined and easy to interpret.
        Function Definitions: The routines’ outputs include clearly defined functions to retrieve external information or trigger actions (e.g., rev

github-actions[bot] avatar Oct 20 '24 04:10 github-actions[bot]

Successfully generated as following:

http://localhost:1200/cookbook - Success ✔️
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <title>OpenAI Cookbook</title>
    <link>https://cookbook.openai.com/</link>
    <atom:link href="http://localhost:1200/cookbook" rel="self" type="application/rss+xml"></atom:link>
    <description>OpenAI Cookbook - Powered by RSSHub</description>
    <generator>RSSHub</generator>
    <webMaster>[email protected] (RSSHub)</webMaster>
    <language>en</language>
    <lastBuildDate>Sun, 20 Oct 2024 13:45:15 GMT</lastBuildDate>
    <ttl>5</ttl>
    <item>
      <title>Leveraging model distillation to fine-tune a model</title>
      <description>OpenAI recently released Distillation which allows to leverage the outputs of a (large) model to fine-tune another (smaller) model. This can significantly reduce the price and the latency for specific tasks as you move to a smaller model. In this cookbook we&#39;ll look at a dataset, distill the output of gpt-4o to gpt-4o-mini and show how we can get significantly better results than on a generic, non-distilled, 4o-mini.
        We&#39;ll also leverage Structured Outputs for a classification problem using a list of enum. We&#39;ll see how fine-tuned model can benefit from structured output and how it will impact the performance. We&#39;ll show that Structured Ouputs work with all of those models, including the distilled one.
        We&#39;ll first analyze the dataset, get the output of both 4o and 4o mini, highlighting the difference in performance of both models, then proceed to the distillation and analyze the performance of this distilled model.
        Prerequisites
        Let&#39;s install and load dependencies.
        Make sure your OpenAI API key is defined in your environment as &quot;OPENAI_API_KEY&quot; and it&#39;ll be loaded by the client directly.
        Loading and understanding the dataset
        For this cookbook, we&#39;ll load the data from the following Kaggle challenge: https://www.kaggle.com/datasets/zynicide/wine-reviews.
        This dataset has a large number of rows and you&#39;re free to run this cookbook on the whole data, but as a biaised french wine-lover, I&#39;ll narrow down the dataset to only French wine to focus on less rows and grape varieties.
        We&#39;re looking at a classification problem where we&#39;d like to guess the grape variety based on all other criterias available, including description, subregion and province that we&#39;ll include in the prompt. It gives a lot of information to the model, you&#39;re free to also remove some information that can help significantly the model such as the region in which it was produced to see if it does a good job at finding the grape.
        Let&#39;s filter the grape varieties that have less than 5 occurences in reviews.
        Let&#39;s proceed with a subset of 500 random rows from this dataset.
        Let&#39;s retrieve all grape varieties to include them in the prompt and in our structured outputs enum list.
        Generating the prompt
        Let&#39;s build out a function to generate our prompt and try it for the first wine of our list.
        To get a understanding of the cost before running the queries, you can leverage tiktoken to understand the number of tokens we&#39;ll send and the cost associated to run this. This will only give you an estimate for to run the completions, not the fine-tuning process (used later in this cookbook when running the distillation), which depends on other factors such as the number of epochs, training set etc.
        Preparing functions to Store Completions
        As we&#39;re looking at a limited list of response (enumerate list of grape varieties), let&#39;s leverage structured outputs so we make sure the model will answer from this list. This also allows us to compare the model&#39;s answer directly with the grape variety and have a deterministic answer (compared to a model that could answer &quot;I think the grape is Pinot Noir&quot; instead of just &quot;Pinot noir&quot;), on top of improving the performance to avoid grape varieties not in our dataset.
        If you want to know more on Structured Outputs you can read this cookbook and this documentation guide.
        To distill a model, you need to store all completions from a model, allowing you to give it as a reference to the smaller model to fine-tune it. We&#39;re therefore adding a store=True parameter to our client.chat.completions.create method so we can store those completions from gpt-4o.
        We&#39;re going to store all completions (even 4o-mini and our future fine-tuned model) so we are able to run Evals from OpenAI platform directly.
        When storing those completions, it&#39;s useful to store them with a metadata tag, that will allow filtering from the OpenAI platform to run distillation &amp;amp; evals on the specific set of completions you&#39;d like to run those.
        Parallel processing
        As we&#39;ll run this on a large number of rows, let&#39;s make sure we run those completions in parallel and use concurrent futures for this. We&#39;ll iterate on our dataframe and output progress every 20 rows. We&#39;ll store the completion from the model we run the completion for in the same dataframe using the column name {model}-variety.
        Let&#39;s try out our call model function before processing the whole dataframe and check the output.
        Great! We confirmed we can get a grape variety as an output, let&#39;s now process the dataset with both gpt-4o and gpt-4o-mini and compare the results.
        Comparing gpt-4o and gpt-4o-mini
        Now that we&#39;ve got all chat completions for those two models ; let&#39;s compare them against the expected grape variety and assess their accuracy at finding it. We&#39;ll do this directly in python here as we&#39;ve got a simple string check to run, but if your task involves more complex evals you can leverage OpenAI Evals or our open-source eval framework.
        We can see that gpt-4o is better a finding grape variety than 4o-mini (12.80% higher or almost 20% relatively to 4o-mini!). Now I&#39;m wondering if we&#39;re making gpt-4o drink wine during training!
        Distilling gpt-4o outputs to gpt-4o-mini
        Let&#39;s assume we&#39;d like to run this prediction often, we want completions to be faster and cheaper, but keep that level of accuracy. That&#39;d be great to be able to distill 4o accuracy to 4o-mini, wouldn&#39;t it? Let&#39;s do it!
        We&#39;ll now go to OpenAI Stored completions page: https://platform.openai.com/chat-completions.
        Let&#39;s select the model gpt-4o (make sure to do this, you don&#39;t want to distill the outputs of 4o-mini that we ran). Let&#39;s also select the metadata distillation: wine-distillation to get only stored completions ran from this cookbook.
        Once you&#39;ve selected completions, you can click on &quot;Distill&quot; on the top right corner to fine-tune a model based on those completions. Once we&#39;ve done that, a file to run the fine-tuning process will automatically be created. Let&#39;s then select gpt-4o-mini as the base model, keep the default parameters (but you&#39;re free to change them or iterate with it to improve performance).
        Once the fine-tuning job is starting, you can retrieve the fine tuning job ID from the fine-tuning page, we&#39;ll use it to monitor status of the fine-tuned job as well as retrieving the fine-tuned model id once done.
        Running completions for the distilled model
        Now that we&#39;ve got our model fine-tuned, we can use this model to run completions and compare accuracy with both gpt4o and gpt4o-mini.
        Let&#39;s grab a different subset of french wines (as we restricted the outputs to french grape varieties, without outliers, we&#39;ll need to focus our validation dataset to this too). Let&#39;s run this on 300 entries for each models.
        Let&#39;s compare accuracy of models
        That&#39;s almost a 22% relative improvement over the non-distilled gpt-4o-mini! 🎉
        Our fine-tuned model performs way better than gpt-4o-mini, while having the same base model. We&#39;ll be able to use this model to run inferences at a lower cost and lower latency for future grape variety prediction.
      </description>
      <link>https://cookbook.openai.com/examples/leveraging_model_distillation_to_fine-tune_a_model</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/leveraging_model_distillation_to_fine-tune_a_model</guid>
      <pubDate>Tue, 15 Oct 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Fine-tuning</category>
    </item>
    <item>
      <title>Orchestrating Agents: Routines and Handoffs</title>
      <description>When working with language models, quite often all you need for solid performance is a good prompt and the right tools. However, when dealing with many unique flows, things may get hairy. This cookbook will walk through one way to tackle this.
        We&#39;ll introduce the notion of routines and handoffs, then walk through the implementation and show how they can be used to orchestrate multiple agents in a simple, powerful, and controllable way.
        Finally, we provide a sample repo, Swarm, that implements these ideas along with examples.
        Let&#39;s start by setting up our imports.
        Routines
        The notion of a &quot;routine&quot; is not strictly defined, and instead meant to capture the idea of a set of steps. Conretely, let&#39;s define a routine to be a list of instructions in natural langauge (which we&#39;ll represent with a system prompt), along with the tools necessary to complete them.
        Let&#39;s take a look at an example. Below, we&#39;ve defined a routine for a customer service agent instructing it to triage the user issue, then either suggest a fix or provide a refund. We&#39;ve also defined the necessary functions execute_refund and look_up_item. We can call this a customer service routine, agent, assistant, etc –&amp;nbsp;however the idea itself is the same: a set of steps and the tools to execute them.
        The main power of routines is their simplicity and robustness. Notice that these instructions contain conditionals much like a state machine or branching in code. LLMs can actually handle these cases quite robustly for small and medium sized routine, with the added benefit of having &quot;soft&quot; adherance –&amp;nbsp;the LLM can naturally steer the conversation without getting stuck in dead-ends.
        Executing Routines
        To execute a routine, let&#39;s implement a simple loop that:
        Gets user input.
        Appends user message to messages.
        Calls the model.
        Appends model response to messages.
        As you can see, this currently ignores function calls, so let&#39;s add that.
        Models require functions to be formatted as a function schema. For convenience, we can define a helper function that turns python functions into the corresponding function schema.
        For example:
        Now, we can use this function to pass the tools to the model when we call it.
        Finally, when the model calls a tool we need to execute the corresponding function and provide the result back to the model.
        We can do this by mapping the name of the tool to the python function in a tool_map, then looking it up in execute_tool_call and calling it. Finally we add the result to the conversation.
        In practice, we&#39;ll also want to let the model use the result to produce another response. That response might also contain a tool call, so we can just run this in a loop until there are no more tool calls.
        If we put everything together, it will look something like this:
        Now that we have a routine, let&#39;s say we want to add more steps and more tools. We can up to a point, but eventually if we try growing the routine with too many different tasks it may start to struggle. This is where we can leverage the notion of multiple routines – given a user request, we can load the right routine with the appropriate steps and tools to address it.
        Dynamically swapping system instructions and tools may seem daunting. However, if we view &quot;routines&quot; as &quot;agents&quot;, then this notion of handoffs allow us to represent these swaps simply –&amp;nbsp;as one agent handing off a conversation to another.
        Handoffs
        Let&#39;s define a handoff as an agent (or routine) handing off an active conversation to another agent, much like when you get transfered to someone else on a phone call. Except in this case, the agents have complete knowledge of your prior conversation!
        To see handoffs in action, let&#39;s start by defining a basic class for an Agent.
        Now to make our code support it, we can change run_full_turn to take an Agent instead of separate system_message and tools:
        We can now run multiple agents easily:
        Great! But we did the handoff manually here –&amp;nbsp;we want the agents themselves to decide when to perform a handoff. A simple, but surprisingly effective way to do this is by giving them a transfer_to_XXX function, where XXX is some agent. The model is smart enough to know to call this function when it makes sense to make a handoff!
        Handoff Functions
        Now that agent can express the intent to make a handoff, we must make it actually happen. There&#39;s many ways to do this, but there&#39;s one particularly clean way.
        For the agent functions we&#39;ve defined so far, like execute_refund or place_order they return a string, which will be provided to the model. What if instead, we return an Agent object to indate which agent we want to transfer to? Like so:
        We can then update our code to check the return type of a function response, and if it&#39;s an Agent, update the agent in use! Additionally, now run_full_turn will need to return the latest agent in use in case there are handoffs. (We can do this in a Response class to keep things neat.)
        Now for the updated run_full_turn:
        Let&#39;s look at an example with more Agents.
        Finally, we can run this in a loop (this won&#39;t run in python notebooks, so you can try this in a separate python file):
        Swarm
        As a proof of concept, we&#39;ve packaged these ideas into a sample library called Swarm. It is meant as an example only, and should not be directly used in production. However, feel free to take the ideas and code to build your own!
      </description>
      <link>https://cookbook.openai.com/examples/orchestrating_agents</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/orchestrating_agents</guid>
      <pubDate>Wed, 09 Oct 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Functions</category>
    </item>
    <item>
      <title>Prompt Caching 101</title>
      <description>OpenAI offers discounted prompt caching for prompts exceeding 1024 tokens, resulting in up to an 80% reduction in latency for longer prompts over 10,000 tokens. By caching repetitive information across LLM API requests, you can greatly reduce both latency and costs. Prompt caching is scoped at the organization level, meaning only members of the same organization can access shared caches. Additionally, caching is eligible for zero data retention, as no data is stored during the process.
        Prompt caching automatically activates for prompts longer than 1024 tokens-- you don&#39;t have to change anything in your completions request. When an API request is made, the system first checks if the beginning portion (prefix) of the prompt has already been cached. If a match is found (cache hit), the cached prompt is used, leading to reduced latency and costs. If there&#39;s no match, the system processes the full prompt from scratch and caches the prefix for future use.
        With these benefits in mind, some of the key use cases where prompt caching can be especially advantageous are:
        Agents using tools and structured outputs: Cache the extended list of tools and schemas.
        Coding and writing assistants: Insert large sections or summaries of codebases and workspaces directly in prompts.
        Chatbots: Cache static portions of multi-turn conversations to maintain context efficiently over extended dialogues.
        In this cookbook, we&#39;ll go through a couple examples of caching tools and images. Recall that in general, you&#39;ll want to put static content like instructions and examples at the beginning of your prompt, and variable content, such as user-specific information, at the end. This also applies to images and tools, which must be identical even in their ordering between requests. All requests, including those with fewer than 1024 tokens, will display a cached_tokens field of the usage.prompt_tokens_details chat completions object indicating how many of the prompt tokens were a cache hit. For requests under 1024 tokens, cached_tokens will be zero. Caching discounts are based on the actual number of tokens processed, including those used for images, which also count toward your rate limits.
        Example 1: Caching tools and multi-turn conversations
        In this example, we define tools and interactions for a customer support assistant, capable of handling tasks such as checking delivery dates, canceling orders, and updating payment methods. The assistant processes two separate messages, first responding to an initial query, followed by a delayed response to a follow-up query.
        When caching tools, it is important that the tool definitions and their order remain identical for them to be included in the prompt prefix. To cache message histories in a multi-turn conversation, append new elements to the end of the messages array. In the response object and the output below, for the second completion run2, you can see that the cached_tokens value is greater than zero, indicating successful caching.
        Example 2: Images
        In our second example we include multiple image URLs of grocery items in the messages array, along with a user query, run three times with delays. Images—whether linked or encoded in base64 within user messages—qualify for caching. Make sure the detail parameter remains consistent, as it affects how images are tokenized. Note that GPT-4o-mini adds extra tokens to cover image processing costs, even though it uses a low-cost token model for text. Caching discounts are based on the actual number of tokens processed, including those used for images, which also count toward your rate limits.
        The output for this example shows that a cache was hit for the second run, however it was not hit for the third run because of a different first url (eggs_url instead of veggie_url), even though the user query is the same.
        Overall tips
        To get the most out of prompt caching, consider following these best practices:
        Place static or frequently reused content at the beginning of prompts: This helps ensure better cache efficiency by keeping dynamic data towards the end of the prompt.
        Maintain consistent usage patterns: Prompts that aren&#39;t used regularly are automatically removed from the cache. To prevent cache evictions, maintain consistent usage of prompts.
        Monitor key metrics: Regularly track cache hit rates, latency, and the proportion of cached tokens. Use these insights to fine-tune your caching strategy and maximize performance.
        By implementing these practices, you can take full advantage of prompt caching, ensuring that your applications are both responsive and cost-efficient. A well-managed caching strategy will significantly reduce processing times, lower costs, and help maintain smooth user experiences.
      </description>
      <link>https://cookbook.openai.com/examples/prompt_caching101</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/prompt_caching101</guid>
      <pubDate>Mon, 30 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
    </item>
    <item>
      <title>Using chained calls for o1 structured outputs</title>
      <description>The initially released versions (September 2024) of o1 reasoning models have advanced capabilities but do not have structured outputs support.
        This means that requests with o1 don&#39;t have reliable type-safety and rely on the prompt itself to return a useful JSON.
        In this guide, we&#39;ll explore two methods to prompt o1 models, specifically o1-preview, to return a valid JSON format when using the OpenAI API.
        Prompting
        The simplest way to return a JSON response using o1-preview is to explicitly prompt it.
        Let&#39;s run through an example of:
        Fetching a wikipedia page of companies
        Determining which could benefit the most from AI capabilities
        Returning them in a JSON format, which could then be ingested by other systems
        Note that the response is already quite good - it returns the JSON with the appropriate responses. However, it runs into the same pitfalls as existing use-cases of prompt-only JSON inference:
        You must manually process this JSON into your type-safe structure
        Model refusals are not explicitly returned from the API as a separate structure
        Structured Outputs
        Let&#39;s now do this with structured outputs. To enable this functionality, we’ll link the o1-preview response with a follow-up request to gpt-4o-mini, which can effectively process the data returned from the initial o1-preview response.
        Conclusion
        Structured outputs allow your code to have reliable type-safety and simpler prompting. In addition, it allows you to re-use your object schemas for easier integration into your existing workflows.
        The o1 class of models currently doesn&#39;t have structured outputs support, but we can re-use existing structured outputs functionality from gpt-4o-mini by chaining two requests together. This flow currently requires two calls, but the second gpt-4o-mini call cost should be minimal compared to the o1-preview/o1-mini calls.
      </description>
      <link>https://cookbook.openai.com/examples/o1/using_chained_calls_for_o1_structured_outputs</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/o1/using_chained_calls_for_o1_structured_outputs</guid>
      <pubDate>Wed, 25 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Reasoning</category>
    </item>
    <item>
      <title>Building a Bring Your Own Browser (BYOB) Tool for Web Browsing and Summarization</title>
      <description>Disclaimer: This cookbook is for educational purposes only. Ensure that you comply with all applicable laws and service terms when using web search and scraping technologies. This cookbook will restrict the search to openai.com domain to retrieve the public information to illustrate the concepts.
        Large Language Models (LLMs) such as GPT-4o have a knowledge cutoff date, which means they lack information about events that occurred after that point. In scenarios where the most recent data is essential, it&#39;s necessary to provide LLMs with access to current web information to ensure accurate and relevant responses.
        In this guide, we will build a Bring Your Own Browser (BYOB) tool using Python to overcome this limitation. Our goal is to create a system that provides up-to-date answers in your application, including the most recent developments such as the latest product launches by OpenAI. By integrating web search capabilities with an LLM, we&#39;ll enable the model to generate responses based on the latest information available online.
        While you can use any publicly available search APIs, we&#39;ll utilize Google&#39;s Custom Search API to perform web searches. The retrieved information from the search results will be processed and passed to the LLM to generate the final response through Retrieval-Augmented Generation (RAG).
        Bring Your Own Browser (BYOB) tools allow users to perform web browsing tasks programmatically. In this notebook, we&#39;ll create a BYOB tool that:
        #1. Set Up a Search Engine: Use a public search API, such as Google&#39;s Custom Search API, to perform web searches and obtain a list of relevant search results.
        #2. Build a Search Dictionary: Collect the title, URL, and a summary of each web page from the search results to create a structured dictionary of information.
        #3. Generate a RAG Response: Implement Retrieval-Augmented Generation (RAG) by passing the gathered information to the LLM, which then generates a final response to the user&#39;s query.
        Use Case
        In this cookbook, we&#39;ll take the example of a user who wants to list recent product launches by OpenAI in chronological order. Because the current GPT-4o model has a knowledge cutoff date, it is not expected that the model will know about recent product launches such as the o1-preview model launched in September 2024.
        Given the knowledge cutoff, as expected the model does not know about the recent product launches by OpenAI.
        Setting up a BYOB tool
        To provide the model with recent events information, we&#39;ll follow these steps:
        Step 1: Set Up a Search Engine to Provide Web Search Results
        Step 2: Build a Search Dictionary with Titles, URLs, and Summaries of Web Pages
        Step 3: Pass the information to the model to generate a RAG Response to the User Query
        Before we begin, ensure you have the following: Python 3.12 or later installed on your machine. You will also need a Google Custom Search API key and Custom Search Engine ID (CSE ID). Necessary Python packages installed: requests, beautifulsoup4, openai. And ensure the OPENAI_API_KEY is set up as an environment variable.
        Step 1: Set Up a Search Engine to Provide Web Search Results
        You can use any publicly available web search APIs to perform this task. We will configure a custom search engine using Google&#39;s Custom Search API. This engine will fetch a list of relevant web pages based on the user&#39;s query, focusing on obtaining the most recent and pertinent results.
        a. Configure Search API key and Function: Acquire a Google API key and a Custom Search Engine ID (CSE ID) from the Google Developers Console. You can navigate to this Programmable Search Engine Link to set up an API key as well as Custom Search Engine ID (CSE ID).
        The search function below sets up the search based on search term, the API and CSE ID keys, as well as number of search results to return. We&#39;ll introduce a parameter site_filter to restrict the output to only openai.com
        b. Identify the search terms for search engine: Before we can retrieve specific results from a 3rd Party API, we may need to use Query Expansion to identify specific terms our browser search API should retrieve. Query expansion is a process where we broaden the original user query by adding related terms, synonyms, or variations. This technique is essential because search engines, like Google&#39;s Custom Search API, are often better at matching a range of related terms rather than just the natural language prompt used by a user.
        For example, searching with only the raw query &quot;List the latest OpenAI product launches in chronological order from latest to oldest in the past 2 years&quot; may return fewer and less relevant results than a more specific and direct search on a succinct phrase such as &quot;Latest OpenAI product launches&quot;. In the code below, we will use the user&#39;s original search_query to produce a more specific search term to use with the Google API to retrieve the results.
        c. Invoke the search function: Now that we have the search term, we will invoke the search function to retrieve the results from Google search API. The results only have the link of the web page and a snippet at this point. In the next step, we will retrieve more information from the webpage and summarize it in a dictionary to pass to the model.
        Step 2: Build a Search Dictionary with Titles, URLs, and Summaries of Web Pages
        After obtaining the search results, we&#39;ll extract and organize the relevant information, so it can be passed to the LLM for final output.
        a. Scrape Web Page Content: For each URL in the search results, retrieve the web page to extract textual content while filtering out non-relevant data like scripts and advertisements as demonstrated in function retrieve_content.
        b. Summarize Content: Use an LLM to generate concise summaries of the scraped content, focusing on information pertinent to the user&#39;s query. Model can be provided the original search text, so it can focus on summarizing the content for the search intent as outlined in function summarize_content.
        c. Create a Structured Dictionary: Organize the data into a dictionary or a DataFrame containing the title, link, and summary for each web page. This structure can be passed on to the LLM to generate the summary with the appropriate citations.
        We retrieved the most recent results. (Note these will vary depending on when you execute this script.)
        Step 3: Pass the information to the model to generate a RAG Response to the User Query
        With the search data organized in a JSON data structure, we will pass this information to the LLM with the original user query to generate the final response. Now, the LLM response includes information beyond its original knowledge cutoff, providing current insights.
        Conclusion
        Large Language Models (LLMs) have a knowledge cutoff and may not be aware of recent events. To provide them with the latest information, you can build a Bring Your Own Browser (BYOB) tool using Python. This tool retrieves current web data and feeds it to the LLM, enabling up-to-date responses.
        The process involves three main steps:
        #1 Set Up a Search Engine: Use a public search API, like Google&#39;s Custom Search API, to perform web searches and obtain a list of relevant search results.
        #2 Build a Search Dictionary: Collect the title, URL, and a summary of each web page from the search results to create a structured dictionary of information.
        #3. Generate a RAG Response: Implement Retrieval-Augmented Generation (RAG) by passing the gathered information to the LLM, which then generates a final response to the user&#39;s query.
        By following these steps, you enhance the LLMs ability to provide up-to-date answers in your application that include the most recent developments, such as the latest product launches by OpenAI.
      </description>
      <link>https://cookbook.openai.com/examples/third_party/web_search_with_google_api_bring_your_own_browser_tool</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/third_party/web_search_with_google_api_bring_your_own_browser_tool</guid>
      <pubDate>Wed, 25 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
    </item>
    <item>
      <title>GPT Actions library - Canvas Learning Management System</title>
      <description>Table of Contents
        General App Information - Overview of Canvas LMS, its functionality, and the role of ChatGPT&#39;s Custom Actions to enhance educational experiences through AI integration.
        Authentication from ChatGPT to Canvas - Explanation of authentication methods (OAuth and User Generated Access Tokens) for connecting ChatGPT to Canvas, with detailed instructions for setting up each option.
        Sample Use Case: Student Course Assistant - Detailed example of using ChatGPT to assist students with course navigation, exam preparation, and personalized feedback, including specific API calls and workflows.
        Other Use Cases for Consideration - Additional potential integrations using the Canvas API, such as classroom analytics and report generation.
        Congratulations
        General App Information
        Canvas is a widely-used Learning Management System (LMS) designed to support online learning and teaching. It offers a robust set of tools for course management, content delivery, assessments, and student collaboration. Through the Canvas REST API, Canvas allows for extensive customization and integration with third-party applications, including AI-powered tools like ChatGPT.
        ChatGPT’s Custom Actions with Canvas enable educators to leverage AI to enhance course content, automate tasks, and provide personalized learning journeys for students. Examples include virtual teaching assistants based on active courses, as the capabilities are well-suited for pulling information in from Canvas to create an educational dialogue. ChatGPT with Custom Actions is not meant for automating the entire Canvas experience nor act as a replacement to many of its capabilities better suited for completion in the Canvas app.
        Authentication from ChatGPT to Canvas
        For a general overview on Authentication in Custom Actions, see the Action authentication documentation.
        There are two options for authentication in Canvas: 1) OAuth and 2) User Generated Access Tokens.
        For large-scale deployments, it is required to use OAuth for Action Authentication.
        If the user is considering a single-user deployment or does not have access to Admin Settings, they may consider User Generated Access Tokens. Be aware that any request made by the action will be made using the token the user generated, so Canvas will register all requests as the user&#39;s activity and use the user&#39;s permissions to complete them.
        Implementing OAuth for Canvas
        While this Canvas Cookbook does not use OAuth, any deployment with more than one user must use it. See OAuth for Canvas Documentation for a detailed walkthrough.
        Here are some things to keep in mind while implementing OAuth in a Canvas Custom Action:
        Access to Canvas’ Admin settings is required for OAuth in order to retrieve a Client ID and Client Secret.
        The Authorization URL will look like (make sure to update the Canvas Install URL): https:///login/oauth2/auth
        The Token URL will look like (make sure to update the Canvas Install URL): ttps:///login/oauth2/token
        Scopes may not need to be defined in the Custom Action. If the developer key does not require scopes and no scope parameter is specified, the access token will have access to all scopes. If the developer key does require scopes and no scope parameter is specified, Canvas will respond with &quot;invalid_scope.&quot; More information on developer keys here and endpoints here.
        Token Exchange Method is Default (POST Request)
        Canvas uses the term redirect_uri where ChatGPT uses the term Callback URL for URL to complete the redirect process after successful authentication.
        Implementing authentication with User Generated Access Tokens
        In some cases, it may be appropriate to use User Generated Access Tokens for Custom Action authentication with Canvas. Here are the steps to follow to do so:
        Proceed to Canvas Account Settings shown here:
        Scroll down to the List of Tokens shown here:
        Generate a New Token, and store this token. It will not be accessible later.
        Sample Use Case: Student Course Assistant
        Overview
        Assists students in navigating and understanding their courses by providing detailed information, generating personalized practice exams, and offering constructive feedback to enhance learning.
        Considerations
        Some information like the Syllabus is returned as an HTML page when requested by the API. This renders it impossible to show in ChatGPT. Instead, reference course description, modules, and the assignments to guide the user.
        Requests can be modified to retrieve specific pieces of information using the include[] query parameter. If you need to request specific information about a course, provide an example in the GPT instructions.
        GPT Instructions
        There can be multiple ways to write these instructions. See here for guidance on Prompt Engineering strategies and best practices.
        # **Context:** You support college students by providing detailed information about their courses hosted on the Canvas Learning Management System. You help them understand course content, generate practice exams based on provided materials, and offer insightful feedback to aid their learning journey. Assume the students are familiar with basic academic terminologies.
        # **Instructions:**
        ## Scenarios
        ### - When the user asks for information about a specific course, follow this 5 step process:
        1. Ask the user to specify the course they want assistance with and the particular area of focus (e.g., overall course overview, specific module).
        2. If you do not know the Course ID for the course requested, use the listYourCourses to find the right course and corresponding ID in Canvas. If none of the courses listed returned courses that seem to match the course request, use the searchCourses to see if there are any similarly named course.
        3. Retrieve the course information from Canvas using the getSingleCourse API call and the listModules API call.
        4. Ask the user which module(s) they would like to focus on and use the listModuleItems to retrieve the requested module items. For any assignments, share links to them.
        5. Ask if the user needs more information or if they need to prepare for an exam.
        ### When a user asks to take a practice test or practice exam for a specific course, follow this 6 step process:
        1. Ask how many questions
        2. Ask which chapters or topics they want to be tested on, provide a couple examples from the course modules in Canvas.
        3. Ask 1 question at a time, be sure the questions are multiple choice (do not generate the next question until the question is answered)
        4. When the user answers, tell them if its right or wrong and give a description for the correct answer
        5. Ask the user if they want to export the test results and write the code to create the PDF
        6. Offer additional resources and study tips tailored to the user&#39;s needs and progress, and inquire if they require further assistance with other courses or topics.
        ### When a user asks to create a study guide
        - Format the generated study guide in a table
        OpenAPI Schema
        API Calls Featured
        [GET] listYourCourses
        [GET] getSingleCourse
        [GET] listModules
        [GET] listModuleItems
        [GET] searchCourses
        Below was generated with a combination of Canvas API Reference and the ActionsGPT.
        openapi: 3.1.0
        info:
        title: Canvas API
        description: API for interacting with Canvas LMS, including courses, modules, module items, and search functionalities.
        version: 1.0.0
        servers:
        - url: https://canvas.instructure.com/api/v1
        description: Canvas LMS API server
        variables:
        domain:
        default: canvas.instructure.com
        description: The domain of your Canvas instance
        paths:
        /courses:
        get:
        operationId: listYourCourses
        summary: List your courses
        description: Retrieves a paginated list of active courses for the current user.
        parameters:
        - name: enrollment_type
        in: query
        description: Filter by enrollment type (e.g., &quot;teacher&quot;, &quot;student&quot;).
        schema:
        type: string
        - name: enrollment_role
        in: query
        description: Filter by role type. Requires admin permissions.
        schema:
        type: string
        - name: enrollment_state
        in: query
        description: Filter by enrollment state (e.g., &quot;active&quot;, &quot;invited&quot;).
        schema:
        type: string
        - name: exclude_blueprint_courses
        in: query
        description: Exclude Blueprint courses if true.
        schema:
        type: boolean
        - name: include
        in: query
        description: Array of additional information to include (e.g., &quot;term&quot;, &quot;teachers&quot;).
        schema:
        type: array
        items:
        type: string
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of courses.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the course.
        name:
        type: string
        description: The name of the course.
        account_id:
        type: integer
        description: The ID of the account associated with the course.
        enrollment_term_id:
        type: integer
        description: The ID of the term associated with the course.
        start_at:
        type: string
        format: date-time
        description: The start date of the course.
        end_at:
        type: string
        format: date-time
        description: The end date of the course.
        course_code:
        type: string
        description: The course code.
        state:
        type: string
        description: The current state of the course (e.g., &quot;unpublished&quot;, &quot;available&quot;).
        &#39;400&#39;:
        description: Bad request, possibly due to invalid query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        /courses/{course_id}:
        get:
        operationId: getSingleCourse
        summary: Get a single course
        description: Retrieves the details of a specific course by its ID.
        parameters:
        - name: course_id
        in: path
        required: true
        description: The ID of the course.
        schema:
        type: integer
        - name: include
        in: query
        description: Array of additional information to include (e.g., &quot;term&quot;, &quot;teachers&quot;).
        schema:
        type: array
        items:
        type: string
        responses:
        &#39;200&#39;:
        description: A single course object.
        content:
        application/json:
        schema:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the course.
        name:
        type: string
        description: The name of the course.
        account_id:
        type: integer
        description: The ID of the account associated with the course.
        enrollment_term_id:
        type: integer
        description: The ID of the term associated with the course.
        start_at:
        type: string
        format: date-time
        description: The start date of the course.
        end_at:
        type: string
        format: date-time
        description: The end date of the course.
        course_code:
        type: string
        description: The course code.
        state:
        type: string
        description: The current state of the course (e.g., &quot;unpublished&quot;, &quot;available&quot;).
        is_public:
        type: boolean
        description: Whether the course is public.
        syllabus_body:
        type: string
        description: The syllabus content of the course.
        term:
        type: object
        description: The term associated with the course.
        properties:
        id:
        type: integer
        name:
        type: string
        start_at:
        type: string
        format: date-time
        end_at:
        type: string
        format: date-time
        &#39;400&#39;:
        description: Bad request, possibly due to an invalid course ID or query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: Course not found, possibly due to an invalid course ID.
        /courses/{course_id}/modules:
        get:
        operationId: listModules
        summary: List modules in a course
        description: Retrieves the list of modules for a given course in Canvas.
        parameters:
        - name: course_id
        in: path
        required: true
        description: The ID of the course.
        schema:
        type: integer
        - name: include
        in: query
        description: Include additional information such as items in the response.
        schema:
        type: array
        items:
        type: string
        example: [&quot;items&quot;]
        - name: search_term
        in: query
        description: The partial title of the module to match and return.
        schema:
        type: string
        - name: student_id
        in: query
        description: Return module completion information for the student with this ID.
        schema:
        type: integer
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of modules in the course.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the module.
        name:
        type: string
        description: The name of the module.
        items_count:
        type: integer
        description: The number of items in the module.
        state:
        type: string
        description: The state of the module (e.g., &quot;active&quot;, &quot;locked&quot;).
        &#39;400&#39;:
        description: Bad request, possibly due to an invalid course ID or query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: Course not found, possibly due to an invalid course ID.
        /courses/{course_id}/modules/{module_id}/items:
        get:
        operationId: listModuleItems
        summary: List items in a module
        description: Retrieves the list of items within a specific module in a Canvas course.
        parameters:
        - name: course_id
        in: path
        required: true
        description: The ID of the course.
        schema:
        type: integer
        - name: module_id
        in: path
        required: true
        description: The ID of the module.
        schema:
        type: integer
        - name: include
        in: query
        description: Include additional information in the response, such as content details.
        schema:
        type: array
        items:
        type: string
        example: [&quot;content_details&quot;]
        - name: student_id
        in: query
        description: Return completion information for the student with this ID.
        schema:
        type: integer
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of items in the module.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the module item.
        title:
        type: string
        description: The title of the module item.
        type:
        type: string
        description: The type of the module item (e.g., &quot;Assignment&quot;, &quot;File&quot;).
        position:
        type: integer
        description: The position of the item within the module.
        indent:
        type: integer
        description: The level of indentation of the item in the module.
        completion_requirement:
        type: object
        description: The completion requirement for the item.
        properties:
        type:
        type: string
        min_score:
        type: integer
        content_id:
        type: integer
        description: The ID of the associated content item (e.g., assignment, file).
        state:
        type: string
        description: The state of the item (e.g., &quot;active&quot;, &quot;locked&quot;).
        &#39;400&#39;:
        description: Bad request, possibly due to an invalid module ID or query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: Module or course not found, possibly due to an invalid module or course ID.
        /search/all_courses:
        get:
        operationId: searchCourses
        summary: Search for courses
        description: Searches for public courses in Canvas.
        parameters:
        - name: search
        in: query
        description: The search term to filter courses.
        schema:
        type: string
        - name: public_only
        in: query
        description: If true, only returns public courses.
        schema:
        type: boolean
        - name: open_enrollment_only
        in: query
        description: If true, only returns courses with open enrollment.
        schema:
        type: boolean
        - name: enrollment_type
        in: query
        description: Filter by enrollment type (e.g., &quot;teacher&quot;, &quot;student&quot;).
        schema:
        type: string
        - name: sort
        in: query
        description: Sort the results by &quot;asc&quot; or &quot;desc&quot; order.
        schema:
        type: string
        enum:
        - asc
        - desc
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of courses matching the search criteria.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the course.
        name:
        type: string
        description: The name of the course.
        account_id:
        type: integer
        description: The ID of the account associated with the course.
        enrollment_term_id:
        type: integer
        description: The ID of the term associated with the course.
        start_at:
        type: string
        format: date-time
        description: The start date of the course.
        end_at:
        type: string
        format: date-time
        description: The end date of the course.
        course_code:
        type: string
        description: The course code.
        state:
        type: string
        description: The current state of the course (e.g., &quot;unpublished&quot;, &quot;available&quot;).
        is_public:
        type: boolean
        description: Whether the course is public.
        term:
        type: object
        description: The term associated with the course.
        properties:
        id:
        type: integer
        name:
        type: string
        start_at:
        type: string
        format: date-time
        end_at:
        type: string
        format: date-time
        &#39;400&#39;:
        description: Bad request, possibly due to invalid query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: No courses found matching the criteria.
        Sample Conversation Starters
        Help me take a practice exam.
        Give an overview of one of my courses.
        List all of my courses.
        GPT Capabilities
        [On] Web Browsing
        [On] DALL·E Image Generation
        [On] Code Interpreter &amp;amp; Data Analysis
        Other Use Cases for Consideration
        Below is a non-exhaustive list of additional use cases that could be explored using the Canvas API. The basic outline for each is provided, but the GPT Instructions and specific API calls referenced are intentionally left to you as the user to decide what works best for your needs.
        Classroom Analytics and Reports
        Use Case: Empowers teachers with comprehensive analytics and performance reports on student engagement, grades, and participation. By leveraging this data, teachers can make informed decisions to tailor their course delivery, identify at-risk students, and enhance overall classroom effectiveness.
        API Resources:
        Analytics and Quiz Statistics: Retrieve detailed data on student participation, grades, and course-level statistics.
        Quiz Reports: Generate and view various reports to analyze overall class performance and track progress over time.
        Review and Improvement Guidance for Graded Assignments
        Use Case: Provide students with a tool to review their graded assignments, analyze their performance, and receive targeted guidance on how to improve in areas where they have knowledge gaps. The tool can highlight specific questions or sections where the student struggled and suggest additional resources or practice materials to help them improve.
        API Resources:
        Submissions and Quiz Submissions: Retrieve the student’s submissions and associated grades.
        Assignments: Retrieve detailed information about the assignment, including rubrics and grading criteria.
        Rubric Assessments: Access detailed feedback and rubric assessments
        Modules: Suggest additional learning modules that target the student’s weak areas using the List modules API.
        Quizzes: Recommend practice quizzes to help the student improve on specific knowledge gaps
        Congratulations!
        You’ve successfully created a Custom GPT with a working Custom Action using Canvas LMS. You should be able to have a conversation that looks similar to the screenshot below. Great job and keep going!
      </description>
      <link>https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_canvas</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_canvas</guid>
      <pubDate>Mon, 16 Sep 2024 16:00:00 GMT</pubDate>
      <category>ChatGPT</category>
      <category>GPT actions library</category>
    </item>
    <item>
      <title>Using reasoning for data validation</title>
      <description>In this guide, we’ll explore how to use the o1 model, specifically o1-preview, to perform data validation through reasoning. We’ll walk through a practical example involving a synthetic medical dataset and demonstrate how to assess the model’s accuracy in identifying issues within the data.
        Overview
        Data validation is a critical step in ensuring the quality and reliability of datasets, especially in sensitive fields like healthcare. Traditional validation methods often rely on predefined rules and patterns. However, advanced models like o1 can understand context and reason about data, offering a more flexible and intelligent approach to validation.
        In this tutorial, we will:
        Generate a synthetic dataset of medical data that contains inconsistencies.
        Define a function that takes in a row of data and validates its accuracy
        Run the validation process and compute accuracy metrics.
        Analyze and interpret the results.
        Synthetic Data Generation
        We will use a lot of the principles described in the Synthetic Data Generation cookbook to create the foundation of our dataset.
        We will prompt the model to generate sets of medical data for our use case. We have provide detailed instructions to the model on how to create the dataset, what format to follow, and how to fill it with inaccuracies. We also provide a few rows of sample data to get the model started.
        Each row in the dataset will have the following fields:
        Patient ID: A randomly generated patient id
        Date of Birth: Date of birth of the patient
        Gender: M/F
        Medical History: Past diagnoses
        Current Medications: Medication the patient is taking
        Allergies: Identified allergies
        Lab Results (Glucose mg/dL)
        Diagnoses: Current diagnosis
        Treatment Plan: Current treatment plan
        Is Valid: Whether or not the current row of data is valid (True/False)
        Issue: If the row of data is not valid, what the issue is
        Some examples of inaccuracies that may be present in the data are:
        Prescribing medications that the patient is allergic to
        Current medications do not match medical history
        Treatment plan does not match diagnosis
        Data Validation
        Now that we have our dataset prepared, we will prompt the reasoning model to review each row of data and determine whether or not it contains an issue. We will ask the model to output whether or not there is an issue in the data and then offer an explanation of the issue.
        Once we have the model determine its list of invalid data, we will pass those results on to a model grader to assess two metrics:
        Accuracy of the model&#39;s ability correctly identify issues with the data
        For the subset of data that issues have been correctly identified, what is the accuracy of the model in identifying the issue at hand
        Given that this task is much more narrow, we can use the faster gpt-4o model to calculate the accuracy.
        REMINDER: Given that these models are still in beta, rate limits will be significantly reduced. Please adjust the number of concurrent workers accordingly.
        Now that we have the model&#39;s results, we can compare it against the source of truth and determine the system&#39;s accuracy
        Issue Identification
        We will now determine the model&#39;s ability to accurately classify the issue in the data
        Below we&#39;ll display the subset of rows that we correctly identified contained an issue. For each row, we&#39;ll show the predicted vs. true issue and whether or not there is a match
        Conclusion
        We can see from the results here that we&#39;re able to generate a high precision/recall for issue identification as well as decent accuracy for pinpointing the exact issue in the data.
        This should help streamline data validation for eval sets across a variety of domains.
      </description>
      <link>https://cookbook.openai.com/examples/o1/using_reasoning_for_data_validation</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/o1/using_reasoning_for_data_validation</guid>
      <pubDate>Wed, 11 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Reasoning</category>
    </item>
    <item>
      <title>Using reasoning for routine generation</title>
      <description>When developing customer service solutions, one of the initial steps involves transforming knowledge base articles into a set of routines that an LLM can comprehend and follow. A routine, in this context, refers to a set of step-by-step instructions designed specifically for the LLM to execute efficiently. Each routine is carefully structured so that a step corresponds to a clear action. Actions can include responding to a user, triggering a function call, or retrieving additional relevant knowledge.
        Most internal knowledge base articles are complex and structured for human interpretation. They often include intricate diagrams, multi-step processes, and decision trees that pose challenges for LLM-based solutions to reason through in a meaningful way. By breaking down these documents into routines, each instruction can be simplified and formatted in a way that guides the LLM through a series of small, manageable tasks. This granular approach reduces ambiguity, allowing the LLM to process the information methodically and reducing the risk of hallucination or deviation from the expected path.
        Converting these knowledge base articles into routines can be time-consuming and challenging, especially for companies attempting to build an automated pipeline. Each routine must account for various user scenarios, where actions need to be clearly defined. For instance, when a function call is necessary, the routine must specify the exact information to retrieve or the action to execute—whether it’s triggering an API, retrieving external data, or pulling in additional context. While automating this process with traditional GPT-class models can significantly reduce the manual effort involved, it often introduces new challenges. Some challenges include designing robust instructions that are specific enough for the LLM to follow consistently, capturing unique edge cases that may arise during customer interactions, providing high-quality few-shot examples to guide the model’s behavior, and in some cases, fine-tuning the model to achieve more reliable or specialized outcomes.
        o1 has demonstrated the capability to efficiently deconstruct these articles and convert them into sets of routines zero-shot, meaning that the LLM can understand and follow the instructions without extensive examples or prior training on similar tasks. This minimizes the prompting effort required, as the routine structure itself provides the necessary guidance for the LLM to complete each step. By breaking down tasks into specific actions and integrating function calls where needed, o1’s approach ensures that even complex workflows can be handled seamlessly by the LLM, leading to more effective and scalable customer service solutions.
        Selecting Knowledge Base Articles
        In this example, we will use a set of publicly available Help Center articles from the OpenAI website and convert them into internal routines that an LLM can execute. Besides transforming the policies into routines, we will also have the model generate functions that allow the LLM to perform actions on behalf of the user. This is necessary to allow the LLM to execute the same actions that human agents have, and access additional information that may not be immediately available just from the policy documentation.
        We will begin by using the following Help Center articles for conversion into routines:
        How do I delete my payment method
        How can I get a Business Associate Agreement (BAA) with OpenAI?
        How can I set up prepaid billing?
        How do I submit a VAT exemption request
        We have our articles stored in an accessible csv. We will take the articles and pass them to o1-preview in parallel and generate the initial routines.
        Our instructions for converting the policy to a routine include:
        Converting the policy from an external facing document to an internal SOP routine
        Breaking down the policy in specific actions and sub-actions
        Outlining specific conditions for moving between steps
        Determing where external knowledge/actions may be required, and defining functions that we could use to get that information
        We&#39;ll store the results of our routines in a dataframe and print them out so we can get an initial look.
        Results
        Upon reviewing the generated routines, we can derive several insights:
        Sample Responses: The model effectively generates sample responses that the LLM can utilize when executing the policy (e.g., “Instruct the user: ‘Confirm and purchase your initial amount of credits.’”).
        Discrete Steps: The model excels at decomposing the problem into discrete actions that the LLM needs to execute. Each instruction is clearly defined and easy to interpret.
        Function Definitions: The routines’ outputs include clearly defined functions to retrieve external information or trigger actions (e.g., rev

github-actions[bot] avatar Oct 20 '24 13:10 github-actions[bot]

Successfully generated as following:

http://localhost:1200/cookbook - Success ✔️
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <title>OpenAI Cookbook</title>
    <link>https://cookbook.openai.com/</link>
    <atom:link href="http://localhost:1200/cookbook" rel="self" type="application/rss+xml"></atom:link>
    <description>OpenAI Cookbook - Powered by RSSHub</description>
    <generator>RSSHub</generator>
    <webMaster>[email protected] (RSSHub)</webMaster>
    <language>en</language>
    <lastBuildDate>Tue, 22 Oct 2024 01:41:43 GMT</lastBuildDate>
    <ttl>5</ttl>
    <item>
      <title>Leveraging model distillation to fine-tune a model</title>
      <description>OpenAI recently released Distillation which allows to leverage the outputs of a (large) model to fine-tune another (smaller) model. This can significantly reduce the price and the latency for specific tasks as you move to a smaller model. In this cookbook we&#39;ll look at a dataset, distill the output of gpt-4o to gpt-4o-mini and show how we can get significantly better results than on a generic, non-distilled, 4o-mini.
        We&#39;ll also leverage Structured Outputs for a classification problem using a list of enum. We&#39;ll see how fine-tuned model can benefit from structured output and how it will impact the performance. We&#39;ll show that Structured Ouputs work with all of those models, including the distilled one.
        We&#39;ll first analyze the dataset, get the output of both 4o and 4o mini, highlighting the difference in performance of both models, then proceed to the distillation and analyze the performance of this distilled model.
        Prerequisites
        Let&#39;s install and load dependencies.
        Make sure your OpenAI API key is defined in your environment as &quot;OPENAI_API_KEY&quot; and it&#39;ll be loaded by the client directly.
        Loading and understanding the dataset
        For this cookbook, we&#39;ll load the data from the following Kaggle challenge: https://www.kaggle.com/datasets/zynicide/wine-reviews.
        This dataset has a large number of rows and you&#39;re free to run this cookbook on the whole data, but as a biaised french wine-lover, I&#39;ll narrow down the dataset to only French wine to focus on less rows and grape varieties.
        We&#39;re looking at a classification problem where we&#39;d like to guess the grape variety based on all other criterias available, including description, subregion and province that we&#39;ll include in the prompt. It gives a lot of information to the model, you&#39;re free to also remove some information that can help significantly the model such as the region in which it was produced to see if it does a good job at finding the grape.
        Let&#39;s filter the grape varieties that have less than 5 occurences in reviews.
        Let&#39;s proceed with a subset of 500 random rows from this dataset.
        Let&#39;s retrieve all grape varieties to include them in the prompt and in our structured outputs enum list.
        Generating the prompt
        Let&#39;s build out a function to generate our prompt and try it for the first wine of our list.
        To get a understanding of the cost before running the queries, you can leverage tiktoken to understand the number of tokens we&#39;ll send and the cost associated to run this. This will only give you an estimate for to run the completions, not the fine-tuning process (used later in this cookbook when running the distillation), which depends on other factors such as the number of epochs, training set etc.
        Preparing functions to Store Completions
        As we&#39;re looking at a limited list of response (enumerate list of grape varieties), let&#39;s leverage structured outputs so we make sure the model will answer from this list. This also allows us to compare the model&#39;s answer directly with the grape variety and have a deterministic answer (compared to a model that could answer &quot;I think the grape is Pinot Noir&quot; instead of just &quot;Pinot noir&quot;), on top of improving the performance to avoid grape varieties not in our dataset.
        If you want to know more on Structured Outputs you can read this cookbook and this documentation guide.
        To distill a model, you need to store all completions from a model, allowing you to give it as a reference to the smaller model to fine-tune it. We&#39;re therefore adding a store=True parameter to our client.chat.completions.create method so we can store those completions from gpt-4o.
        We&#39;re going to store all completions (even 4o-mini and our future fine-tuned model) so we are able to run Evals from OpenAI platform directly.
        When storing those completions, it&#39;s useful to store them with a metadata tag, that will allow filtering from the OpenAI platform to run distillation &amp;amp; evals on the specific set of completions you&#39;d like to run those.
        Parallel processing
        As we&#39;ll run this on a large number of rows, let&#39;s make sure we run those completions in parallel and use concurrent futures for this. We&#39;ll iterate on our dataframe and output progress every 20 rows. We&#39;ll store the completion from the model we run the completion for in the same dataframe using the column name {model}-variety.
        Let&#39;s try out our call model function before processing the whole dataframe and check the output.
        Great! We confirmed we can get a grape variety as an output, let&#39;s now process the dataset with both gpt-4o and gpt-4o-mini and compare the results.
        Comparing gpt-4o and gpt-4o-mini
        Now that we&#39;ve got all chat completions for those two models ; let&#39;s compare them against the expected grape variety and assess their accuracy at finding it. We&#39;ll do this directly in python here as we&#39;ve got a simple string check to run, but if your task involves more complex evals you can leverage OpenAI Evals or our open-source eval framework.
        We can see that gpt-4o is better a finding grape variety than 4o-mini (12.80% higher or almost 20% relatively to 4o-mini!). Now I&#39;m wondering if we&#39;re making gpt-4o drink wine during training!
        Distilling gpt-4o outputs to gpt-4o-mini
        Let&#39;s assume we&#39;d like to run this prediction often, we want completions to be faster and cheaper, but keep that level of accuracy. That&#39;d be great to be able to distill 4o accuracy to 4o-mini, wouldn&#39;t it? Let&#39;s do it!
        We&#39;ll now go to OpenAI Stored completions page: https://platform.openai.com/chat-completions.
        Let&#39;s select the model gpt-4o (make sure to do this, you don&#39;t want to distill the outputs of 4o-mini that we ran). Let&#39;s also select the metadata distillation: wine-distillation to get only stored completions ran from this cookbook.
        Once you&#39;ve selected completions, you can click on &quot;Distill&quot; on the top right corner to fine-tune a model based on those completions. Once we&#39;ve done that, a file to run the fine-tuning process will automatically be created. Let&#39;s then select gpt-4o-mini as the base model, keep the default parameters (but you&#39;re free to change them or iterate with it to improve performance).
        Once the fine-tuning job is starting, you can retrieve the fine tuning job ID from the fine-tuning page, we&#39;ll use it to monitor status of the fine-tuned job as well as retrieving the fine-tuned model id once done.
        Running completions for the distilled model
        Now that we&#39;ve got our model fine-tuned, we can use this model to run completions and compare accuracy with both gpt4o and gpt4o-mini.
        Let&#39;s grab a different subset of french wines (as we restricted the outputs to french grape varieties, without outliers, we&#39;ll need to focus our validation dataset to this too). Let&#39;s run this on 300 entries for each models.
        Let&#39;s compare accuracy of models
        That&#39;s almost a 22% relative improvement over the non-distilled gpt-4o-mini! 🎉
        Our fine-tuned model performs way better than gpt-4o-mini, while having the same base model. We&#39;ll be able to use this model to run inferences at a lower cost and lower latency for future grape variety prediction.
      </description>
      <link>https://cookbook.openai.com/examples/leveraging_model_distillation_to_fine-tune_a_model</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/leveraging_model_distillation_to_fine-tune_a_model</guid>
      <pubDate>Tue, 15 Oct 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Fine-tuning</category>
    </item>
    <item>
      <title>Orchestrating Agents: Routines and Handoffs</title>
      <description>When working with language models, quite often all you need for solid performance is a good prompt and the right tools. However, when dealing with many unique flows, things may get hairy. This cookbook will walk through one way to tackle this.
        We&#39;ll introduce the notion of routines and handoffs, then walk through the implementation and show how they can be used to orchestrate multiple agents in a simple, powerful, and controllable way.
        Finally, we provide a sample repo, Swarm, that implements these ideas along with examples.
        Let&#39;s start by setting up our imports.
        Routines
        The notion of a &quot;routine&quot; is not strictly defined, and instead meant to capture the idea of a set of steps. Conretely, let&#39;s define a routine to be a list of instructions in natural langauge (which we&#39;ll represent with a system prompt), along with the tools necessary to complete them.
        Let&#39;s take a look at an example. Below, we&#39;ve defined a routine for a customer service agent instructing it to triage the user issue, then either suggest a fix or provide a refund. We&#39;ve also defined the necessary functions execute_refund and look_up_item. We can call this a customer service routine, agent, assistant, etc –&amp;nbsp;however the idea itself is the same: a set of steps and the tools to execute them.
        The main power of routines is their simplicity and robustness. Notice that these instructions contain conditionals much like a state machine or branching in code. LLMs can actually handle these cases quite robustly for small and medium sized routine, with the added benefit of having &quot;soft&quot; adherance –&amp;nbsp;the LLM can naturally steer the conversation without getting stuck in dead-ends.
        Executing Routines
        To execute a routine, let&#39;s implement a simple loop that:
        Gets user input.
        Appends user message to messages.
        Calls the model.
        Appends model response to messages.
        As you can see, this currently ignores function calls, so let&#39;s add that.
        Models require functions to be formatted as a function schema. For convenience, we can define a helper function that turns python functions into the corresponding function schema.
        For example:
        Now, we can use this function to pass the tools to the model when we call it.
        Finally, when the model calls a tool we need to execute the corresponding function and provide the result back to the model.
        We can do this by mapping the name of the tool to the python function in a tool_map, then looking it up in execute_tool_call and calling it. Finally we add the result to the conversation.
        In practice, we&#39;ll also want to let the model use the result to produce another response. That response might also contain a tool call, so we can just run this in a loop until there are no more tool calls.
        If we put everything together, it will look something like this:
        Now that we have a routine, let&#39;s say we want to add more steps and more tools. We can up to a point, but eventually if we try growing the routine with too many different tasks it may start to struggle. This is where we can leverage the notion of multiple routines – given a user request, we can load the right routine with the appropriate steps and tools to address it.
        Dynamically swapping system instructions and tools may seem daunting. However, if we view &quot;routines&quot; as &quot;agents&quot;, then this notion of handoffs allow us to represent these swaps simply –&amp;nbsp;as one agent handing off a conversation to another.
        Handoffs
        Let&#39;s define a handoff as an agent (or routine) handing off an active conversation to another agent, much like when you get transfered to someone else on a phone call. Except in this case, the agents have complete knowledge of your prior conversation!
        To see handoffs in action, let&#39;s start by defining a basic class for an Agent.
        Now to make our code support it, we can change run_full_turn to take an Agent instead of separate system_message and tools:
        We can now run multiple agents easily:
        Great! But we did the handoff manually here –&amp;nbsp;we want the agents themselves to decide when to perform a handoff. A simple, but surprisingly effective way to do this is by giving them a transfer_to_XXX function, where XXX is some agent. The model is smart enough to know to call this function when it makes sense to make a handoff!
        Handoff Functions
        Now that agent can express the intent to make a handoff, we must make it actually happen. There&#39;s many ways to do this, but there&#39;s one particularly clean way.
        For the agent functions we&#39;ve defined so far, like execute_refund or place_order they return a string, which will be provided to the model. What if instead, we return an Agent object to indate which agent we want to transfer to? Like so:
        We can then update our code to check the return type of a function response, and if it&#39;s an Agent, update the agent in use! Additionally, now run_full_turn will need to return the latest agent in use in case there are handoffs. (We can do this in a Response class to keep things neat.)
        Now for the updated run_full_turn:
        Let&#39;s look at an example with more Agents.
        Finally, we can run this in a loop (this won&#39;t run in python notebooks, so you can try this in a separate python file):
        Swarm
        As a proof of concept, we&#39;ve packaged these ideas into a sample library called Swarm. It is meant as an example only, and should not be directly used in production. However, feel free to take the ideas and code to build your own!
      </description>
      <link>https://cookbook.openai.com/examples/orchestrating_agents</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/orchestrating_agents</guid>
      <pubDate>Wed, 09 Oct 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Functions</category>
    </item>
    <item>
      <title>Prompt Caching 101</title>
      <description>OpenAI offers discounted prompt caching for prompts exceeding 1024 tokens, resulting in up to an 80% reduction in latency for longer prompts over 10,000 tokens. By caching repetitive information across LLM API requests, you can greatly reduce both latency and costs. Prompt caching is scoped at the organization level, meaning only members of the same organization can access shared caches. Additionally, caching is eligible for zero data retention, as no data is stored during the process.
        Prompt caching automatically activates for prompts longer than 1024 tokens-- you don&#39;t have to change anything in your completions request. When an API request is made, the system first checks if the beginning portion (prefix) of the prompt has already been cached. If a match is found (cache hit), the cached prompt is used, leading to reduced latency and costs. If there&#39;s no match, the system processes the full prompt from scratch and caches the prefix for future use.
        With these benefits in mind, some of the key use cases where prompt caching can be especially advantageous are:
        Agents using tools and structured outputs: Cache the extended list of tools and schemas.
        Coding and writing assistants: Insert large sections or summaries of codebases and workspaces directly in prompts.
        Chatbots: Cache static portions of multi-turn conversations to maintain context efficiently over extended dialogues.
        In this cookbook, we&#39;ll go through a couple examples of caching tools and images. Recall that in general, you&#39;ll want to put static content like instructions and examples at the beginning of your prompt, and variable content, such as user-specific information, at the end. This also applies to images and tools, which must be identical even in their ordering between requests. All requests, including those with fewer than 1024 tokens, will display a cached_tokens field of the usage.prompt_tokens_details chat completions object indicating how many of the prompt tokens were a cache hit. For requests under 1024 tokens, cached_tokens will be zero. Caching discounts are based on the actual number of tokens processed, including those used for images, which also count toward your rate limits.
        Example 1: Caching tools and multi-turn conversations
        In this example, we define tools and interactions for a customer support assistant, capable of handling tasks such as checking delivery dates, canceling orders, and updating payment methods. The assistant processes two separate messages, first responding to an initial query, followed by a delayed response to a follow-up query.
        When caching tools, it is important that the tool definitions and their order remain identical for them to be included in the prompt prefix. To cache message histories in a multi-turn conversation, append new elements to the end of the messages array. In the response object and the output below, for the second completion run2, you can see that the cached_tokens value is greater than zero, indicating successful caching.
        Example 2: Images
        In our second example we include multiple image URLs of grocery items in the messages array, along with a user query, run three times with delays. Images—whether linked or encoded in base64 within user messages—qualify for caching. Make sure the detail parameter remains consistent, as it affects how images are tokenized. Note that GPT-4o-mini adds extra tokens to cover image processing costs, even though it uses a low-cost token model for text. Caching discounts are based on the actual number of tokens processed, including those used for images, which also count toward your rate limits.
        The output for this example shows that a cache was hit for the second run, however it was not hit for the third run because of a different first url (eggs_url instead of veggie_url), even though the user query is the same.
        Overall tips
        To get the most out of prompt caching, consider following these best practices:
        Place static or frequently reused content at the beginning of prompts: This helps ensure better cache efficiency by keeping dynamic data towards the end of the prompt.
        Maintain consistent usage patterns: Prompts that aren&#39;t used regularly are automatically removed from the cache. To prevent cache evictions, maintain consistent usage of prompts.
        Monitor key metrics: Regularly track cache hit rates, latency, and the proportion of cached tokens. Use these insights to fine-tune your caching strategy and maximize performance.
        By implementing these practices, you can take full advantage of prompt caching, ensuring that your applications are both responsive and cost-efficient. A well-managed caching strategy will significantly reduce processing times, lower costs, and help maintain smooth user experiences.
      </description>
      <link>https://cookbook.openai.com/examples/prompt_caching101</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/prompt_caching101</guid>
      <pubDate>Mon, 30 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
    </item>
    <item>
      <title>Using chained calls for o1 structured outputs</title>
      <description>The initially released versions (September 2024) of o1 reasoning models have advanced capabilities but do not have structured outputs support.
        This means that requests with o1 don&#39;t have reliable type-safety and rely on the prompt itself to return a useful JSON.
        In this guide, we&#39;ll explore two methods to prompt o1 models, specifically o1-preview, to return a valid JSON format when using the OpenAI API.
        Prompting
        The simplest way to return a JSON response using o1-preview is to explicitly prompt it.
        Let&#39;s run through an example of:
        Fetching a wikipedia page of companies
        Determining which could benefit the most from AI capabilities
        Returning them in a JSON format, which could then be ingested by other systems
        Note that the response is already quite good - it returns the JSON with the appropriate responses. However, it runs into the same pitfalls as existing use-cases of prompt-only JSON inference:
        You must manually process this JSON into your type-safe structure
        Model refusals are not explicitly returned from the API as a separate structure
        Structured Outputs
        Let&#39;s now do this with structured outputs. To enable this functionality, we’ll link the o1-preview response with a follow-up request to gpt-4o-mini, which can effectively process the data returned from the initial o1-preview response.
        Conclusion
        Structured outputs allow your code to have reliable type-safety and simpler prompting. In addition, it allows you to re-use your object schemas for easier integration into your existing workflows.
        The o1 class of models currently doesn&#39;t have structured outputs support, but we can re-use existing structured outputs functionality from gpt-4o-mini by chaining two requests together. This flow currently requires two calls, but the second gpt-4o-mini call cost should be minimal compared to the o1-preview/o1-mini calls.
      </description>
      <link>https://cookbook.openai.com/examples/o1/using_chained_calls_for_o1_structured_outputs</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/o1/using_chained_calls_for_o1_structured_outputs</guid>
      <pubDate>Wed, 25 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Reasoning</category>
    </item>
    <item>
      <title>Building a Bring Your Own Browser (BYOB) Tool for Web Browsing and Summarization</title>
      <description>Disclaimer: This cookbook is for educational purposes only. Ensure that you comply with all applicable laws and service terms when using web search and scraping technologies. This cookbook will restrict the search to openai.com domain to retrieve the public information to illustrate the concepts.
        Large Language Models (LLMs) such as GPT-4o have a knowledge cutoff date, which means they lack information about events that occurred after that point. In scenarios where the most recent data is essential, it&#39;s necessary to provide LLMs with access to current web information to ensure accurate and relevant responses.
        In this guide, we will build a Bring Your Own Browser (BYOB) tool using Python to overcome this limitation. Our goal is to create a system that provides up-to-date answers in your application, including the most recent developments such as the latest product launches by OpenAI. By integrating web search capabilities with an LLM, we&#39;ll enable the model to generate responses based on the latest information available online.
        While you can use any publicly available search APIs, we&#39;ll utilize Google&#39;s Custom Search API to perform web searches. The retrieved information from the search results will be processed and passed to the LLM to generate the final response through Retrieval-Augmented Generation (RAG).
        Bring Your Own Browser (BYOB) tools allow users to perform web browsing tasks programmatically. In this notebook, we&#39;ll create a BYOB tool that:
        #1. Set Up a Search Engine: Use a public search API, such as Google&#39;s Custom Search API, to perform web searches and obtain a list of relevant search results.
        #2. Build a Search Dictionary: Collect the title, URL, and a summary of each web page from the search results to create a structured dictionary of information.
        #3. Generate a RAG Response: Implement Retrieval-Augmented Generation (RAG) by passing the gathered information to the LLM, which then generates a final response to the user&#39;s query.
        Use Case
        In this cookbook, we&#39;ll take the example of a user who wants to list recent product launches by OpenAI in chronological order. Because the current GPT-4o model has a knowledge cutoff date, it is not expected that the model will know about recent product launches such as the o1-preview model launched in September 2024.
        Given the knowledge cutoff, as expected the model does not know about the recent product launches by OpenAI.
        Setting up a BYOB tool
        To provide the model with recent events information, we&#39;ll follow these steps:
        Step 1: Set Up a Search Engine to Provide Web Search Results
        Step 2: Build a Search Dictionary with Titles, URLs, and Summaries of Web Pages
        Step 3: Pass the information to the model to generate a RAG Response to the User Query
        Before we begin, ensure you have the following: Python 3.12 or later installed on your machine. You will also need a Google Custom Search API key and Custom Search Engine ID (CSE ID). Necessary Python packages installed: requests, beautifulsoup4, openai. And ensure the OPENAI_API_KEY is set up as an environment variable.
        Step 1: Set Up a Search Engine to Provide Web Search Results
        You can use any publicly available web search APIs to perform this task. We will configure a custom search engine using Google&#39;s Custom Search API. This engine will fetch a list of relevant web pages based on the user&#39;s query, focusing on obtaining the most recent and pertinent results.
        a. Configure Search API key and Function: Acquire a Google API key and a Custom Search Engine ID (CSE ID) from the Google Developers Console. You can navigate to this Programmable Search Engine Link to set up an API key as well as Custom Search Engine ID (CSE ID).
        The search function below sets up the search based on search term, the API and CSE ID keys, as well as number of search results to return. We&#39;ll introduce a parameter site_filter to restrict the output to only openai.com
        b. Identify the search terms for search engine: Before we can retrieve specific results from a 3rd Party API, we may need to use Query Expansion to identify specific terms our browser search API should retrieve. Query expansion is a process where we broaden the original user query by adding related terms, synonyms, or variations. This technique is essential because search engines, like Google&#39;s Custom Search API, are often better at matching a range of related terms rather than just the natural language prompt used by a user.
        For example, searching with only the raw query &quot;List the latest OpenAI product launches in chronological order from latest to oldest in the past 2 years&quot; may return fewer and less relevant results than a more specific and direct search on a succinct phrase such as &quot;Latest OpenAI product launches&quot;. In the code below, we will use the user&#39;s original search_query to produce a more specific search term to use with the Google API to retrieve the results.
        c. Invoke the search function: Now that we have the search term, we will invoke the search function to retrieve the results from Google search API. The results only have the link of the web page and a snippet at this point. In the next step, we will retrieve more information from the webpage and summarize it in a dictionary to pass to the model.
        Step 2: Build a Search Dictionary with Titles, URLs, and Summaries of Web Pages
        After obtaining the search results, we&#39;ll extract and organize the relevant information, so it can be passed to the LLM for final output.
        a. Scrape Web Page Content: For each URL in the search results, retrieve the web page to extract textual content while filtering out non-relevant data like scripts and advertisements as demonstrated in function retrieve_content.
        b. Summarize Content: Use an LLM to generate concise summaries of the scraped content, focusing on information pertinent to the user&#39;s query. Model can be provided the original search text, so it can focus on summarizing the content for the search intent as outlined in function summarize_content.
        c. Create a Structured Dictionary: Organize the data into a dictionary or a DataFrame containing the title, link, and summary for each web page. This structure can be passed on to the LLM to generate the summary with the appropriate citations.
        We retrieved the most recent results. (Note these will vary depending on when you execute this script.)
        Step 3: Pass the information to the model to generate a RAG Response to the User Query
        With the search data organized in a JSON data structure, we will pass this information to the LLM with the original user query to generate the final response. Now, the LLM response includes information beyond its original knowledge cutoff, providing current insights.
        Conclusion
        Large Language Models (LLMs) have a knowledge cutoff and may not be aware of recent events. To provide them with the latest information, you can build a Bring Your Own Browser (BYOB) tool using Python. This tool retrieves current web data and feeds it to the LLM, enabling up-to-date responses.
        The process involves three main steps:
        #1 Set Up a Search Engine: Use a public search API, like Google&#39;s Custom Search API, to perform web searches and obtain a list of relevant search results.
        #2 Build a Search Dictionary: Collect the title, URL, and a summary of each web page from the search results to create a structured dictionary of information.
        #3. Generate a RAG Response: Implement Retrieval-Augmented Generation (RAG) by passing the gathered information to the LLM, which then generates a final response to the user&#39;s query.
        By following these steps, you enhance the LLMs ability to provide up-to-date answers in your application that include the most recent developments, such as the latest product launches by OpenAI.
      </description>
      <link>https://cookbook.openai.com/examples/third_party/web_search_with_google_api_bring_your_own_browser_tool</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/third_party/web_search_with_google_api_bring_your_own_browser_tool</guid>
      <pubDate>Wed, 25 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
    </item>
    <item>
      <title>GPT Actions library - Canvas Learning Management System</title>
      <description>Table of Contents
        General App Information - Overview of Canvas LMS, its functionality, and the role of ChatGPT&#39;s Custom Actions to enhance educational experiences through AI integration.
        Authentication from ChatGPT to Canvas - Explanation of authentication methods (OAuth and User Generated Access Tokens) for connecting ChatGPT to Canvas, with detailed instructions for setting up each option.
        Sample Use Case: Student Course Assistant - Detailed example of using ChatGPT to assist students with course navigation, exam preparation, and personalized feedback, including specific API calls and workflows.
        Other Use Cases for Consideration - Additional potential integrations using the Canvas API, such as classroom analytics and report generation.
        Congratulations
        General App Information
        Canvas is a widely-used Learning Management System (LMS) designed to support online learning and teaching. It offers a robust set of tools for course management, content delivery, assessments, and student collaboration. Through the Canvas REST API, Canvas allows for extensive customization and integration with third-party applications, including AI-powered tools like ChatGPT.
        ChatGPT’s Custom Actions with Canvas enable educators to leverage AI to enhance course content, automate tasks, and provide personalized learning journeys for students. Examples include virtual teaching assistants based on active courses, as the capabilities are well-suited for pulling information in from Canvas to create an educational dialogue. ChatGPT with Custom Actions is not meant for automating the entire Canvas experience nor act as a replacement to many of its capabilities better suited for completion in the Canvas app.
        Authentication from ChatGPT to Canvas
        For a general overview on Authentication in Custom Actions, see the Action authentication documentation.
        There are two options for authentication in Canvas: 1) OAuth and 2) User Generated Access Tokens.
        For large-scale deployments, it is required to use OAuth for Action Authentication.
        If the user is considering a single-user deployment or does not have access to Admin Settings, they may consider User Generated Access Tokens. Be aware that any request made by the action will be made using the token the user generated, so Canvas will register all requests as the user&#39;s activity and use the user&#39;s permissions to complete them.
        Implementing OAuth for Canvas
        While this Canvas Cookbook does not use OAuth, any deployment with more than one user must use it. See OAuth for Canvas Documentation for a detailed walkthrough.
        Here are some things to keep in mind while implementing OAuth in a Canvas Custom Action:
        Access to Canvas’ Admin settings is required for OAuth in order to retrieve a Client ID and Client Secret.
        The Authorization URL will look like (make sure to update the Canvas Install URL): https:///login/oauth2/auth
        The Token URL will look like (make sure to update the Canvas Install URL): ttps:///login/oauth2/token
        Scopes may not need to be defined in the Custom Action. If the developer key does not require scopes and no scope parameter is specified, the access token will have access to all scopes. If the developer key does require scopes and no scope parameter is specified, Canvas will respond with &quot;invalid_scope.&quot; More information on developer keys here and endpoints here.
        Token Exchange Method is Default (POST Request)
        Canvas uses the term redirect_uri where ChatGPT uses the term Callback URL for URL to complete the redirect process after successful authentication.
        Implementing authentication with User Generated Access Tokens
        In some cases, it may be appropriate to use User Generated Access Tokens for Custom Action authentication with Canvas. Here are the steps to follow to do so:
        Proceed to Canvas Account Settings shown here:
        Scroll down to the List of Tokens shown here:
        Generate a New Token, and store this token. It will not be accessible later.
        Sample Use Case: Student Course Assistant
        Overview
        Assists students in navigating and understanding their courses by providing detailed information, generating personalized practice exams, and offering constructive feedback to enhance learning.
        Considerations
        Some information like the Syllabus is returned as an HTML page when requested by the API. This renders it impossible to show in ChatGPT. Instead, reference course description, modules, and the assignments to guide the user.
        Requests can be modified to retrieve specific pieces of information using the include[] query parameter. If you need to request specific information about a course, provide an example in the GPT instructions.
        GPT Instructions
        There can be multiple ways to write these instructions. See here for guidance on Prompt Engineering strategies and best practices.
        # **Context:** You support college students by providing detailed information about their courses hosted on the Canvas Learning Management System. You help them understand course content, generate practice exams based on provided materials, and offer insightful feedback to aid their learning journey. Assume the students are familiar with basic academic terminologies.
        # **Instructions:**
        ## Scenarios
        ### - When the user asks for information about a specific course, follow this 5 step process:
        1. Ask the user to specify the course they want assistance with and the particular area of focus (e.g., overall course overview, specific module).
        2. If you do not know the Course ID for the course requested, use the listYourCourses to find the right course and corresponding ID in Canvas. If none of the courses listed returned courses that seem to match the course request, use the searchCourses to see if there are any similarly named course.
        3. Retrieve the course information from Canvas using the getSingleCourse API call and the listModules API call.
        4. Ask the user which module(s) they would like to focus on and use the listModuleItems to retrieve the requested module items. For any assignments, share links to them.
        5. Ask if the user needs more information or if they need to prepare for an exam.
        ### When a user asks to take a practice test or practice exam for a specific course, follow this 6 step process:
        1. Ask how many questions
        2. Ask which chapters or topics they want to be tested on, provide a couple examples from the course modules in Canvas.
        3. Ask 1 question at a time, be sure the questions are multiple choice (do not generate the next question until the question is answered)
        4. When the user answers, tell them if its right or wrong and give a description for the correct answer
        5. Ask the user if they want to export the test results and write the code to create the PDF
        6. Offer additional resources and study tips tailored to the user&#39;s needs and progress, and inquire if they require further assistance with other courses or topics.
        ### When a user asks to create a study guide
        - Format the generated study guide in a table
        OpenAPI Schema
        API Calls Featured
        [GET] listYourCourses
        [GET] getSingleCourse
        [GET] listModules
        [GET] listModuleItems
        [GET] searchCourses
        Below was generated with a combination of Canvas API Reference and the ActionsGPT.
        openapi: 3.1.0
        info:
        title: Canvas API
        description: API for interacting with Canvas LMS, including courses, modules, module items, and search functionalities.
        version: 1.0.0
        servers:
        - url: https://canvas.instructure.com/api/v1
        description: Canvas LMS API server
        variables:
        domain:
        default: canvas.instructure.com
        description: The domain of your Canvas instance
        paths:
        /courses:
        get:
        operationId: listYourCourses
        summary: List your courses
        description: Retrieves a paginated list of active courses for the current user.
        parameters:
        - name: enrollment_type
        in: query
        description: Filter by enrollment type (e.g., &quot;teacher&quot;, &quot;student&quot;).
        schema:
        type: string
        - name: enrollment_role
        in: query
        description: Filter by role type. Requires admin permissions.
        schema:
        type: string
        - name: enrollment_state
        in: query
        description: Filter by enrollment state (e.g., &quot;active&quot;, &quot;invited&quot;).
        schema:
        type: string
        - name: exclude_blueprint_courses
        in: query
        description: Exclude Blueprint courses if true.
        schema:
        type: boolean
        - name: include
        in: query
        description: Array of additional information to include (e.g., &quot;term&quot;, &quot;teachers&quot;).
        schema:
        type: array
        items:
        type: string
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of courses.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the course.
        name:
        type: string
        description: The name of the course.
        account_id:
        type: integer
        description: The ID of the account associated with the course.
        enrollment_term_id:
        type: integer
        description: The ID of the term associated with the course.
        start_at:
        type: string
        format: date-time
        description: The start date of the course.
        end_at:
        type: string
        format: date-time
        description: The end date of the course.
        course_code:
        type: string
        description: The course code.
        state:
        type: string
        description: The current state of the course (e.g., &quot;unpublished&quot;, &quot;available&quot;).
        &#39;400&#39;:
        description: Bad request, possibly due to invalid query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        /courses/{course_id}:
        get:
        operationId: getSingleCourse
        summary: Get a single course
        description: Retrieves the details of a specific course by its ID.
        parameters:
        - name: course_id
        in: path
        required: true
        description: The ID of the course.
        schema:
        type: integer
        - name: include
        in: query
        description: Array of additional information to include (e.g., &quot;term&quot;, &quot;teachers&quot;).
        schema:
        type: array
        items:
        type: string
        responses:
        &#39;200&#39;:
        description: A single course object.
        content:
        application/json:
        schema:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the course.
        name:
        type: string
        description: The name of the course.
        account_id:
        type: integer
        description: The ID of the account associated with the course.
        enrollment_term_id:
        type: integer
        description: The ID of the term associated with the course.
        start_at:
        type: string
        format: date-time
        description: The start date of the course.
        end_at:
        type: string
        format: date-time
        description: The end date of the course.
        course_code:
        type: string
        description: The course code.
        state:
        type: string
        description: The current state of the course (e.g., &quot;unpublished&quot;, &quot;available&quot;).
        is_public:
        type: boolean
        description: Whether the course is public.
        syllabus_body:
        type: string
        description: The syllabus content of the course.
        term:
        type: object
        description: The term associated with the course.
        properties:
        id:
        type: integer
        name:
        type: string
        start_at:
        type: string
        format: date-time
        end_at:
        type: string
        format: date-time
        &#39;400&#39;:
        description: Bad request, possibly due to an invalid course ID or query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: Course not found, possibly due to an invalid course ID.
        /courses/{course_id}/modules:
        get:
        operationId: listModules
        summary: List modules in a course
        description: Retrieves the list of modules for a given course in Canvas.
        parameters:
        - name: course_id
        in: path
        required: true
        description: The ID of the course.
        schema:
        type: integer
        - name: include
        in: query
        description: Include additional information such as items in the response.
        schema:
        type: array
        items:
        type: string
        example: [&quot;items&quot;]
        - name: search_term
        in: query
        description: The partial title of the module to match and return.
        schema:
        type: string
        - name: student_id
        in: query
        description: Return module completion information for the student with this ID.
        schema:
        type: integer
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of modules in the course.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the module.
        name:
        type: string
        description: The name of the module.
        items_count:
        type: integer
        description: The number of items in the module.
        state:
        type: string
        description: The state of the module (e.g., &quot;active&quot;, &quot;locked&quot;).
        &#39;400&#39;:
        description: Bad request, possibly due to an invalid course ID or query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: Course not found, possibly due to an invalid course ID.
        /courses/{course_id}/modules/{module_id}/items:
        get:
        operationId: listModuleItems
        summary: List items in a module
        description: Retrieves the list of items within a specific module in a Canvas course.
        parameters:
        - name: course_id
        in: path
        required: true
        description: The ID of the course.
        schema:
        type: integer
        - name: module_id
        in: path
        required: true
        description: The ID of the module.
        schema:
        type: integer
        - name: include
        in: query
        description: Include additional information in the response, such as content details.
        schema:
        type: array
        items:
        type: string
        example: [&quot;content_details&quot;]
        - name: student_id
        in: query
        description: Return completion information for the student with this ID.
        schema:
        type: integer
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of items in the module.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the module item.
        title:
        type: string
        description: The title of the module item.
        type:
        type: string
        description: The type of the module item (e.g., &quot;Assignment&quot;, &quot;File&quot;).
        position:
        type: integer
        description: The position of the item within the module.
        indent:
        type: integer
        description: The level of indentation of the item in the module.
        completion_requirement:
        type: object
        description: The completion requirement for the item.
        properties:
        type:
        type: string
        min_score:
        type: integer
        content_id:
        type: integer
        description: The ID of the associated content item (e.g., assignment, file).
        state:
        type: string
        description: The state of the item (e.g., &quot;active&quot;, &quot;locked&quot;).
        &#39;400&#39;:
        description: Bad request, possibly due to an invalid module ID or query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: Module or course not found, possibly due to an invalid module or course ID.
        /search/all_courses:
        get:
        operationId: searchCourses
        summary: Search for courses
        description: Searches for public courses in Canvas.
        parameters:
        - name: search
        in: query
        description: The search term to filter courses.
        schema:
        type: string
        - name: public_only
        in: query
        description: If true, only returns public courses.
        schema:
        type: boolean
        - name: open_enrollment_only
        in: query
        description: If true, only returns courses with open enrollment.
        schema:
        type: boolean
        - name: enrollment_type
        in: query
        description: Filter by enrollment type (e.g., &quot;teacher&quot;, &quot;student&quot;).
        schema:
        type: string
        - name: sort
        in: query
        description: Sort the results by &quot;asc&quot; or &quot;desc&quot; order.
        schema:
        type: string
        enum:
        - asc
        - desc
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of courses matching the search criteria.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the course.
        name:
        type: string
        description: The name of the course.
        account_id:
        type: integer
        description: The ID of the account associated with the course.
        enrollment_term_id:
        type: integer
        description: The ID of the term associated with the course.
        start_at:
        type: string
        format: date-time
        description: The start date of the course.
        end_at:
        type: string
        format: date-time
        description: The end date of the course.
        course_code:
        type: string
        description: The course code.
        state:
        type: string
        description: The current state of the course (e.g., &quot;unpublished&quot;, &quot;available&quot;).
        is_public:
        type: boolean
        description: Whether the course is public.
        term:
        type: object
        description: The term associated with the course.
        properties:
        id:
        type: integer
        name:
        type: string
        start_at:
        type: string
        format: date-time
        end_at:
        type: string
        format: date-time
        &#39;400&#39;:
        description: Bad request, possibly due to invalid query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: No courses found matching the criteria.
        Sample Conversation Starters
        Help me take a practice exam.
        Give an overview of one of my courses.
        List all of my courses.
        GPT Capabilities
        [On] Web Browsing
        [On] DALL·E Image Generation
        [On] Code Interpreter &amp;amp; Data Analysis
        Other Use Cases for Consideration
        Below is a non-exhaustive list of additional use cases that could be explored using the Canvas API. The basic outline for each is provided, but the GPT Instructions and specific API calls referenced are intentionally left to you as the user to decide what works best for your needs.
        Classroom Analytics and Reports
        Use Case: Empowers teachers with comprehensive analytics and performance reports on student engagement, grades, and participation. By leveraging this data, teachers can make informed decisions to tailor their course delivery, identify at-risk students, and enhance overall classroom effectiveness.
        API Resources:
        Analytics and Quiz Statistics: Retrieve detailed data on student participation, grades, and course-level statistics.
        Quiz Reports: Generate and view various reports to analyze overall class performance and track progress over time.
        Review and Improvement Guidance for Graded Assignments
        Use Case: Provide students with a tool to review their graded assignments, analyze their performance, and receive targeted guidance on how to improve in areas where they have knowledge gaps. The tool can highlight specific questions or sections where the student struggled and suggest additional resources or practice materials to help them improve.
        API Resources:
        Submissions and Quiz Submissions: Retrieve the student’s submissions and associated grades.
        Assignments: Retrieve detailed information about the assignment, including rubrics and grading criteria.
        Rubric Assessments: Access detailed feedback and rubric assessments
        Modules: Suggest additional learning modules that target the student’s weak areas using the List modules API.
        Quizzes: Recommend practice quizzes to help the student improve on specific knowledge gaps
        Congratulations!
        You’ve successfully created a Custom GPT with a working Custom Action using Canvas LMS. You should be able to have a conversation that looks similar to the screenshot below. Great job and keep going!
      </description>
      <link>https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_canvas</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_canvas</guid>
      <pubDate>Mon, 16 Sep 2024 16:00:00 GMT</pubDate>
      <category>ChatGPT</category>
      <category>GPT actions library</category>
    </item>
    <item>
      <title>Using reasoning for data validation</title>
      <description>In this guide, we’ll explore how to use the o1 model, specifically o1-preview, to perform data validation through reasoning. We’ll walk through a practical example involving a synthetic medical dataset and demonstrate how to assess the model’s accuracy in identifying issues within the data.
        Overview
        Data validation is a critical step in ensuring the quality and reliability of datasets, especially in sensitive fields like healthcare. Traditional validation methods often rely on predefined rules and patterns. However, advanced models like o1 can understand context and reason about data, offering a more flexible and intelligent approach to validation.
        In this tutorial, we will:
        Generate a synthetic dataset of medical data that contains inconsistencies.
        Define a function that takes in a row of data and validates its accuracy
        Run the validation process and compute accuracy metrics.
        Analyze and interpret the results.
        Synthetic Data Generation
        We will use a lot of the principles described in the Synthetic Data Generation cookbook to create the foundation of our dataset.
        We will prompt the model to generate sets of medical data for our use case. We have provide detailed instructions to the model on how to create the dataset, what format to follow, and how to fill it with inaccuracies. We also provide a few rows of sample data to get the model started.
        Each row in the dataset will have the following fields:
        Patient ID: A randomly generated patient id
        Date of Birth: Date of birth of the patient
        Gender: M/F
        Medical History: Past diagnoses
        Current Medications: Medication the patient is taking
        Allergies: Identified allergies
        Lab Results (Glucose mg/dL)
        Diagnoses: Current diagnosis
        Treatment Plan: Current treatment plan
        Is Valid: Whether or not the current row of data is valid (True/False)
        Issue: If the row of data is not valid, what the issue is
        Some examples of inaccuracies that may be present in the data are:
        Prescribing medications that the patient is allergic to
        Current medications do not match medical history
        Treatment plan does not match diagnosis
        Data Validation
        Now that we have our dataset prepared, we will prompt the reasoning model to review each row of data and determine whether or not it contains an issue. We will ask the model to output whether or not there is an issue in the data and then offer an explanation of the issue.
        Once we have the model determine its list of invalid data, we will pass those results on to a model grader to assess two metrics:
        Accuracy of the model&#39;s ability correctly identify issues with the data
        For the subset of data that issues have been correctly identified, what is the accuracy of the model in identifying the issue at hand
        Given that this task is much more narrow, we can use the faster gpt-4o model to calculate the accuracy.
        REMINDER: Given that these models are still in beta, rate limits will be significantly reduced. Please adjust the number of concurrent workers accordingly.
        Now that we have the model&#39;s results, we can compare it against the source of truth and determine the system&#39;s accuracy
        Issue Identification
        We will now determine the model&#39;s ability to accurately classify the issue in the data
        Below we&#39;ll display the subset of rows that we correctly identified contained an issue. For each row, we&#39;ll show the predicted vs. true issue and whether or not there is a match
        Conclusion
        We can see from the results here that we&#39;re able to generate a high precision/recall for issue identification as well as decent accuracy for pinpointing the exact issue in the data.
        This should help streamline data validation for eval sets across a variety of domains.
      </description>
      <link>https://cookbook.openai.com/examples/o1/using_reasoning_for_data_validation</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/o1/using_reasoning_for_data_validation</guid>
      <pubDate>Wed, 11 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Reasoning</category>
    </item>
    <item>
      <title>Using reasoning for routine generation</title>
      <description>When developing customer service solutions, one of the initial steps involves transforming knowledge base articles into a set of routines that an LLM can comprehend and follow. A routine, in this context, refers to a set of step-by-step instructions designed specifically for the LLM to execute efficiently. Each routine is carefully structured so that a step corresponds to a clear action. Actions can include responding to a user, triggering a function call, or retrieving additional relevant knowledge.
        Most internal knowledge base articles are complex and structured for human interpretation. They often include intricate diagrams, multi-step processes, and decision trees that pose challenges for LLM-based solutions to reason through in a meaningful way. By breaking down these documents into routines, each instruction can be simplified and formatted in a way that guides the LLM through a series of small, manageable tasks. This granular approach reduces ambiguity, allowing the LLM to process the information methodically and reducing the risk of hallucination or deviation from the expected path.
        Converting these knowledge base articles into routines can be time-consuming and challenging, especially for companies attempting to build an automated pipeline. Each routine must account for various user scenarios, where actions need to be clearly defined. For instance, when a function call is necessary, the routine must specify the exact information to retrieve or the action to execute—whether it’s triggering an API, retrieving external data, or pulling in additional context. While automating this process with traditional GPT-class models can significantly reduce the manual effort involved, it often introduces new challenges. Some challenges include designing robust instructions that are specific enough for the LLM to follow consistently, capturing unique edge cases that may arise during customer interactions, providing high-quality few-shot examples to guide the model’s behavior, and in some cases, fine-tuning the model to achieve more reliable or specialized outcomes.
        o1 has demonstrated the capability to efficiently deconstruct these articles and convert them into sets of routines zero-shot, meaning that the LLM can understand and follow the instructions without extensive examples or prior training on similar tasks. This minimizes the prompting effort required, as the routine structure itself provides the necessary guidance for the LLM to complete each step. By breaking down tasks into specific actions and integrating function calls where needed, o1’s approach ensures that even complex workflows can be handled seamlessly by the LLM, leading to more effective and scalable customer service solutions.
        Selecting Knowledge Base Articles
        In this example, we will use a set of publicly available Help Center articles from the OpenAI website and convert them into internal routines that an LLM can execute. Besides transforming the policies into routines, we will also have the model generate functions that allow the LLM to perform actions on behalf of the user. This is necessary to allow the LLM to execute the same actions that human agents have, and access additional information that may not be immediately available just from the policy documentation.
        We will begin by using the following Help Center articles for conversion into routines:
        How do I delete my payment method
        How can I get a Business Associate Agreement (BAA) with OpenAI?
        How can I set up prepaid billing?
        How do I submit a VAT exemption request
        We have our articles stored in an accessible csv. We will take the articles and pass them to o1-preview in parallel and generate the initial routines.
        Our instructions for converting the policy to a routine include:
        Converting the policy from an external facing document to an internal SOP routine
        Breaking down the policy in specific actions and sub-actions
        Outlining specific conditions for moving between steps
        Determing where external knowledge/actions may be required, and defining functions that we could use to get that information
        We&#39;ll store the results of our routines in a dataframe and print them out so we can get an initial look.
        Results
        Upon reviewing the generated routines, we can derive several insights:
        Sample Responses: The model effectively generates sample responses that the LLM can utilize when executing the policy (e.g., “Instruct the user: ‘Confirm and purchase your initial amount of credits.’”).
        Discrete Steps: The model excels at decomposing the problem into discrete actions that the LLM needs to execute. Each instruction is clearly defined and easy to interpret.
        Function Definitions: The routines’ outputs include clearly defined functions to retrieve external information or trigger actions (e.g., rev

github-actions[bot] avatar Oct 22 '24 01:10 github-actions[bot]

Successfully generated as following:

http://localhost:1200/cookbook - Success ✔️
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <title>OpenAI Cookbook</title>
    <link>https://cookbook.openai.com/</link>
    <atom:link href="http://localhost:1200/cookbook" rel="self" type="application/rss+xml"></atom:link>
    <description>OpenAI Cookbook - Powered by RSSHub</description>
    <generator>RSSHub</generator>
    <webMaster>[email protected] (RSSHub)</webMaster>
    <language>en</language>
    <lastBuildDate>Tue, 22 Oct 2024 07:40:45 GMT</lastBuildDate>
    <ttl>5</ttl>
    <item>
      <title>Leveraging model distillation to fine-tune a model</title>
      <description>OpenAI recently released Distillation which allows to leverage the outputs of a (large) model to fine-tune another (smaller) model. This can significantly reduce the price and the latency for specific tasks as you move to a smaller model. In this cookbook we&#39;ll look at a dataset, distill the output of gpt-4o to gpt-4o-mini and show how we can get significantly better results than on a generic, non-distilled, 4o-mini.
        We&#39;ll also leverage Structured Outputs for a classification problem using a list of enum. We&#39;ll see how fine-tuned model can benefit from structured output and how it will impact the performance. We&#39;ll show that Structured Ouputs work with all of those models, including the distilled one.
        We&#39;ll first analyze the dataset, get the output of both 4o and 4o mini, highlighting the difference in performance of both models, then proceed to the distillation and analyze the performance of this distilled model.
        Prerequisites
        Let&#39;s install and load dependencies.
        Make sure your OpenAI API key is defined in your environment as &quot;OPENAI_API_KEY&quot; and it&#39;ll be loaded by the client directly.
        Loading and understanding the dataset
        For this cookbook, we&#39;ll load the data from the following Kaggle challenge: https://www.kaggle.com/datasets/zynicide/wine-reviews.
        This dataset has a large number of rows and you&#39;re free to run this cookbook on the whole data, but as a biaised french wine-lover, I&#39;ll narrow down the dataset to only French wine to focus on less rows and grape varieties.
        We&#39;re looking at a classification problem where we&#39;d like to guess the grape variety based on all other criterias available, including description, subregion and province that we&#39;ll include in the prompt. It gives a lot of information to the model, you&#39;re free to also remove some information that can help significantly the model such as the region in which it was produced to see if it does a good job at finding the grape.
        Let&#39;s filter the grape varieties that have less than 5 occurences in reviews.
        Let&#39;s proceed with a subset of 500 random rows from this dataset.
        Let&#39;s retrieve all grape varieties to include them in the prompt and in our structured outputs enum list.
        Generating the prompt
        Let&#39;s build out a function to generate our prompt and try it for the first wine of our list.
        To get a understanding of the cost before running the queries, you can leverage tiktoken to understand the number of tokens we&#39;ll send and the cost associated to run this. This will only give you an estimate for to run the completions, not the fine-tuning process (used later in this cookbook when running the distillation), which depends on other factors such as the number of epochs, training set etc.
        Preparing functions to Store Completions
        As we&#39;re looking at a limited list of response (enumerate list of grape varieties), let&#39;s leverage structured outputs so we make sure the model will answer from this list. This also allows us to compare the model&#39;s answer directly with the grape variety and have a deterministic answer (compared to a model that could answer &quot;I think the grape is Pinot Noir&quot; instead of just &quot;Pinot noir&quot;), on top of improving the performance to avoid grape varieties not in our dataset.
        If you want to know more on Structured Outputs you can read this cookbook and this documentation guide.
        To distill a model, you need to store all completions from a model, allowing you to give it as a reference to the smaller model to fine-tune it. We&#39;re therefore adding a store=True parameter to our client.chat.completions.create method so we can store those completions from gpt-4o.
        We&#39;re going to store all completions (even 4o-mini and our future fine-tuned model) so we are able to run Evals from OpenAI platform directly.
        When storing those completions, it&#39;s useful to store them with a metadata tag, that will allow filtering from the OpenAI platform to run distillation &amp;amp; evals on the specific set of completions you&#39;d like to run those.
        Parallel processing
        As we&#39;ll run this on a large number of rows, let&#39;s make sure we run those completions in parallel and use concurrent futures for this. We&#39;ll iterate on our dataframe and output progress every 20 rows. We&#39;ll store the completion from the model we run the completion for in the same dataframe using the column name {model}-variety.
        Let&#39;s try out our call model function before processing the whole dataframe and check the output.
        Great! We confirmed we can get a grape variety as an output, let&#39;s now process the dataset with both gpt-4o and gpt-4o-mini and compare the results.
        Comparing gpt-4o and gpt-4o-mini
        Now that we&#39;ve got all chat completions for those two models ; let&#39;s compare them against the expected grape variety and assess their accuracy at finding it. We&#39;ll do this directly in python here as we&#39;ve got a simple string check to run, but if your task involves more complex evals you can leverage OpenAI Evals or our open-source eval framework.
        We can see that gpt-4o is better a finding grape variety than 4o-mini (12.80% higher or almost 20% relatively to 4o-mini!). Now I&#39;m wondering if we&#39;re making gpt-4o drink wine during training!
        Distilling gpt-4o outputs to gpt-4o-mini
        Let&#39;s assume we&#39;d like to run this prediction often, we want completions to be faster and cheaper, but keep that level of accuracy. That&#39;d be great to be able to distill 4o accuracy to 4o-mini, wouldn&#39;t it? Let&#39;s do it!
        We&#39;ll now go to OpenAI Stored completions page: https://platform.openai.com/chat-completions.
        Let&#39;s select the model gpt-4o (make sure to do this, you don&#39;t want to distill the outputs of 4o-mini that we ran). Let&#39;s also select the metadata distillation: wine-distillation to get only stored completions ran from this cookbook.
        Once you&#39;ve selected completions, you can click on &quot;Distill&quot; on the top right corner to fine-tune a model based on those completions. Once we&#39;ve done that, a file to run the fine-tuning process will automatically be created. Let&#39;s then select gpt-4o-mini as the base model, keep the default parameters (but you&#39;re free to change them or iterate with it to improve performance).
        Once the fine-tuning job is starting, you can retrieve the fine tuning job ID from the fine-tuning page, we&#39;ll use it to monitor status of the fine-tuned job as well as retrieving the fine-tuned model id once done.
        Running completions for the distilled model
        Now that we&#39;ve got our model fine-tuned, we can use this model to run completions and compare accuracy with both gpt4o and gpt4o-mini.
        Let&#39;s grab a different subset of french wines (as we restricted the outputs to french grape varieties, without outliers, we&#39;ll need to focus our validation dataset to this too). Let&#39;s run this on 300 entries for each models.
        Let&#39;s compare accuracy of models
        That&#39;s almost a 22% relative improvement over the non-distilled gpt-4o-mini! 🎉
        Our fine-tuned model performs way better than gpt-4o-mini, while having the same base model. We&#39;ll be able to use this model to run inferences at a lower cost and lower latency for future grape variety prediction.
      </description>
      <link>https://cookbook.openai.com/examples/leveraging_model_distillation_to_fine-tune_a_model</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/leveraging_model_distillation_to_fine-tune_a_model</guid>
      <pubDate>Tue, 15 Oct 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Fine-tuning</category>
    </item>
    <item>
      <title>Orchestrating Agents: Routines and Handoffs</title>
      <description>When working with language models, quite often all you need for solid performance is a good prompt and the right tools. However, when dealing with many unique flows, things may get hairy. This cookbook will walk through one way to tackle this.
        We&#39;ll introduce the notion of routines and handoffs, then walk through the implementation and show how they can be used to orchestrate multiple agents in a simple, powerful, and controllable way.
        Finally, we provide a sample repo, Swarm, that implements these ideas along with examples.
        Let&#39;s start by setting up our imports.
        Routines
        The notion of a &quot;routine&quot; is not strictly defined, and instead meant to capture the idea of a set of steps. Conretely, let&#39;s define a routine to be a list of instructions in natural langauge (which we&#39;ll represent with a system prompt), along with the tools necessary to complete them.
        Let&#39;s take a look at an example. Below, we&#39;ve defined a routine for a customer service agent instructing it to triage the user issue, then either suggest a fix or provide a refund. We&#39;ve also defined the necessary functions execute_refund and look_up_item. We can call this a customer service routine, agent, assistant, etc –&amp;nbsp;however the idea itself is the same: a set of steps and the tools to execute them.
        The main power of routines is their simplicity and robustness. Notice that these instructions contain conditionals much like a state machine or branching in code. LLMs can actually handle these cases quite robustly for small and medium sized routine, with the added benefit of having &quot;soft&quot; adherance –&amp;nbsp;the LLM can naturally steer the conversation without getting stuck in dead-ends.
        Executing Routines
        To execute a routine, let&#39;s implement a simple loop that:
        Gets user input.
        Appends user message to messages.
        Calls the model.
        Appends model response to messages.
        As you can see, this currently ignores function calls, so let&#39;s add that.
        Models require functions to be formatted as a function schema. For convenience, we can define a helper function that turns python functions into the corresponding function schema.
        For example:
        Now, we can use this function to pass the tools to the model when we call it.
        Finally, when the model calls a tool we need to execute the corresponding function and provide the result back to the model.
        We can do this by mapping the name of the tool to the python function in a tool_map, then looking it up in execute_tool_call and calling it. Finally we add the result to the conversation.
        In practice, we&#39;ll also want to let the model use the result to produce another response. That response might also contain a tool call, so we can just run this in a loop until there are no more tool calls.
        If we put everything together, it will look something like this:
        Now that we have a routine, let&#39;s say we want to add more steps and more tools. We can up to a point, but eventually if we try growing the routine with too many different tasks it may start to struggle. This is where we can leverage the notion of multiple routines – given a user request, we can load the right routine with the appropriate steps and tools to address it.
        Dynamically swapping system instructions and tools may seem daunting. However, if we view &quot;routines&quot; as &quot;agents&quot;, then this notion of handoffs allow us to represent these swaps simply –&amp;nbsp;as one agent handing off a conversation to another.
        Handoffs
        Let&#39;s define a handoff as an agent (or routine) handing off an active conversation to another agent, much like when you get transfered to someone else on a phone call. Except in this case, the agents have complete knowledge of your prior conversation!
        To see handoffs in action, let&#39;s start by defining a basic class for an Agent.
        Now to make our code support it, we can change run_full_turn to take an Agent instead of separate system_message and tools:
        We can now run multiple agents easily:
        Great! But we did the handoff manually here –&amp;nbsp;we want the agents themselves to decide when to perform a handoff. A simple, but surprisingly effective way to do this is by giving them a transfer_to_XXX function, where XXX is some agent. The model is smart enough to know to call this function when it makes sense to make a handoff!
        Handoff Functions
        Now that agent can express the intent to make a handoff, we must make it actually happen. There&#39;s many ways to do this, but there&#39;s one particularly clean way.
        For the agent functions we&#39;ve defined so far, like execute_refund or place_order they return a string, which will be provided to the model. What if instead, we return an Agent object to indate which agent we want to transfer to? Like so:
        We can then update our code to check the return type of a function response, and if it&#39;s an Agent, update the agent in use! Additionally, now run_full_turn will need to return the latest agent in use in case there are handoffs. (We can do this in a Response class to keep things neat.)
        Now for the updated run_full_turn:
        Let&#39;s look at an example with more Agents.
        Finally, we can run this in a loop (this won&#39;t run in python notebooks, so you can try this in a separate python file):
        Swarm
        As a proof of concept, we&#39;ve packaged these ideas into a sample library called Swarm. It is meant as an example only, and should not be directly used in production. However, feel free to take the ideas and code to build your own!
      </description>
      <link>https://cookbook.openai.com/examples/orchestrating_agents</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/orchestrating_agents</guid>
      <pubDate>Wed, 09 Oct 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Functions</category>
    </item>
    <item>
      <title>Prompt Caching 101</title>
      <description>OpenAI offers discounted prompt caching for prompts exceeding 1024 tokens, resulting in up to an 80% reduction in latency for longer prompts over 10,000 tokens. By caching repetitive information across LLM API requests, you can greatly reduce both latency and costs. Prompt caching is scoped at the organization level, meaning only members of the same organization can access shared caches. Additionally, caching is eligible for zero data retention, as no data is stored during the process.
        Prompt caching automatically activates for prompts longer than 1024 tokens-- you don&#39;t have to change anything in your completions request. When an API request is made, the system first checks if the beginning portion (prefix) of the prompt has already been cached. If a match is found (cache hit), the cached prompt is used, leading to reduced latency and costs. If there&#39;s no match, the system processes the full prompt from scratch and caches the prefix for future use.
        With these benefits in mind, some of the key use cases where prompt caching can be especially advantageous are:
        Agents using tools and structured outputs: Cache the extended list of tools and schemas.
        Coding and writing assistants: Insert large sections or summaries of codebases and workspaces directly in prompts.
        Chatbots: Cache static portions of multi-turn conversations to maintain context efficiently over extended dialogues.
        In this cookbook, we&#39;ll go through a couple examples of caching tools and images. Recall that in general, you&#39;ll want to put static content like instructions and examples at the beginning of your prompt, and variable content, such as user-specific information, at the end. This also applies to images and tools, which must be identical even in their ordering between requests. All requests, including those with fewer than 1024 tokens, will display a cached_tokens field of the usage.prompt_tokens_details chat completions object indicating how many of the prompt tokens were a cache hit. For requests under 1024 tokens, cached_tokens will be zero. Caching discounts are based on the actual number of tokens processed, including those used for images, which also count toward your rate limits.
        Example 1: Caching tools and multi-turn conversations
        In this example, we define tools and interactions for a customer support assistant, capable of handling tasks such as checking delivery dates, canceling orders, and updating payment methods. The assistant processes two separate messages, first responding to an initial query, followed by a delayed response to a follow-up query.
        When caching tools, it is important that the tool definitions and their order remain identical for them to be included in the prompt prefix. To cache message histories in a multi-turn conversation, append new elements to the end of the messages array. In the response object and the output below, for the second completion run2, you can see that the cached_tokens value is greater than zero, indicating successful caching.
        Example 2: Images
        In our second example we include multiple image URLs of grocery items in the messages array, along with a user query, run three times with delays. Images—whether linked or encoded in base64 within user messages—qualify for caching. Make sure the detail parameter remains consistent, as it affects how images are tokenized. Note that GPT-4o-mini adds extra tokens to cover image processing costs, even though it uses a low-cost token model for text. Caching discounts are based on the actual number of tokens processed, including those used for images, which also count toward your rate limits.
        The output for this example shows that a cache was hit for the second run, however it was not hit for the third run because of a different first url (eggs_url instead of veggie_url), even though the user query is the same.
        Overall tips
        To get the most out of prompt caching, consider following these best practices:
        Place static or frequently reused content at the beginning of prompts: This helps ensure better cache efficiency by keeping dynamic data towards the end of the prompt.
        Maintain consistent usage patterns: Prompts that aren&#39;t used regularly are automatically removed from the cache. To prevent cache evictions, maintain consistent usage of prompts.
        Monitor key metrics: Regularly track cache hit rates, latency, and the proportion of cached tokens. Use these insights to fine-tune your caching strategy and maximize performance.
        By implementing these practices, you can take full advantage of prompt caching, ensuring that your applications are both responsive and cost-efficient. A well-managed caching strategy will significantly reduce processing times, lower costs, and help maintain smooth user experiences.
      </description>
      <link>https://cookbook.openai.com/examples/prompt_caching101</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/prompt_caching101</guid>
      <pubDate>Mon, 30 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
    </item>
    <item>
      <title>Using chained calls for o1 structured outputs</title>
      <description>The initially released versions (September 2024) of o1 reasoning models have advanced capabilities but do not have structured outputs support.
        This means that requests with o1 don&#39;t have reliable type-safety and rely on the prompt itself to return a useful JSON.
        In this guide, we&#39;ll explore two methods to prompt o1 models, specifically o1-preview, to return a valid JSON format when using the OpenAI API.
        Prompting
        The simplest way to return a JSON response using o1-preview is to explicitly prompt it.
        Let&#39;s run through an example of:
        Fetching a wikipedia page of companies
        Determining which could benefit the most from AI capabilities
        Returning them in a JSON format, which could then be ingested by other systems
        Note that the response is already quite good - it returns the JSON with the appropriate responses. However, it runs into the same pitfalls as existing use-cases of prompt-only JSON inference:
        You must manually process this JSON into your type-safe structure
        Model refusals are not explicitly returned from the API as a separate structure
        Structured Outputs
        Let&#39;s now do this with structured outputs. To enable this functionality, we’ll link the o1-preview response with a follow-up request to gpt-4o-mini, which can effectively process the data returned from the initial o1-preview response.
        Conclusion
        Structured outputs allow your code to have reliable type-safety and simpler prompting. In addition, it allows you to re-use your object schemas for easier integration into your existing workflows.
        The o1 class of models currently doesn&#39;t have structured outputs support, but we can re-use existing structured outputs functionality from gpt-4o-mini by chaining two requests together. This flow currently requires two calls, but the second gpt-4o-mini call cost should be minimal compared to the o1-preview/o1-mini calls.
      </description>
      <link>https://cookbook.openai.com/examples/o1/using_chained_calls_for_o1_structured_outputs</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/o1/using_chained_calls_for_o1_structured_outputs</guid>
      <pubDate>Wed, 25 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Reasoning</category>
    </item>
    <item>
      <title>Building a Bring Your Own Browser (BYOB) Tool for Web Browsing and Summarization</title>
      <description>Disclaimer: This cookbook is for educational purposes only. Ensure that you comply with all applicable laws and service terms when using web search and scraping technologies. This cookbook will restrict the search to openai.com domain to retrieve the public information to illustrate the concepts.
        Large Language Models (LLMs) such as GPT-4o have a knowledge cutoff date, which means they lack information about events that occurred after that point. In scenarios where the most recent data is essential, it&#39;s necessary to provide LLMs with access to current web information to ensure accurate and relevant responses.
        In this guide, we will build a Bring Your Own Browser (BYOB) tool using Python to overcome this limitation. Our goal is to create a system that provides up-to-date answers in your application, including the most recent developments such as the latest product launches by OpenAI. By integrating web search capabilities with an LLM, we&#39;ll enable the model to generate responses based on the latest information available online.
        While you can use any publicly available search APIs, we&#39;ll utilize Google&#39;s Custom Search API to perform web searches. The retrieved information from the search results will be processed and passed to the LLM to generate the final response through Retrieval-Augmented Generation (RAG).
        Bring Your Own Browser (BYOB) tools allow users to perform web browsing tasks programmatically. In this notebook, we&#39;ll create a BYOB tool that:
        #1. Set Up a Search Engine: Use a public search API, such as Google&#39;s Custom Search API, to perform web searches and obtain a list of relevant search results.
        #2. Build a Search Dictionary: Collect the title, URL, and a summary of each web page from the search results to create a structured dictionary of information.
        #3. Generate a RAG Response: Implement Retrieval-Augmented Generation (RAG) by passing the gathered information to the LLM, which then generates a final response to the user&#39;s query.
        Use Case
        In this cookbook, we&#39;ll take the example of a user who wants to list recent product launches by OpenAI in chronological order. Because the current GPT-4o model has a knowledge cutoff date, it is not expected that the model will know about recent product launches such as the o1-preview model launched in September 2024.
        Given the knowledge cutoff, as expected the model does not know about the recent product launches by OpenAI.
        Setting up a BYOB tool
        To provide the model with recent events information, we&#39;ll follow these steps:
        Step 1: Set Up a Search Engine to Provide Web Search Results
        Step 2: Build a Search Dictionary with Titles, URLs, and Summaries of Web Pages
        Step 3: Pass the information to the model to generate a RAG Response to the User Query
        Before we begin, ensure you have the following: Python 3.12 or later installed on your machine. You will also need a Google Custom Search API key and Custom Search Engine ID (CSE ID). Necessary Python packages installed: requests, beautifulsoup4, openai. And ensure the OPENAI_API_KEY is set up as an environment variable.
        Step 1: Set Up a Search Engine to Provide Web Search Results
        You can use any publicly available web search APIs to perform this task. We will configure a custom search engine using Google&#39;s Custom Search API. This engine will fetch a list of relevant web pages based on the user&#39;s query, focusing on obtaining the most recent and pertinent results.
        a. Configure Search API key and Function: Acquire a Google API key and a Custom Search Engine ID (CSE ID) from the Google Developers Console. You can navigate to this Programmable Search Engine Link to set up an API key as well as Custom Search Engine ID (CSE ID).
        The search function below sets up the search based on search term, the API and CSE ID keys, as well as number of search results to return. We&#39;ll introduce a parameter site_filter to restrict the output to only openai.com
        b. Identify the search terms for search engine: Before we can retrieve specific results from a 3rd Party API, we may need to use Query Expansion to identify specific terms our browser search API should retrieve. Query expansion is a process where we broaden the original user query by adding related terms, synonyms, or variations. This technique is essential because search engines, like Google&#39;s Custom Search API, are often better at matching a range of related terms rather than just the natural language prompt used by a user.
        For example, searching with only the raw query &quot;List the latest OpenAI product launches in chronological order from latest to oldest in the past 2 years&quot; may return fewer and less relevant results than a more specific and direct search on a succinct phrase such as &quot;Latest OpenAI product launches&quot;. In the code below, we will use the user&#39;s original search_query to produce a more specific search term to use with the Google API to retrieve the results.
        c. Invoke the search function: Now that we have the search term, we will invoke the search function to retrieve the results from Google search API. The results only have the link of the web page and a snippet at this point. In the next step, we will retrieve more information from the webpage and summarize it in a dictionary to pass to the model.
        Step 2: Build a Search Dictionary with Titles, URLs, and Summaries of Web Pages
        After obtaining the search results, we&#39;ll extract and organize the relevant information, so it can be passed to the LLM for final output.
        a. Scrape Web Page Content: For each URL in the search results, retrieve the web page to extract textual content while filtering out non-relevant data like scripts and advertisements as demonstrated in function retrieve_content.
        b. Summarize Content: Use an LLM to generate concise summaries of the scraped content, focusing on information pertinent to the user&#39;s query. Model can be provided the original search text, so it can focus on summarizing the content for the search intent as outlined in function summarize_content.
        c. Create a Structured Dictionary: Organize the data into a dictionary or a DataFrame containing the title, link, and summary for each web page. This structure can be passed on to the LLM to generate the summary with the appropriate citations.
        We retrieved the most recent results. (Note these will vary depending on when you execute this script.)
        Step 3: Pass the information to the model to generate a RAG Response to the User Query
        With the search data organized in a JSON data structure, we will pass this information to the LLM with the original user query to generate the final response. Now, the LLM response includes information beyond its original knowledge cutoff, providing current insights.
        Conclusion
        Large Language Models (LLMs) have a knowledge cutoff and may not be aware of recent events. To provide them with the latest information, you can build a Bring Your Own Browser (BYOB) tool using Python. This tool retrieves current web data and feeds it to the LLM, enabling up-to-date responses.
        The process involves three main steps:
        #1 Set Up a Search Engine: Use a public search API, like Google&#39;s Custom Search API, to perform web searches and obtain a list of relevant search results.
        #2 Build a Search Dictionary: Collect the title, URL, and a summary of each web page from the search results to create a structured dictionary of information.
        #3. Generate a RAG Response: Implement Retrieval-Augmented Generation (RAG) by passing the gathered information to the LLM, which then generates a final response to the user&#39;s query.
        By following these steps, you enhance the LLMs ability to provide up-to-date answers in your application that include the most recent developments, such as the latest product launches by OpenAI.
      </description>
      <link>https://cookbook.openai.com/examples/third_party/web_search_with_google_api_bring_your_own_browser_tool</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/third_party/web_search_with_google_api_bring_your_own_browser_tool</guid>
      <pubDate>Wed, 25 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
    </item>
    <item>
      <title>GPT Actions library - Canvas Learning Management System</title>
      <description>Table of Contents
        General App Information - Overview of Canvas LMS, its functionality, and the role of ChatGPT&#39;s Custom Actions to enhance educational experiences through AI integration.
        Authentication from ChatGPT to Canvas - Explanation of authentication methods (OAuth and User Generated Access Tokens) for connecting ChatGPT to Canvas, with detailed instructions for setting up each option.
        Sample Use Case: Student Course Assistant - Detailed example of using ChatGPT to assist students with course navigation, exam preparation, and personalized feedback, including specific API calls and workflows.
        Other Use Cases for Consideration - Additional potential integrations using the Canvas API, such as classroom analytics and report generation.
        Congratulations
        General App Information
        Canvas is a widely-used Learning Management System (LMS) designed to support online learning and teaching. It offers a robust set of tools for course management, content delivery, assessments, and student collaboration. Through the Canvas REST API, Canvas allows for extensive customization and integration with third-party applications, including AI-powered tools like ChatGPT.
        ChatGPT’s Custom Actions with Canvas enable educators to leverage AI to enhance course content, automate tasks, and provide personalized learning journeys for students. Examples include virtual teaching assistants based on active courses, as the capabilities are well-suited for pulling information in from Canvas to create an educational dialogue. ChatGPT with Custom Actions is not meant for automating the entire Canvas experience nor act as a replacement to many of its capabilities better suited for completion in the Canvas app.
        Authentication from ChatGPT to Canvas
        For a general overview on Authentication in Custom Actions, see the Action authentication documentation.
        There are two options for authentication in Canvas: 1) OAuth and 2) User Generated Access Tokens.
        For large-scale deployments, it is required to use OAuth for Action Authentication.
        If the user is considering a single-user deployment or does not have access to Admin Settings, they may consider User Generated Access Tokens. Be aware that any request made by the action will be made using the token the user generated, so Canvas will register all requests as the user&#39;s activity and use the user&#39;s permissions to complete them.
        Implementing OAuth for Canvas
        While this Canvas Cookbook does not use OAuth, any deployment with more than one user must use it. See OAuth for Canvas Documentation for a detailed walkthrough.
        Here are some things to keep in mind while implementing OAuth in a Canvas Custom Action:
        Access to Canvas’ Admin settings is required for OAuth in order to retrieve a Client ID and Client Secret.
        The Authorization URL will look like (make sure to update the Canvas Install URL): https:///login/oauth2/auth
        The Token URL will look like (make sure to update the Canvas Install URL): ttps:///login/oauth2/token
        Scopes may not need to be defined in the Custom Action. If the developer key does not require scopes and no scope parameter is specified, the access token will have access to all scopes. If the developer key does require scopes and no scope parameter is specified, Canvas will respond with &quot;invalid_scope.&quot; More information on developer keys here and endpoints here.
        Token Exchange Method is Default (POST Request)
        Canvas uses the term redirect_uri where ChatGPT uses the term Callback URL for URL to complete the redirect process after successful authentication.
        Implementing authentication with User Generated Access Tokens
        In some cases, it may be appropriate to use User Generated Access Tokens for Custom Action authentication with Canvas. Here are the steps to follow to do so:
        Proceed to Canvas Account Settings shown here:
        Scroll down to the List of Tokens shown here:
        Generate a New Token, and store this token. It will not be accessible later.
        Sample Use Case: Student Course Assistant
        Overview
        Assists students in navigating and understanding their courses by providing detailed information, generating personalized practice exams, and offering constructive feedback to enhance learning.
        Considerations
        Some information like the Syllabus is returned as an HTML page when requested by the API. This renders it impossible to show in ChatGPT. Instead, reference course description, modules, and the assignments to guide the user.
        Requests can be modified to retrieve specific pieces of information using the include[] query parameter. If you need to request specific information about a course, provide an example in the GPT instructions.
        GPT Instructions
        There can be multiple ways to write these instructions. See here for guidance on Prompt Engineering strategies and best practices.
        # **Context:** You support college students by providing detailed information about their courses hosted on the Canvas Learning Management System. You help them understand course content, generate practice exams based on provided materials, and offer insightful feedback to aid their learning journey. Assume the students are familiar with basic academic terminologies.
        # **Instructions:**
        ## Scenarios
        ### - When the user asks for information about a specific course, follow this 5 step process:
        1. Ask the user to specify the course they want assistance with and the particular area of focus (e.g., overall course overview, specific module).
        2. If you do not know the Course ID for the course requested, use the listYourCourses to find the right course and corresponding ID in Canvas. If none of the courses listed returned courses that seem to match the course request, use the searchCourses to see if there are any similarly named course.
        3. Retrieve the course information from Canvas using the getSingleCourse API call and the listModules API call.
        4. Ask the user which module(s) they would like to focus on and use the listModuleItems to retrieve the requested module items. For any assignments, share links to them.
        5. Ask if the user needs more information or if they need to prepare for an exam.
        ### When a user asks to take a practice test or practice exam for a specific course, follow this 6 step process:
        1. Ask how many questions
        2. Ask which chapters or topics they want to be tested on, provide a couple examples from the course modules in Canvas.
        3. Ask 1 question at a time, be sure the questions are multiple choice (do not generate the next question until the question is answered)
        4. When the user answers, tell them if its right or wrong and give a description for the correct answer
        5. Ask the user if they want to export the test results and write the code to create the PDF
        6. Offer additional resources and study tips tailored to the user&#39;s needs and progress, and inquire if they require further assistance with other courses or topics.
        ### When a user asks to create a study guide
        - Format the generated study guide in a table
        OpenAPI Schema
        API Calls Featured
        [GET] listYourCourses
        [GET] getSingleCourse
        [GET] listModules
        [GET] listModuleItems
        [GET] searchCourses
        Below was generated with a combination of Canvas API Reference and the ActionsGPT.
        openapi: 3.1.0
        info:
        title: Canvas API
        description: API for interacting with Canvas LMS, including courses, modules, module items, and search functionalities.
        version: 1.0.0
        servers:
        - url: https://canvas.instructure.com/api/v1
        description: Canvas LMS API server
        variables:
        domain:
        default: canvas.instructure.com
        description: The domain of your Canvas instance
        paths:
        /courses:
        get:
        operationId: listYourCourses
        summary: List your courses
        description: Retrieves a paginated list of active courses for the current user.
        parameters:
        - name: enrollment_type
        in: query
        description: Filter by enrollment type (e.g., &quot;teacher&quot;, &quot;student&quot;).
        schema:
        type: string
        - name: enrollment_role
        in: query
        description: Filter by role type. Requires admin permissions.
        schema:
        type: string
        - name: enrollment_state
        in: query
        description: Filter by enrollment state (e.g., &quot;active&quot;, &quot;invited&quot;).
        schema:
        type: string
        - name: exclude_blueprint_courses
        in: query
        description: Exclude Blueprint courses if true.
        schema:
        type: boolean
        - name: include
        in: query
        description: Array of additional information to include (e.g., &quot;term&quot;, &quot;teachers&quot;).
        schema:
        type: array
        items:
        type: string
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of courses.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the course.
        name:
        type: string
        description: The name of the course.
        account_id:
        type: integer
        description: The ID of the account associated with the course.
        enrollment_term_id:
        type: integer
        description: The ID of the term associated with the course.
        start_at:
        type: string
        format: date-time
        description: The start date of the course.
        end_at:
        type: string
        format: date-time
        description: The end date of the course.
        course_code:
        type: string
        description: The course code.
        state:
        type: string
        description: The current state of the course (e.g., &quot;unpublished&quot;, &quot;available&quot;).
        &#39;400&#39;:
        description: Bad request, possibly due to invalid query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        /courses/{course_id}:
        get:
        operationId: getSingleCourse
        summary: Get a single course
        description: Retrieves the details of a specific course by its ID.
        parameters:
        - name: course_id
        in: path
        required: true
        description: The ID of the course.
        schema:
        type: integer
        - name: include
        in: query
        description: Array of additional information to include (e.g., &quot;term&quot;, &quot;teachers&quot;).
        schema:
        type: array
        items:
        type: string
        responses:
        &#39;200&#39;:
        description: A single course object.
        content:
        application/json:
        schema:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the course.
        name:
        type: string
        description: The name of the course.
        account_id:
        type: integer
        description: The ID of the account associated with the course.
        enrollment_term_id:
        type: integer
        description: The ID of the term associated with the course.
        start_at:
        type: string
        format: date-time
        description: The start date of the course.
        end_at:
        type: string
        format: date-time
        description: The end date of the course.
        course_code:
        type: string
        description: The course code.
        state:
        type: string
        description: The current state of the course (e.g., &quot;unpublished&quot;, &quot;available&quot;).
        is_public:
        type: boolean
        description: Whether the course is public.
        syllabus_body:
        type: string
        description: The syllabus content of the course.
        term:
        type: object
        description: The term associated with the course.
        properties:
        id:
        type: integer
        name:
        type: string
        start_at:
        type: string
        format: date-time
        end_at:
        type: string
        format: date-time
        &#39;400&#39;:
        description: Bad request, possibly due to an invalid course ID or query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: Course not found, possibly due to an invalid course ID.
        /courses/{course_id}/modules:
        get:
        operationId: listModules
        summary: List modules in a course
        description: Retrieves the list of modules for a given course in Canvas.
        parameters:
        - name: course_id
        in: path
        required: true
        description: The ID of the course.
        schema:
        type: integer
        - name: include
        in: query
        description: Include additional information such as items in the response.
        schema:
        type: array
        items:
        type: string
        example: [&quot;items&quot;]
        - name: search_term
        in: query
        description: The partial title of the module to match and return.
        schema:
        type: string
        - name: student_id
        in: query
        description: Return module completion information for the student with this ID.
        schema:
        type: integer
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of modules in the course.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the module.
        name:
        type: string
        description: The name of the module.
        items_count:
        type: integer
        description: The number of items in the module.
        state:
        type: string
        description: The state of the module (e.g., &quot;active&quot;, &quot;locked&quot;).
        &#39;400&#39;:
        description: Bad request, possibly due to an invalid course ID or query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: Course not found, possibly due to an invalid course ID.
        /courses/{course_id}/modules/{module_id}/items:
        get:
        operationId: listModuleItems
        summary: List items in a module
        description: Retrieves the list of items within a specific module in a Canvas course.
        parameters:
        - name: course_id
        in: path
        required: true
        description: The ID of the course.
        schema:
        type: integer
        - name: module_id
        in: path
        required: true
        description: The ID of the module.
        schema:
        type: integer
        - name: include
        in: query
        description: Include additional information in the response, such as content details.
        schema:
        type: array
        items:
        type: string
        example: [&quot;content_details&quot;]
        - name: student_id
        in: query
        description: Return completion information for the student with this ID.
        schema:
        type: integer
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of items in the module.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the module item.
        title:
        type: string
        description: The title of the module item.
        type:
        type: string
        description: The type of the module item (e.g., &quot;Assignment&quot;, &quot;File&quot;).
        position:
        type: integer
        description: The position of the item within the module.
        indent:
        type: integer
        description: The level of indentation of the item in the module.
        completion_requirement:
        type: object
        description: The completion requirement for the item.
        properties:
        type:
        type: string
        min_score:
        type: integer
        content_id:
        type: integer
        description: The ID of the associated content item (e.g., assignment, file).
        state:
        type: string
        description: The state of the item (e.g., &quot;active&quot;, &quot;locked&quot;).
        &#39;400&#39;:
        description: Bad request, possibly due to an invalid module ID or query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: Module or course not found, possibly due to an invalid module or course ID.
        /search/all_courses:
        get:
        operationId: searchCourses
        summary: Search for courses
        description: Searches for public courses in Canvas.
        parameters:
        - name: search
        in: query
        description: The search term to filter courses.
        schema:
        type: string
        - name: public_only
        in: query
        description: If true, only returns public courses.
        schema:
        type: boolean
        - name: open_enrollment_only
        in: query
        description: If true, only returns courses with open enrollment.
        schema:
        type: boolean
        - name: enrollment_type
        in: query
        description: Filter by enrollment type (e.g., &quot;teacher&quot;, &quot;student&quot;).
        schema:
        type: string
        - name: sort
        in: query
        description: Sort the results by &quot;asc&quot; or &quot;desc&quot; order.
        schema:
        type: string
        enum:
        - asc
        - desc
        - name: per_page
        in: query
        description: The number of results to return per page.
        schema:
        type: integer
        example: 10
        - name: page
        in: query
        description: The page number to return.
        schema:
        type: integer
        example: 1
        responses:
        &#39;200&#39;:
        description: A list of courses matching the search criteria.
        content:
        application/json:
        schema:
        type: array
        items:
        type: object
        properties:
        id:
        type: integer
        description: The ID of the course.
        name:
        type: string
        description: The name of the course.
        account_id:
        type: integer
        description: The ID of the account associated with the course.
        enrollment_term_id:
        type: integer
        description: The ID of the term associated with the course.
        start_at:
        type: string
        format: date-time
        description: The start date of the course.
        end_at:
        type: string
        format: date-time
        description: The end date of the course.
        course_code:
        type: string
        description: The course code.
        state:
        type: string
        description: The current state of the course (e.g., &quot;unpublished&quot;, &quot;available&quot;).
        is_public:
        type: boolean
        description: Whether the course is public.
        term:
        type: object
        description: The term associated with the course.
        properties:
        id:
        type: integer
        name:
        type: string
        start_at:
        type: string
        format: date-time
        end_at:
        type: string
        format: date-time
        &#39;400&#39;:
        description: Bad request, possibly due to invalid query parameters.
        &#39;401&#39;:
        description: Unauthorized, likely due to invalid authentication credentials.
        &#39;404&#39;:
        description: No courses found matching the criteria.
        Sample Conversation Starters
        Help me take a practice exam.
        Give an overview of one of my courses.
        List all of my courses.
        GPT Capabilities
        [On] Web Browsing
        [On] DALL·E Image Generation
        [On] Code Interpreter &amp;amp; Data Analysis
        Other Use Cases for Consideration
        Below is a non-exhaustive list of additional use cases that could be explored using the Canvas API. The basic outline for each is provided, but the GPT Instructions and specific API calls referenced are intentionally left to you as the user to decide what works best for your needs.
        Classroom Analytics and Reports
        Use Case: Empowers teachers with comprehensive analytics and performance reports on student engagement, grades, and participation. By leveraging this data, teachers can make informed decisions to tailor their course delivery, identify at-risk students, and enhance overall classroom effectiveness.
        API Resources:
        Analytics and Quiz Statistics: Retrieve detailed data on student participation, grades, and course-level statistics.
        Quiz Reports: Generate and view various reports to analyze overall class performance and track progress over time.
        Review and Improvement Guidance for Graded Assignments
        Use Case: Provide students with a tool to review their graded assignments, analyze their performance, and receive targeted guidance on how to improve in areas where they have knowledge gaps. The tool can highlight specific questions or sections where the student struggled and suggest additional resources or practice materials to help them improve.
        API Resources:
        Submissions and Quiz Submissions: Retrieve the student’s submissions and associated grades.
        Assignments: Retrieve detailed information about the assignment, including rubrics and grading criteria.
        Rubric Assessments: Access detailed feedback and rubric assessments
        Modules: Suggest additional learning modules that target the student’s weak areas using the List modules API.
        Quizzes: Recommend practice quizzes to help the student improve on specific knowledge gaps
        Congratulations!
        You’ve successfully created a Custom GPT with a working Custom Action using Canvas LMS. You should be able to have a conversation that looks similar to the screenshot below. Great job and keep going!
      </description>
      <link>https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_canvas</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_canvas</guid>
      <pubDate>Mon, 16 Sep 2024 16:00:00 GMT</pubDate>
      <category>ChatGPT</category>
      <category>GPT actions library</category>
    </item>
    <item>
      <title>Using reasoning for data validation</title>
      <description>In this guide, we’ll explore how to use the o1 model, specifically o1-preview, to perform data validation through reasoning. We’ll walk through a practical example involving a synthetic medical dataset and demonstrate how to assess the model’s accuracy in identifying issues within the data.
        Overview
        Data validation is a critical step in ensuring the quality and reliability of datasets, especially in sensitive fields like healthcare. Traditional validation methods often rely on predefined rules and patterns. However, advanced models like o1 can understand context and reason about data, offering a more flexible and intelligent approach to validation.
        In this tutorial, we will:
        Generate a synthetic dataset of medical data that contains inconsistencies.
        Define a function that takes in a row of data and validates its accuracy
        Run the validation process and compute accuracy metrics.
        Analyze and interpret the results.
        Synthetic Data Generation
        We will use a lot of the principles described in the Synthetic Data Generation cookbook to create the foundation of our dataset.
        We will prompt the model to generate sets of medical data for our use case. We have provide detailed instructions to the model on how to create the dataset, what format to follow, and how to fill it with inaccuracies. We also provide a few rows of sample data to get the model started.
        Each row in the dataset will have the following fields:
        Patient ID: A randomly generated patient id
        Date of Birth: Date of birth of the patient
        Gender: M/F
        Medical History: Past diagnoses
        Current Medications: Medication the patient is taking
        Allergies: Identified allergies
        Lab Results (Glucose mg/dL)
        Diagnoses: Current diagnosis
        Treatment Plan: Current treatment plan
        Is Valid: Whether or not the current row of data is valid (True/False)
        Issue: If the row of data is not valid, what the issue is
        Some examples of inaccuracies that may be present in the data are:
        Prescribing medications that the patient is allergic to
        Current medications do not match medical history
        Treatment plan does not match diagnosis
        Data Validation
        Now that we have our dataset prepared, we will prompt the reasoning model to review each row of data and determine whether or not it contains an issue. We will ask the model to output whether or not there is an issue in the data and then offer an explanation of the issue.
        Once we have the model determine its list of invalid data, we will pass those results on to a model grader to assess two metrics:
        Accuracy of the model&#39;s ability correctly identify issues with the data
        For the subset of data that issues have been correctly identified, what is the accuracy of the model in identifying the issue at hand
        Given that this task is much more narrow, we can use the faster gpt-4o model to calculate the accuracy.
        REMINDER: Given that these models are still in beta, rate limits will be significantly reduced. Please adjust the number of concurrent workers accordingly.
        Now that we have the model&#39;s results, we can compare it against the source of truth and determine the system&#39;s accuracy
        Issue Identification
        We will now determine the model&#39;s ability to accurately classify the issue in the data
        Below we&#39;ll display the subset of rows that we correctly identified contained an issue. For each row, we&#39;ll show the predicted vs. true issue and whether or not there is a match
        Conclusion
        We can see from the results here that we&#39;re able to generate a high precision/recall for issue identification as well as decent accuracy for pinpointing the exact issue in the data.
        This should help streamline data validation for eval sets across a variety of domains.
      </description>
      <link>https://cookbook.openai.com/examples/o1/using_reasoning_for_data_validation</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/o1/using_reasoning_for_data_validation</guid>
      <pubDate>Wed, 11 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Reasoning</category>
    </item>
    <item>
      <title>Using reasoning for routine generation</title>
      <description>When developing customer service solutions, one of the initial steps involves transforming knowledge base articles into a set of routines that an LLM can comprehend and follow. A routine, in this context, refers to a set of step-by-step instructions designed specifically for the LLM to execute efficiently. Each routine is carefully structured so that a step corresponds to a clear action. Actions can include responding to a user, triggering a function call, or retrieving additional relevant knowledge.
        Most internal knowledge base articles are complex and structured for human interpretation. They often include intricate diagrams, multi-step processes, and decision trees that pose challenges for LLM-based solutions to reason through in a meaningful way. By breaking down these documents into routines, each instruction can be simplified and formatted in a way that guides the LLM through a series of small, manageable tasks. This granular approach reduces ambiguity, allowing the LLM to process the information methodically and reducing the risk of hallucination or deviation from the expected path.
        Converting these knowledge base articles into routines can be time-consuming and challenging, especially for companies attempting to build an automated pipeline. Each routine must account for various user scenarios, where actions need to be clearly defined. For instance, when a function call is necessary, the routine must specify the exact information to retrieve or the action to execute—whether it’s triggering an API, retrieving external data, or pulling in additional context. While automating this process with traditional GPT-class models can significantly reduce the manual effort involved, it often introduces new challenges. Some challenges include designing robust instructions that are specific enough for the LLM to follow consistently, capturing unique edge cases that may arise during customer interactions, providing high-quality few-shot examples to guide the model’s behavior, and in some cases, fine-tuning the model to achieve more reliable or specialized outcomes.
        o1 has demonstrated the capability to efficiently deconstruct these articles and convert them into sets of routines zero-shot, meaning that the LLM can understand and follow the instructions without extensive examples or prior training on similar tasks. This minimizes the prompting effort required, as the routine structure itself provides the necessary guidance for the LLM to complete each step. By breaking down tasks into specific actions and integrating function calls where needed, o1’s approach ensures that even complex workflows can be handled seamlessly by the LLM, leading to more effective and scalable customer service solutions.
        Selecting Knowledge Base Articles
        In this example, we will use a set of publicly available Help Center articles from the OpenAI website and convert them into internal routines that an LLM can execute. Besides transforming the policies into routines, we will also have the model generate functions that allow the LLM to perform actions on behalf of the user. This is necessary to allow the LLM to execute the same actions that human agents have, and access additional information that may not be immediately available just from the policy documentation.
        We will begin by using the following Help Center articles for conversion into routines:
        How do I delete my payment method
        How can I get a Business Associate Agreement (BAA) with OpenAI?
        How can I set up prepaid billing?
        How do I submit a VAT exemption request
        We have our articles stored in an accessible csv. We will take the articles and pass them to o1-preview in parallel and generate the initial routines.
        Our instructions for converting the policy to a routine include:
        Converting the policy from an external facing document to an internal SOP routine
        Breaking down the policy in specific actions and sub-actions
        Outlining specific conditions for moving between steps
        Determing where external knowledge/actions may be required, and defining functions that we could use to get that information
        We&#39;ll store the results of our routines in a dataframe and print them out so we can get an initial look.
        Results
        Upon reviewing the generated routines, we can derive several insights:
        Sample Responses: The model effectively generates sample responses that the LLM can utilize when executing the policy (e.g., “Instruct the user: ‘Confirm and purchase your initial amount of credits.’”).
        Discrete Steps: The model excels at decomposing the problem into discrete actions that the LLM needs to execute. Each instruction is clearly defined and easy to interpret.
        Function Definitions: The routines’ outputs include clearly defined functions to retrieve external information or trigger actions (e.g., rev

github-actions[bot] avatar Oct 22 '24 07:10 github-actions[bot]

Successfully generated as following:

http://localhost:1200/cookbook - Success ✔️
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <title>OpenAI Cookbook</title>
    <link>https://cookbook.openai.com/</link>
    <atom:link href="http://localhost:1200/cookbook" rel="self" type="application/rss+xml"></atom:link>
    <description>OpenAI Cookbook - Powered by RSSHub</description>
    <generator>RSSHub</generator>
    <webMaster>[email protected] (RSSHub)</webMaster>
    <language>en</language>
    <lastBuildDate>Wed, 30 Oct 2024 02:13:55 GMT</lastBuildDate>
    <ttl>5</ttl>
    <item>
      <title>Enhance your prompts with meta prompting</title>
      <description>Welcome to our cookbook on meta prompting! In this guide, we&#39;ll explore how to take a basic prompt and refine it to enhance the quality of outputs from a language model. We&#39;ll use the example of summarizing news reports to illustrate the process.
        Meta-prompting is a technique where you use an LLM to generate or improve prompts. Typically this is done using a higher intelligence model that optimizes prompts for a model with less intelligence. It’s a process of using prompts to guide, structure, and optimize other prompts, helping ensure they’re more effective in guiding the LLM towards high-quality, relevant outputs. We&#39;ll be leveraging the capabilities of o1-preview, a more intelligent model with advanced reasoning skills, to improve a prompt for gpt-4o.
        We&#39;re committed to making your development journey with LLMs smoother and more accessible through this technique. Don&#39;t forget to check out our Generate Anything feature in the playground — it&#39;s a fantastic starting point to dive into meta prompting.
        In this example, we&#39;ll begin with a simple prompt for summarizing news articles and then enhance it to see how the outputs improve. We&#39;ll use o1-preview to analyze and refine our prompt, adding more detail and clarity along the way. Finally, we&#39;ll evaluate the outputs systematically to understand the impact of our refinements.
        Importing the Data
        Let&#39;s kick things off by importing the bbc_news_alltime dataset from HuggingFace. This dataset contains all BBC News articles, capturing everything published monthly from 2017 up to the latest complete month. For our experiment, we&#39;ll focus exclusively on a sample from a recent month—August 2024—to keep things current and manageable.
        Iterating on Prompts
        Let&#39;s start with a straightforward prompt and then use o1-preview to enhance it for better results. We want to summarize news articles, so this is what i&#39;ll ask the model to do.
        To improve the prompt, we need to provide o1-preview with the context and goals we want to achieve. We can then ask it to generate a more detailed prompt that would produce richer and more comprehensive news summaries.
        Generating the Summaries
        Now that we have both prompts, let&#39;s generate the summaries! For each entry in our dataset, we&#39;ll use both the simple and the enhanced prompts to see how they compare. By doing this, we&#39;ll get a firsthand look at how our refinements with o1-preview can lead to richer and more detailed summaries. Let&#39;s dive in and see the difference for ourselves!
        Let&#39;s check if everything looks good and if we can generate a summary for the first news report.
        By comparing the summaries generated from the simple and enhanced prompts, we can already see significant improvements. The initial summary gives us a general overview of the article, whereas the enhanced summary dives deeper — it not only provides a detailed summary but also categorizes the news type, lists relevant tags, and even includes a sentiment analysis.
        Let&#39;s test on the entire dataset now!
        Evaluating the Results
        To assess the difference in performance between the two prompts, we&#39;ll use a structured evaluation approach with the LLM acting as a judge. This means we&#39;ll leverage the language model itself to evaluate and compare the outputs based on specific criteria.
        What Does &quot;LLM as a Judge&quot; Mean?
        Using an LLM as a judge involves having the language model evaluate its own outputs or those of another model. It applies predefined criteria to assess aspects like accuracy, clarity, and relevance. This approach helps us obtain an objective and consistent evaluation without human bias, making it easier to identify improvements between different prompts. Our cookbook on Getting Started with OpenAI Evals offers a glimps on how you can get started with this approach.
        Here&#39;s the prompt we&#39;ll use for evaluation:
        Here&#39;s a pro tip — you can actually use meta prompting to refine your evaluation prompt as well! By applying the same iterative enhancement to the prompt that instructs the LLM to act as a judge, you can make your evaluations even more precise and insightful.
        Let&#39;s use this prompt to evaluate our summaries!
        After evaluating the results, we found that while the basic prompt performed well in clarity and structure, the enhanced prompt significantly improved outputs across several other key criteria: Categorization, Keywords and Tags, Sentiment Analysis, and Detail and Completeness. The complex prompt led to summaries that were more informative, better organized, and richer in content.
        This demonstrates how refining prompts can greatly enhance the quality of the generated summaries. Although this is a simplified example, the benefits of prompt optimization are expected to be even more pronounced in real-world, production-level applications, leading to outputs that are more aligned with specific goals and user needs.
        Conclusion
        Meta prompting is a powerful technique that can significantly enhance the quality of outputs from language models. Our exploration showed that starting with a simple prompt and refining it using o1-preview led to summaries that were more informative, better organized, and richer in content—improving across key criteria like categorization, keywords and tags, sentiment analysis, and completeness. This exercise underscores the value of prompt optimization, and even in this simplified example, the benefits are clear. In real-world applications, leveraging meta prompting and tools like o1-preview can elevate language model performance to better meet your specific goals and user needs.
      </description>
      <link>https://cookbook.openai.com/examples/enhance_your_prompts_with_meta_prompting</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/enhance_your_prompts_with_meta_prompting</guid>
      <pubDate>Tue, 22 Oct 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Reasoning</category>
    </item>
    <item>
      <title>GPT Actions library - GitHub</title>
      <description>Introduction
        This page provides instructions for developers connecting a GPT Action to GitHub. Before proceeding, familiarize yourself with the following resources:
        Introduction to GPT Actions
        GPT Actions Library
        Building a GPT Action from Scratch
        This GPT Action helps developers evaluate the quality and security of a GitHub Pull Request diff. It provides feedback and suggestions for each domain, allowing developers to modify or accept the feedback before automatically submitting it as a comment on the Pull Request.
        Value &amp;amp; Example Business Use Cases
        Value:
        Users can leverage ChatGPT&#39;s natural language capabilities to assist with GitHub Pull Request reviews.
        For developers: Analyze code changes and perform high-quality reviews with instant feedback on proposed modifications.
        For organizations: Ensure diffs adhere to best practices and coding standards, or automatically propose refactored alternatives (additional API requests may be required to define best practices).
        Overall: Boost productivity and ensure higher-quality, more secure code with this AI-powered Code Review assistant.
        Example Use Cases:
        A reviewer seeks feedback on the quality and security of a proposed code change.
        An organization encourages adherence to best practices and standards automatically during code review.
        Demonstration Video:
        Application Information
        Key Links
        Before starting, explore these resources:
        GitHub
        GitHub API Documentation
        Prerequisites
        Ensure you have a repository with an open pull request.
        Application Setup
        Select a Pull Request
        Navigate to a repository, e.g., example PR.
        Note the owner (e.g., &quot;microsoft&quot;), repository name (e.g., &quot;vscode&quot;), and PR number (e.g., &quot;229241&quot;).
        If the repository owner is an SSO organization, your token may need approval.
        Review how to perform a high-quality code review.
        Generate a &quot;Fine Grained&quot; GitHub Personal Access Token
        Log in to GitHub and go to Settings.
        Navigate to Developer settings &amp;gt; Fine Grained Personal access tokens.
        Click Generate new token, name it, set an expiration date, and select the necessary scopes (e.g., read:content, read&amp;amp;write:pull_requests).
        Copy and securely store the token.
        ChatGPT Steps
        Custom GPT Instructions
        Once you&#39;ve created a Custom GPT, copy the following into the Instructions panel:
        # **Context:** You support software developers by providing detailed information about their pull request diff content from repositories hosted on GitHub. You help them understand the quality, security and completeness implications of the pull request by providing concise feedback about the code changes based on known best practices. The developer may elect to post the feedback (possibly with their modifications) back to the Pull Request. Assume the developer is familiar with software development.
        # **Instructions:**
        ## Scenarios
        ### - When the user asks for information about a specific pull request, follow this 5 step process:
        1. If you don&#39;t already have it, ask the user to specify the pull request owner, repository and pull request number they want assistance with and the particular area of focus (e.g., code performance, security vulnerabilities, and best practices).
        2. Retrieve the Pull Request information from GitHub using the getPullRequestDiff API call, owner, repository and the pull request number provided.
        3. Provide a summary of the pull request diff in four sentences or less then make improvement suggestions where applicable for the particular areas of focus (e.g., code performance, security vulnerabilities, and best practices).
        4. Ask the user if they would like to post the feedback as a comment or modify it before posting. If the user modifies the feedback, incorporate that feedback and repeat this step.
        5. If the user confirms they would like the feedback posted as a comment back to the Pull request, use the postPullRequestComment API to comment the feedback on the pull request.
        OpenAPI Schema
        Once you&#39;ve created a Custom GPT, copy the text below in the Actions panel. Have questions? Check out Getting Started Example to see how this step works in more detail.
        Below is an example of what connecting to GitHub to GET the Pull Request Diff and POST the Feedback to the Pull Request might look like.
        openapi: 3.1.0
        info:
        title: GitHub Pull Request API
        description: Retrieve the diff of a pull request and post comments back to it.
        version: 1.0.0
        servers:
        - url: https://api.github.com
        description: GitHub API
        paths:
        /repos/{owner}/{repo}/pulls/{pull_number}:
        get:
        operationId: getPullRequestDiff
        summary: Get the diff of a pull request.
        parameters:
        - name: owner
        in: path
        required: true
        schema:
        type: string
        description: Owner of the repository.
        - name: repo
        in: path
        required: true
        schema:
        type: string
        description: Name of the repository.
        - name: pull_number
        in: path
        required: true
        schema:
        type: integer
        description: The number of the pull request.
        - name: Accept
        in: header
        required: true
        schema:
        type: string
        enum:
        - application/vnd.github.v3.diff
        description: Media type for the diff format.
        responses:
        &quot;200&quot;:
        description: Successfully retrieved the pull request diff.
        content:
        text/plain:
        schema:
        type: string
        &quot;404&quot;:
        description: Pull request not found.
        /repos/{owner}/{repo}/issues/{issue_number}/comments:
        post:
        operationId: postPullRequestComment
        summary: Post a comment to the pull request.
        parameters:
        - name: owner
        in: path
        required: true
        schema:
        type: string
        description: Owner of the repository.
        - name: repo
        in: path
        required: true
        schema:
        type: string
        description: Name of the repository.
        - name: issue_number
        in: path
        required: true
        schema:
        type: integer
        description: The issue or pull request number.
        requestBody:
        required: true
        content:
        application/json:
        schema:
        type: object
        properties:
        body:
        type: string
        description: The content of the comment.
        responses:
        &quot;201&quot;:
        description: Successfully created a comment.
        content:
        application/json:
        schema:
        type: object
        properties:
        id:
        type: integer
        body:
        type: string
        user:
        type: object
        properties:
        login:
        type: string
        id:
        type: integer
        &quot;404&quot;:
        description: Pull request not found.
        Authentication Instructions
        Below are instructions on setting up authentication with this 3rd party application. Have questions? Check out Getting Started Example to see how this step works in more detail.
        In ChatGPT (refer to Step 2 in the Getting Started Example)
        In ChatGPT, click on &quot;Authentication&quot; and choose &quot;Bearer&quot;. Enter in the information below. Ensure your token has the permissions described in Application setup, above.
        Authentication Type: API Key
        Auth Type: Bearer
        API Key
        &lt;personal_access_token&gt;
        Test the GPT
        You are now ready to test out the GPT. You can enter a simple prompt like &quot;Can you review my pull request? owner: &lt;org_name&gt;, repo: &lt;repo_name&gt;, pull request number: &lt;pr_number&gt;&quot; and expect to see the following:
        A summary of changes in the referenced pull request(PR).
        Quality and Security feedback and suggestions to incorporate in the next iteration of the PR.
        An option to iterate on the feedback or accept it and have the GPT post it directly to the PR as a comment from you.
        Are there integrations that you’d like us to prioritize? Are there errors in our integrations? File a PR or issue in our github, and we’ll take a look.
        &lt;/pr_number&gt;&lt;/repo_name&gt;&lt;/org_name&gt;&lt;/personal_access_token&gt;</description>
      <link>https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_github</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_github</guid>
      <pubDate>Tue, 22 Oct 2024 16:00:00 GMT</pubDate>
      <category>ChatGPT</category>
      <category>GPT actions library</category>
    </item>
    <item>
      <title>Voice Translation into Different Languages</title>
      <description>Have you ever wanted to translate a podcast into your native language? Translating and dubbing audio content can make it more accessible to audiences worldwide. With GPT-4o&#39;s new audio-in and audio-out modality, this process is now easier than ever.
        This guide will walk you through translating an English audio file into Hindi using OpenAI&#39;s GPT-4o audio modality API.
        GPT-4o simplifies the dubbing process for audio content. Previously, you had to convert the audio to text and then translate the text into the target language before converting it back into audio. Now, with GPT-4o’s voice-to-voice capability, you can achieve this in a single step with audio input and output.
        A note on semantics used in this Cookbook regarding Language and written Script. These words are generally used interchangeably, though it&#39;s important to understand the distinction, given the task at hand.
        - Language refers to the spoken or written system of communication. For instance, Hindi and Marathi are different languages, but both use the Devanagari script. Similarly, English and French are different languages, but are written in Latin script.
        - Script refers to the set of characters or symbols used to write the language. For example, Serbian language traditionally written in Cyrillic Script, is also written in Latin script.
        GPT-4o audio-in and audio-out modality makes it easier to dub the audio from one language to another with one API call.
        1. Transcribe the source audio file into source language script using GPT-4o. This is an optional step that can be skipped if you already have the transcription of source audio content.
        2. Dub the audio file from source language directly to the target langauge.
        3. Obtain Translation Benchmarks using BLEU or ROUGE.
        4. Interpret and improve scores by adjusting prompting parameters in steps 1-3 as needed.
        Before we get started, make sure you have your OpenAI API key configured as an environment variable, and necessary packages installed as outlined in the code cells below.
        Step 1: Transcribe the Audio to Source Language Script using GPT-4o
        Let&#39;s start by creating a function that sends an audio file to OpenAI&#39;s GPT-4o API for processing, using the chat completions API endpoint.
        The function process_audio_with_gpt_4o takes three inputs:
        A base64-encoded audio file (base64_encoded_audio) that will be sent to the GPT-4o model.
        Desired output modalities (such as text, or both text and audio).
        A system prompt that instructs the model on how to process the input.
        The function sends an API request to OpenAI&#39;s chat/completions endpoint. The request headers include the API key for authorization. The data payload contains the model type (gpt-4o-audio-preview), the selected output modalities, and audio details, such as the voice type and format (in this case, &quot;alloy&quot; and &quot;wav&quot;). It also includes the system prompt and the base64-encoded audio file as part of the &quot;user&quot; message. If the API request is successful (HTTP status 200), the response is returned as JSON. If an error occurs (non-200 status), it prints the error code and message.
        This function enables audio processing through OpenAI&#39;s GPT-4o API, allowing tasks like dubbing, transcription, or translation to be performed based on the input provided.
        Using the function process_audio_with_gpt_4o, we will first get an English transcription of the source audio. You can skip this step if you already have a transcription in the source language.
        In this step, we:
        Read the WAV file and convert it into base64 encoding.
        Set the output modality to [&quot;text&quot;], as we only need a text transcription.
        Provide a system prompt to instruct the model to focus on transcribing the speech and to ignore background noises like applause.
        Call the process_audio_with_gpt_4o function to process the audio and return the transcription.
        This English transcript will serve as our ground truth as we benchmark the Hindi language dubbing of the audio in Step 3.
        Step 2. Dub the Audio from the Source Language to the Target Language using GPT-4o
        With GPT-4o, we can directly dub the audio file from English to Hindi and get the Hindi transcription of the audio in one API call. For this, we set the output modality to [&quot;text&quot;, &quot;audio&quot;]
        In the following code snippet, we will retrieve both the Hindi transcription and the dubbed audio from the GPT-4o response. Previously, this would have been a multistep process, involving several API calls to first transcribe, then translate, and finally produce the audio in the target language. With GPT-4o, we can now accomplish this in a single API call.
        The transcribed text is a combination of Hindi and English, represented in their respective scripts: Devanagari for Hindi and Latin for English. This approach ensures more natural-sounding speech with the correct pronunciation of both languages&#39; words. We will use the pydub module to play the audio as demonstrated in the code below.
        Step 3. Obtain Translation Benchmarks (e.g., BLEU or ROUGE)
        We can assess the quality of the translated text by comparing it to a reference translation using evaluation metrics like BLEU and ROUGE.
        BLEU (Bilingual Evaluation Understudy): Measures the overlap of n-grams between the candidate and reference translations. Scores range from 0 to 100, with higher scores indicating better quality.
        ROUGE (Recall-Oriented Understudy for Gisting Evaluation): Commonly used for summarization evaluation. Measures the overlap of n-grams and the longest common subsequence between the candidate and reference texts.
        Ideally, a reference translation (a human-translated version) of the original text is needed for an accurate evaluation. However, developing such evaluations can be challenging, as it requires time and effort from bilingual humans proficient in both languages.
        An alternative is to transcribe the output audio file from the target language back into the original language to assess the quality of the translation using GPT-4o.
        With the text transcribed back into English language script from the Hindi audio, we can run the evaluation metrics by comparing it to the original English transcription.
        Step 4. Interpret and improve scores by adjusting prompting parameters in steps 1-3 as needed
        In this example, both BLEU and ROUGE scores indicate that the quality of the voice translation is between very good and excellent.
        Interpreting BLEU Scores: While there is no universally accepted scale, some interpretations suggest:
        0 to 10: Poor quality translation; significant errors and lack of fluency.
        10 to 20: Low quality; understandable in parts but contains many errors.
        20 to 30: Fair quality; conveys the general meaning but lacks precision and fluency.
        30 to 40: Good quality; understandable and relatively accurate with minor errors.
        40 to 50: Very good quality; accurate and fluent with very few errors.
        50 and above: Excellent quality; closely resembles human translation.
        Interpreting ROUGE scores: The interpretation of a &quot;good&quot; ROUGE score can vary depending on the task, dataset, and domain. The following guidelines indicate a good outcome:
        ROUGE-1 (unigram overlap): Scores between 0.5 to 0.6 are generally considered good for abstractive summarization tasks.
        ROUGE-L (Longest Common Subsequence): Scores around 0.4 to 0.5 are often regarded as good, reflecting the model&#39;s ability to capture the structure of the reference text.
        If the score for your translation is unsatisfactory, consider the following questions:
        1. Is the source audio accurately transcribed?
        If the transcription contains errors, such as confusing similar-sounding words, you can provide a glossary of such terms in the system prompt during step 1. This helps the model avoid misinterpretations and ensures accurate transcription of specific terms.
        2. Is the source audio free of grammatical errors?
        If the source audio contains grammatical errors, consider using a post-processing step with the GPT model to refine the transcription by removing grammatical mistakes and adding appropriate punctuation. After this, instead of using GPT-4o’s audio-in and audio-out modality, you can use the corrected transcription with GPT-4o’s text-in and audio-out modality to generate the audio in the target language.
        3. Are there words that make sense to keep in the original language?
        Certain terms or concepts may not have a suitable translation in the target language or may be better understood in their original form. Revisit your glossary_of_terms_to_keep_in_original_language and include any such terms to maintain clarity and context.
        Conclusion
        In summary, this cookbook offers a clear, step-by-step process for translating and dubbing audio, making content more accessible to a global audience. Using GPT-4o’s audio input and output capabilities, translating and dubbing audio files from one language to another becomes much simpler. Our example focused on translating an audio file from English to Hindi.
        The process can be broken down into the following steps:
        1. Transcription: Obtain transcription of the source language audio into source language script using GPT-4o text modality.
        2. Dub: Directly dub the audio file into the target language using GPT-4o&#39;s audio modality.
        3. Benchmark Translation Quality: Evaluate the translation’s accuracy using BLEU or ROUGE scores compared to reference text.
        4. Optimize the Process: If needed, adjust the prompting parameters to improve the transcription and dubbing results.
        This guide also highlights the crucial distinction between &quot;language&quot; and &quot;script&quot;—terms that are often confused but are essential in translation work. Language refers to the system of communication, either spoken or written, while script is the set of characters used to write a language. Grasping this difference is vital for effective translation and dubbing.
        By following the techniques in this cookbook, you can translate and dub a wide range of content—from podcasts and training videos to full-length films—into multiple languages. This method applies across industries such as entertainment, education, business, and global communication, empowering creators to extend their reach to diverse linguistic audiences.
      </description>
      <link>https://cookbook.openai.com/examples/voice_solutions/voice_translation_into_different_languages_using_gpt-4o</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/voice_solutions/voice_translation_into_different_languages_using_gpt-4o</guid>
      <pubDate>Sun, 20 Oct 2024 16:00:00 GMT</pubDate>
      <category>Audio</category>
      <category>Completions</category>
    </item>
    <item>
      <title>Leveraging model distillation to fine-tune a model</title>
      <description>OpenAI recently released Distillation which allows to leverage the outputs of a (large) model to fine-tune another (smaller) model. This can significantly reduce the price and the latency for specific tasks as you move to a smaller model. In this cookbook we&#39;ll look at a dataset, distill the output of gpt-4o to gpt-4o-mini and show how we can get significantly better results than on a generic, non-distilled, 4o-mini.
        We&#39;ll also leverage Structured Outputs for a classification problem using a list of enum. We&#39;ll see how fine-tuned model can benefit from structured output and how it will impact the performance. We&#39;ll show that Structured Ouputs work with all of those models, including the distilled one.
        We&#39;ll first analyze the dataset, get the output of both 4o and 4o mini, highlighting the difference in performance of both models, then proceed to the distillation and analyze the performance of this distilled model.
        Prerequisites
        Let&#39;s install and load dependencies.
        Make sure your OpenAI API key is defined in your environment as &quot;OPENAI_API_KEY&quot; and it&#39;ll be loaded by the client directly.
        Loading and understanding the dataset
        For this cookbook, we&#39;ll load the data from the following Kaggle challenge: https://www.kaggle.com/datasets/zynicide/wine-reviews.
        This dataset has a large number of rows and you&#39;re free to run this cookbook on the whole data, but as a biaised french wine-lover, I&#39;ll narrow down the dataset to only French wine to focus on less rows and grape varieties.
        We&#39;re looking at a classification problem where we&#39;d like to guess the grape variety based on all other criterias available, including description, subregion and province that we&#39;ll include in the prompt. It gives a lot of information to the model, you&#39;re free to also remove some information that can help significantly the model such as the region in which it was produced to see if it does a good job at finding the grape.
        Let&#39;s filter the grape varieties that have less than 5 occurences in reviews.
        Let&#39;s proceed with a subset of 500 random rows from this dataset.
        Let&#39;s retrieve all grape varieties to include them in the prompt and in our structured outputs enum list.
        Generating the prompt
        Let&#39;s build out a function to generate our prompt and try it for the first wine of our list.
        To get a understanding of the cost before running the queries, you can leverage tiktoken to understand the number of tokens we&#39;ll send and the cost associated to run this. This will only give you an estimate for to run the completions, not the fine-tuning process (used later in this cookbook when running the distillation), which depends on other factors such as the number of epochs, training set etc.
        Preparing functions to Store Completions
        As we&#39;re looking at a limited list of response (enumerate list of grape varieties), let&#39;s leverage structured outputs so we make sure the model will answer from this list. This also allows us to compare the model&#39;s answer directly with the grape variety and have a deterministic answer (compared to a model that could answer &quot;I think the grape is Pinot Noir&quot; instead of just &quot;Pinot noir&quot;), on top of improving the performance to avoid grape varieties not in our dataset.
        If you want to know more on Structured Outputs you can read this cookbook and this documentation guide.
        To distill a model, you need to store all completions from a model, allowing you to give it as a reference to the smaller model to fine-tune it. We&#39;re therefore adding a store=True parameter to our client.chat.completions.create method so we can store those completions from gpt-4o.
        We&#39;re going to store all completions (even 4o-mini and our future fine-tuned model) so we are able to run Evals from OpenAI platform directly.
        When storing those completions, it&#39;s useful to store them with a metadata tag, that will allow filtering from the OpenAI platform to run distillation &amp;amp; evals on the specific set of completions you&#39;d like to run those.
        Parallel processing
        As we&#39;ll run this on a large number of rows, let&#39;s make sure we run those completions in parallel and use concurrent futures for this. We&#39;ll iterate on our dataframe and output progress every 20 rows. We&#39;ll store the completion from the model we run the completion for in the same dataframe using the column name {model}-variety.
        Let&#39;s try out our call model function before processing the whole dataframe and check the output.
        Great! We confirmed we can get a grape variety as an output, let&#39;s now process the dataset with both gpt-4o and gpt-4o-mini and compare the results.
        Comparing gpt-4o and gpt-4o-mini
        Now that we&#39;ve got all chat completions for those two models ; let&#39;s compare them against the expected grape variety and assess their accuracy at finding it. We&#39;ll do this directly in python here as we&#39;ve got a simple string check to run, but if your task involves more complex evals you can leverage OpenAI Evals or our open-source eval framework.
        We can see that gpt-4o is better a finding grape variety than 4o-mini (12.80% higher or almost 20% relatively to 4o-mini!). Now I&#39;m wondering if we&#39;re making gpt-4o drink wine during training!
        Distilling gpt-4o outputs to gpt-4o-mini
        Let&#39;s assume we&#39;d like to run this prediction often, we want completions to be faster and cheaper, but keep that level of accuracy. That&#39;d be great to be able to distill 4o accuracy to 4o-mini, wouldn&#39;t it? Let&#39;s do it!
        We&#39;ll now go to OpenAI Stored completions page: https://platform.openai.com/chat-completions.
        Let&#39;s select the model gpt-4o (make sure to do this, you don&#39;t want to distill the outputs of 4o-mini that we ran). Let&#39;s also select the metadata distillation: wine-distillation to get only stored completions ran from this cookbook.
        Once you&#39;ve selected completions, you can click on &quot;Distill&quot; on the top right corner to fine-tune a model based on those completions. Once we&#39;ve done that, a file to run the fine-tuning process will automatically be created. Let&#39;s then select gpt-4o-mini as the base model, keep the default parameters (but you&#39;re free to change them or iterate with it to improve performance).
        Once the fine-tuning job is starting, you can retrieve the fine tuning job ID from the fine-tuning page, we&#39;ll use it to monitor status of the fine-tuned job as well as retrieving the fine-tuned model id once done.
        Running completions for the distilled model
        Now that we&#39;ve got our model fine-tuned, we can use this model to run completions and compare accuracy with both gpt4o and gpt4o-mini.
        Let&#39;s grab a different subset of french wines (as we restricted the outputs to french grape varieties, without outliers, we&#39;ll need to focus our validation dataset to this too). Let&#39;s run this on 300 entries for each models.
        Let&#39;s compare accuracy of models
        That&#39;s almost a 22% relative improvement over the non-distilled gpt-4o-mini! 🎉
        Our fine-tuned model performs way better than gpt-4o-mini, while having the same base model. We&#39;ll be able to use this model to run inferences at a lower cost and lower latency for future grape variety prediction.
      </description>
      <link>https://cookbook.openai.com/examples/leveraging_model_distillation_to_fine-tune_a_model</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/leveraging_model_distillation_to_fine-tune_a_model</guid>
      <pubDate>Tue, 15 Oct 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Fine-tuning</category>
    </item>
    <item>
      <title>Custom LLM as a Judge to Detect Hallucinations with Braintrust</title>
      <description>Let&#39;s say you&#39;re working on a customer service bot and trying to evaluate the quality of its responses. Consider a question like &quot;What is your return policy?&quot; If the correct answer is &quot;You can return items within 30 days of purchase,&quot; but your bot generates &quot;You can return items within 30 days,&quot; how would you evaluate whether this is a good response?
        A heuristic like the Levenshtein string distance would indicate that the response is incorrect. However, a better approach is to use an LLM-as-a-judge to assess the accuracy of the response. LLM-as-a-judge is a technique that leverages an LLM to score the quality of answers. LLMs can reason about language beyond surface-level string comparisons, enabling them to evaluate answers more accurately.
        In this cookbook, we&#39;ll walk through how to build an LLM-as-a-judge scorer that can detect hallucinations using Braintrust, a third-party evaluation platform that is compatible with OpenAI&#39;s models.
        Installing dependencies
        Let&#39;s install a few basic dependencies. We&#39;ll use the CoQA dataset (via DuckDB), Braintrust for evals, and OpenAI&#39;s models. Please note that Braintrust is a third-party evaluation platform and you should review their terms of service and privacy policy before proceeding.
        Next, let&#39;s initialize the OpenAI client. We&#39;ll use the AsyncOpenAI client so that we can parallelize our requests. The braintrust.wrap_openai function
        wraps the OpenAI client to enable logging LLM calls to Braintrust. We&#39;ll use Braintrust to facilitate the evaluations below.
        Before proceeding, you should sign up for a Braintrust account and set BRAINTRUST_API_KEY in your environment to a valid API key.
        Explore the dataset
        We&#39;ll use the CoQA dataset which contains a diverse set of passages, questions, and answers. Because CoQA is quite large, we&#39;ll just look at the first several passages. As with any public dataset, there&#39;s a chance that the underlying LLMs have memorized aspects of the dataset, so when developing your own scorers, it&#39;s a good idea to test them using
        your own private data.
        The data contains a series of passages, each with a number of questions and answers. Let&#39;s flatten this into a list of (passage, question, answer) tuples.
        Adding hallucinations
        Because Braintrust&#39;s scorer is designed to test hallucinations, we can use the QA pairs to generate known hallucinations. We&#39;ll create hallucinated answers by asking an
        LLM to confidently generate an answer to each question without using the passage.
        Creating the evaluators
        We&#39;ll consider a few popular approaches for creating an LLM-as-a-judge. For each approach, we&#39;ll create a scorer and then &quot;meta-evaluate&quot; it to see how it performs.
        Since we know that the hallucinated answers are incorrect, we&#39;ll assess the quality of an evaluator by testing how often it scores the hallucinated answers as 0.
        LLM-as-a-judge #1: Numeric rater
        A common initial intuition when creating an LLM-as-a-judge is asking the LLM to rate the answer on a scale of 1 to 5. The benefit of this approach is that
        it&#39;s easy to convert the LLM&#39;s output into a numeric score.
        We&#39;ll use a modified version of the Factuality template, but ask the LLM to
        rate the answer on a scale of 1 to 10.
        This looks promising! Now that we have sanity checked it on a single example, let&#39;s run a proper evaluation and see how it performs on a wider set of data. An evaluation consists of three components:
        Data: In this case, the input is the question, hallucinated answer, and ground truth answer. The scorer will convert this into a score between 0 and 1. The expected score is 0, since it&#39;s a hallucination.
        Task: The task is simply calling the numeric rater for each input.
        Scores: We&#39;ll assess the quality of the generated score by comparing it with the ground truth score. Since we know both numbers are between 0 and 1, we can use the normalized difference as the score.
        It looks like the numeric rater scored almost 94% in total. That&#39;s not bad, but if 6% of your evals are incorrectly judged, that could make it very hard to trust them. Let&#39;s dig into the Braintrust
        UI to get some insight into what&#39;s going on.
        It looks like a number of the incorrect answers were scored with numbers between 1 and 10. However, we do not currently have any insight into why the model gave these scores. Let&#39;s see if we can
        fix that next.
        LLM-as-a-judge #2: Adding reasoning
        Let&#39;s tweak the prompt to get the LLM to also reason about its rating. This method is called Chain of Thought Reasoning. In addition
        to potentially improving the score, it will give us some insight into why the model gave these scores.
        It doesn&#39;t look like adding reasoning helped the score (in fact, it&#39;s half a percent worse). However, if we look at one of the failures, we&#39;ll get some insight into
        what the model was thinking. Here is an example of a hallucinated answer:
        And the score along with its reasoning:
        It looks like the model is applying its own judgement to compute partial credit. This is a common problem with numeric rating—both for models and for humans—and can often be solved
        by using better prompting.
        LLM-as-a-judge #3: Classifying instead of rating
        Next, we&#39;ll spell out specific criteria and ask the model to classify the answer according to those criteria. This method allows us to more precisely guide the model
        towards the hallucinations we&#39;re testing for. Intuitively, giving the model specific criteria to rate will result in a more accurate score.
        The classifier scored 98.5% which is a significant improvement!
        Codifying this pattern
        The classifier above can simply be rewritten as:
        PROMPT = &quot;&quot;&quot;\
        You are comparing a submitted answer to an expert answer on a given question. Here is the data:
        [BEGIN DATA]
        ************
        [Question]: {{input}}
        ************
        [Expert]: {{expected}}
        ************
        [Submission]: {{output}}
        ************
        [END DATA]
        Compare the factual content of the submitted answer with the expert answer. Ignore any differences in style, grammar, or punctuation.
        The submitted answer may either be a subset or superset of the expert answer, or it may conflict with it. Determine which case applies. Answer the question by selecting one of the following options:
        (A) The submitted answer is a subset of the expert answer and is fully consistent with it.
        (B) The submitted answer is a superset of the expert answer and is fully consistent with it.
        (C) The submitted answer contains all the same details as the expert answer.
        (D) There is a disagreement between the submitted answer and the expert answer.
        (E) The answers differ, but these differences don&#39;t matter from the perspective of factuality.
        Answer the question by calling `select_choice` with your reasoning in a step-by-step matter to be
        sure that your conclusion is correct. Avoid simply stating the correct answer at the outset. Select a
        single choice by setting the `choice` parameter to a single choice from A, B, C, D, or E.
        &quot;&quot;&quot;
        Classifier = autoevals.LLMClassifier(
        name=&quot;Hallucination detector&quot;,
        prompt_template=PROMPT,
        choice_scores={&quot;A&quot;: 0.5, &quot;B&quot;: 0, &quot;C&quot;: 1, &quot;D&quot;: 0, &quot;E&quot;: 1},
        use_cot=True,
        )
        Next steps
        As a next step, you could dig into the individual improvements and regressions to assess them and consider future improvements to the prompt. You could also test it on your own data, and double check that the results hold for your use case.
        You could also measure a model like o1, try fine-tuning a smaller model and see if the results are reproducible, or use few-shot prompting to align the model with more subjective criteria.
        In all cases, you should strive to evaluate your results, so you can rigorously assess the impact of each change.
      </description>
      <link>https://cookbook.openai.com/examples/custom-llm-as-a-judge</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/custom-llm-as-a-judge</guid>
      <pubDate>Sun, 13 Oct 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category></category>
    </item>
    <item>
      <title>Orchestrating Agents: Routines and Handoffs</title>
      <description>When working with language models, quite often all you need for solid performance is a good prompt and the right tools. However, when dealing with many unique flows, things may get hairy. This cookbook will walk through one way to tackle this.
        We&#39;ll introduce the notion of routines and handoffs, then walk through the implementation and show how they can be used to orchestrate multiple agents in a simple, powerful, and controllable way.
        Finally, we provide a sample repo, Swarm, that implements these ideas along with examples.
        Let&#39;s start by setting up our imports.
        Routines
        The notion of a &quot;routine&quot; is not strictly defined, and instead meant to capture the idea of a set of steps. Concretely, let&#39;s define a routine to be a list of instructions in natural langauge (which we&#39;ll represent with a system prompt), along with the tools necessary to complete them.
        Let&#39;s take a look at an example. Below, we&#39;ve defined a routine for a customer service agent instructing it to triage the user issue, then either suggest a fix or provide a refund. We&#39;ve also defined the necessary functions execute_refund and look_up_item. We can call this a customer service routine, agent, assistant, etc –&amp;nbsp;however the idea itself is the same: a set of steps and the tools to execute them.
        The main power of routines is their simplicity and robustness. Notice that these instructions contain conditionals much like a state machine or branching in code. LLMs can actually handle these cases quite robustly for small and medium sized routine, with the added benefit of having &quot;soft&quot; adherance –&amp;nbsp;the LLM can naturally steer the conversation without getting stuck in dead-ends.
        Executing Routines
        To execute a routine, let&#39;s implement a simple loop that:
        Gets user input.
        Appends user message to messages.
        Calls the model.
        Appends model response to messages.
        As you can see, this currently ignores function calls, so let&#39;s add that.
        Models require functions to be formatted as a function schema. For convenience, we can define a helper function that turns python functions into the corresponding function schema.
        For example:
        Now, we can use this function to pass the tools to the model when we call it.
        Finally, when the model calls a tool we need to execute the corresponding function and provide the result back to the model.
        We can do this by mapping the name of the tool to the python function in a tool_map, then looking it up in execute_tool_call and calling it. Finally we add the result to the conversation.
        In practice, we&#39;ll also want to let the model use the result to produce another response. That response might also contain a tool call, so we can just run this in a loop until there are no more tool calls.
        If we put everything together, it will look something like this:
        Now that we have a routine, let&#39;s say we want to add more steps and more tools. We can up to a point, but eventually if we try growing the routine with too many different tasks it may start to struggle. This is where we can leverage the notion of multiple routines – given a user request, we can load the right routine with the appropriate steps and tools to address it.
        Dynamically swapping system instructions and tools may seem daunting. However, if we view &quot;routines&quot; as &quot;agents&quot;, then this notion of handoffs allow us to represent these swaps simply –&amp;nbsp;as one agent handing off a conversation to another.
        Handoffs
        Let&#39;s define a handoff as an agent (or routine) handing off an active conversation to another agent, much like when you get transfered to someone else on a phone call. Except in this case, the agents have complete knowledge of your prior conversation!
        To see handoffs in action, let&#39;s start by defining a basic class for an Agent.
        Now to make our code support it, we can change run_full_turn to take an Agent instead of separate system_message and tools:
        We can now run multiple agents easily:
        Great! But we did the handoff manually here –&amp;nbsp;we want the agents themselves to decide when to perform a handoff. A simple, but surprisingly effective way to do this is by giving them a transfer_to_XXX function, where XXX is some agent. The model is smart enough to know to call this function when it makes sense to make a handoff!
        Handoff Functions
        Now that agent can express the intent to make a handoff, we must make it actually happen. There&#39;s many ways to do this, but there&#39;s one particularly clean way.
        For the agent functions we&#39;ve defined so far, like execute_refund or place_order they return a string, which will be provided to the model. What if instead, we return an Agent object to indate which agent we want to transfer to? Like so:
        We can then update our code to check the return type of a function response, and if it&#39;s an Agent, update the agent in use! Additionally, now run_full_turn will need to return the latest agent in use in case there are handoffs. (We can do this in a Response class to keep things neat.)
        Now for the updated run_full_turn:
        Let&#39;s look at an example with more Agents.
        Finally, we can run this in a loop (this won&#39;t run in python notebooks, so you can try this in a separate python file):
        Swarm
        As a proof of concept, we&#39;ve packaged these ideas into a sample library called Swarm. It is meant as an example only, and should not be directly used in production. However, feel free to take the ideas and code to build your own!
      </description>
      <link>https://cookbook.openai.com/examples/orchestrating_agents</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/orchestrating_agents</guid>
      <pubDate>Wed, 09 Oct 2024 16:00:00 GMT</pubDate>
      <category></category>
      <category>Completions</category>
      <category>Functions</category>
    </item>
    <item>
      <title>Vision Fine-tuning on GPT-4o for Visual Question Answering on Medical Images</title>
      <description>We&#39;re excited to announce the launch of Vision Fine-Tuning on GPT-4o, a cutting-edge multimodal fine-tuning capability that empowers developers to fine-tune GPT-4o using both images and text. With this new feature, you can customize models to have stronger image understanding capabilities, unlocking possibilities across various industries and applications.
        From advanced visual search to improved object detection for autonomous vehicles or smart cities, and even precision in medical image analysis, vision fine-tuning enables you to craft solutions tailored to your specific needs. By combining text and image inputs, this product is uniquely positioned for tasks like visual question answering, where detailed, context-aware answers are derived from analyzing images. In general, this seems to be most effective when the model is presented with questions and images that resemble the training data as we are able to teach the model how to search and identify relevant parts of the image to answer the question correctly. Similarly to fine-tuning on text inputs, vision fine-tuning is not as useful for teaching the model new information.
        In this guide, we’ll walk you through the steps to fine-tune GPT-4o with multimodal inputs. Specifically, we’ll demonstrate how to train a model for answering questions related to medical radiology images, but the potential applications span countless domains—from web design and education to healthcare and research.
        Whether you&#39;re looking to build smarter defect detection models for manufacturing, enhance complex document processing and diagram understanding, or develop applications with better visual comprehension for a variety of other use cases, this guide will show you just how fast and easy it is to get started.
        For more information, check out the full Documentation.
        Load Dataset
        We will work with a dataset of question-answer pairs on radiology images from the VQA-RAD dataset, accessible through HuggingFace. This dataset is specifically designed for Medical Visual Question Answering (VQA) systems, allowing us to fine-tune models for real-world medical applications.
        Curated by a team of clinicians, the dataset consists of manually generated samples, offering both open-ended questions and binary &quot;yes/no&quot; questions about radiology images. These carefully crafted questions help train and evaluate models on their ability to interpret and analyze medical imagery, a critical task in healthcare and diagnostics.
        Let&#39;s inspect the first sample from the training set.
        In this example, the question prompts the model to analyze a brain scan and determine whether any regions of the brain show signs of infarction. A brain infarction occurs when brain tissue is damaged or dies due to a lack of blood flow, which can lead to stroke or other serious conditions.
        This type of task is typical in medical visual question answering, where the model must interpret complex medical images and provide accurate, context-specific responses. By training on these kinds of questions, we can enhance the model&#39;s ability to perform detailed image analysis in critical fields like radiology.
        Data Preparation
        To ensure successful fine-tuning of our model, it’s crucial to properly structure the training data. Correctly formatting the data helps avoid validation errors during training and ensures the model can effectively learn from both text and image inputs. The good news is, this process is quite straightforward.
        Each example in the training dataset should be a conversation in the same format as the Chat Completions API. Specifically, this means structuring the data as a series of messages, where each message includes a role (such as &quot;user&quot; or &quot;assistant&quot;) and the content of the message.
        Since we are working with both text and images for vision fine-tuning, we’ll construct these messages to include both content types. For each training sample, the question about the image is presented as a user message, and the corresponding answer is provided as an assistant message.
        Images can be included in one of two ways:
        As HTTP URLs, referencing the location of the image.
        As data URLs containing the image encoded in base64.
        Here’s an example of how the message format should look:
        Let&#39;s start by defining the system instructions for our model. These instructions provide the model with important context, guiding how it should behave when processing the training data. Clear and concise system instructions are particularly useful to make sure the model reasons well on both text and images.
        To ensure our images are properly formatted for vision fine-tuning, they must be in base64 format and either RGB or RGBA. This ensures the model can accurately process the images during training. Below is a function that handles the encoding of images, while also converting them to the correct format if necessary.
        We will also include Few-Shot examples from the training set as user and assistant messages to help guide the model&#39;s reasoning process.
        Now that we have our system instructions, few-shot examples, and the image encoding function in place, the next step is to iterate through the training set and construct the messages required for fine-tuning. As a reminder, each training example must be formatted as a conversation and must include both the image (in base64 format) and the corresponding question and answer.
        To fine-tune GPT-4o, we recommend providing at least 10 examples, but you’ll typically see noticeable improvements with 50 to 100 training examples. In this case, we&#39;ll go all-in and fine-tune the model using the full VQA-RAD dataset, which consists of 1,793 samples.
        We save our final training set in a .jsonl file where each line in the file represents a single example in the training dataset.
        Just like the training set, we need to structure our test set in the same message format. However, there&#39;s a key difference: since the test set is used for evaluation, we do not include the assistant&#39;s message (i.e., the answer). This ensures the model generates its own answers, which we can later compare to the ground truth for performance evaluation.
        Fine-tuning
        Now that we have prepared our training dataset in the right format, we can upload our training file using the Files API for fine-tuning.
        Once the file is uploaded, we&#39;re ready to proceed to the next step: starting the fine-tuning job.
        To create a fine-tuning job, we use the fine-tuning API. You can track the progress of the fine-tuning job in the Platform UI.
        Evaluation
        Once the fine-tuning job is complete, it’s time to evaluate the performance of our model by running inference on the test set. This step involves using the fine-tuned model to generate responses to the questions in the test set and comparing its predictions to the ground truth answers for evaluation.
        Now that we’ve run inference using our fine-tuned model, let’s inspect a few specific examples to understand how well the model performed compared to the actual answers.
        As we’ve seen, while many of the model’s predicted answers are close to the ground truth, they don’t always match exactly, particularly in open-ended questions where phrasing or details may differ. To assess the quality of these predictions, we will use GPT-4o to evaluate the similarity between the predicted responses and the ground truth labels from the dataset.
        In order to evaluate our model responses, we will use GPT-4o to determine the similarity between the ground truth and our predicted responses. We will rank our predicted answers based on the following criteria:
        Very Similar: The predicted answer exactly matches the ground truth and there is no important information omitted, although wording and phrasing of the answer may differ.
        Mostly Similar: The predicted answer closely aligns with the ground truth in terms of medical diagnosis and recommendations, with some minor discrepancies.
        Somewhat Similar: Although the predicted answer has noticeable differences to the ground truth, the core content is accurate, perhaps with some missing information.
        Incorrect: The predicted answer is completely incorrect, irrelevant, or contains critical errors or omissions from the ground truth.
        To fully understand the impact of fine-tuning, we also evaluated the same set of test questions using the non-fine-tuned GPT-4o model. While the code for this process is not shown here for brevity, it is identical to the evaluation method shown earlier (with the exception of switching the model parameter).
        Let&#39;s start by comparing the performance of the fine-tuned model vs the non-fine-tuned model for Closed form (Yes/No) questions.
        Note that with the fine-tuned model, we can check for exact matches between the predicted and actual answers because the model has learned to produce consistent answers. However, for the non-fine-tuned model, we need to account for variations in phrasing and wording in the predicted answers.
        With a generous allowance for variations in phrasing and wording for the non-fine-tuned model including ignoring case and allowing for partial matches, the fine-tuned model still outperforms the non-fine-tuned model by a margin of 6.38% on this set of questions.
        Now, let&#39;s compare the performance of the fine-tuned model vs the non-fine-tuned model over all questions.
        The results provide a clear picture of the benefits gained through fine-tuning, without any other modifications.
        Comparing the distribution of ratings between the fine-tuned GPT-4o model and GPT-4o without fine-tuning, we see that the fine-tuned model gets more responses exactly correct, as well as getting more responses correct overall.
        Key Takeaways
        Improved Precision: Fine-tuning helped the model produce more precise answers that matched the ground truth, especially in highly domain-specific tasks like radiology image analysis.
        Better Generalization: While the non-fine-tuned GPT-4o performed well on some questions, it was less consistent. The fine-tuned model exhibited better generalization across a variety of test questions, thanks to the exposure to multimodal medical data during training.
        While the results from vision fine-tuning are promising, there are still several incorrect responses that highlight opportunities for improvement. Much like fine-tuning on text, the effectiveness of vision fine-tuning depends heavily on the quality, diversity, and representativeness of the training data. In particular, models benefit from focusing on cases where errors occur most frequently, allowing for targeted improvements.
        Upon reviewing the incorrect results, a recurring issue is the model&#39;s difficulty in accurately identifying locations or specific structures based on radiology images. This suggests that the model might require more diverse training examples, especially for location-based tasks, or clearer, expert-informed instructions to guide the model’s understanding.
        Next Steps:
        Expand the Training Dataset: Adding more varied examples that cover the model’s weaker areas, such as location identification in medical images, could significantly enhance performance.
        Expert-Informed Prompts: Incorporating domain-specific instructions from experts into the training prompts may further refine the model’s ability to accurately interpret and respond to complex medical queries.
        Although there is still progress to be made on this particular task, the initial results are encouraging. With minimal setup and effort, we’ve already observed an uplift in overall accuracy with vision fine-tuning, indicating that this approach holds great potential. Vision fine-tuning opens up possibilities for improvement across a wide range of visual question answering tasks, as well as other tasks that rely on strong visual understanding.
      </description>
      <link>https://cookbook.openai.com/examples/multimodal/vision_fine_tuning_on_gpt4o_for_visual_question_answering_on_medical_images</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/multimodal/vision_fine_tuning_on_gpt4o_for_visual_question_answering_on_medical_images</guid>
      <pubDate>Tue, 01 Oct 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Fine-tuning</category>
      <category>Vision</category>
    </item>
    <item>
      <title>Prompt Caching 101</title>
      <description>OpenAI offers discounted prompt caching for prompts exceeding 1024 tokens, resulting in up to an 80% reduction in latency for longer prompts over 10,000 tokens. By caching repetitive information across LLM API requests, you can greatly reduce both latency and costs. Prompt caching is scoped at the organization level, meaning only members of the same organization can access shared caches. Additionally, caching is eligible for zero data retention, as no data is stored during the process.
        Prompt caching automatically activates for prompts longer than 1024 tokens-- you don&#39;t have to change anything in your completions request. When an API request is made, the system first checks if the beginning portion (prefix) of the prompt has already been cached. If a match is found (cache hit), the cached prompt is used, leading to reduced latency and costs. If there&#39;s no match, the system processes the full prompt from scratch and caches the prefix for future use.
        With these benefits in mind, some of the key use cases where prompt caching can be especially advantageous are:
        Agents using tools and structured outputs: Cache the extended list of tools and schemas.
        Coding and writing assistants: Insert large sections or summaries of codebases and workspaces directly in prompts.
        Chatbots: Cache static portions of multi-turn conversations to maintai

github-actions[bot] avatar Oct 30 '24 02:10 github-actions[bot]

Successfully generated as following:

http://localhost:1200/openai/cookbook - Success ✔️
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <title>OpenAI Cookbook</title>
    <link>https://cookbook.openai.com/</link>
    <atom:link href="http://localhost:1200/openai/cookbook" rel="self" type="application/rss+xml"></atom:link>
    <description>OpenAI Cookbook - Powered by RSSHub</description>
    <generator>RSSHub</generator>
    <webMaster>[email protected] (RSSHub)</webMaster>
    <language>en</language>
    <lastBuildDate>Wed, 30 Oct 2024 04:03:45 GMT</lastBuildDate>
    <ttl>5</ttl>
    <item>
      <title>Enhance your prompts with meta prompting</title>
      <description>&lt;p&gt;Welcome to our cookbook on meta prompting! In this guide, we&#39;ll explore how to take a basic prompt and refine it to enhance the quality of outputs from a language model. We&#39;ll use the example of summarizing news reports to illustrate the process.&lt;/p&gt;
        &lt;p&gt;Meta-prompting is a technique where you use an LLM to generate or improve prompts. Typically this is done using a higher intelligence model that optimizes prompts for a model with less intelligence. It’s a process of using prompts to guide, structure, and optimize other prompts, helping ensure they’re more effective in guiding the LLM towards high-quality, relevant outputs. We&#39;ll be leveraging the capabilities of &lt;code&gt;o1-preview&lt;/code&gt;, a more intelligent model with advanced reasoning skills, to improve a prompt for &lt;code&gt;gpt-4o&lt;/code&gt;.&lt;/p&gt;
        &lt;p&gt;We&#39;re committed to making your development journey with LLMs smoother and more accessible through this technique. Don&#39;t forget to check out our &lt;a href=&quot;https://platform.openai.com/docs/guides/prompt-generation&quot;&gt;Generate Anything&lt;/a&gt; feature in the playground — it&#39;s a fantastic starting point to dive into meta prompting.&lt;/p&gt;
        &lt;p&gt;In this example, we&#39;ll begin with a simple prompt for summarizing news articles and then enhance it to see how the outputs improve. We&#39;ll use &lt;code&gt;o1-preview&lt;/code&gt; to analyze and refine our prompt, adding more detail and clarity along the way. Finally, we&#39;ll evaluate the outputs systematically to understand the impact of our refinements.&lt;/p&gt;</description>
      <link>https://cookbook.openai.com/examples/enhance_your_prompts_with_meta_prompting</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/enhance_your_prompts_with_meta_prompting</guid>
      <pubDate>Tue, 22 Oct 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Reasoning</category>
    </item>
    <item>
      <title>GPT Actions library - GitHub</title>
      <description>&lt;h2 id=&quot;introduction&quot;&gt;&lt;a class=&quot;heading-link&quot; href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_github#introduction&quot;&gt;Introduction&lt;/a&gt;&lt;/h2&gt;
        &lt;p&gt;This page provides instructions for developers connecting a GPT Action to GitHub. Before proceeding, familiarize yourself with the following resources:&lt;/p&gt;
        &lt;ul&gt;
        &lt;li&gt;&lt;a href=&quot;https://platform.openai.com/docs/actions&quot;&gt;Introduction to GPT Actions&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;https://platform.openai.com/docs/actions/actions-library&quot;&gt;GPT Actions Library&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;https://platform.openai.com/docs/actions/getting-started&quot;&gt;Building a GPT Action from Scratch&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
        &lt;p&gt;This GPT Action helps developers evaluate the quality and security of a GitHub Pull Request diff. It provides feedback and suggestions for each domain, allowing developers to modify or accept the feedback before automatically submitting it as a comment on the Pull Request.&lt;/p&gt;
        &lt;h2 id=&quot;value--example-business-use-cases&quot;&gt;&lt;a class=&quot;heading-link&quot; href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_github#value--example-business-use-cases&quot;&gt;Value &amp;amp; Example Business Use Cases&lt;/a&gt;&lt;/h2&gt;
        &lt;h3 id=&quot;value&quot;&gt;&lt;a class=&quot;heading-link&quot; href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_github#value&quot;&gt;&lt;strong&gt;Value&lt;/strong&gt;:&lt;/a&gt;&lt;/h3&gt;
        &lt;p&gt;Users can leverage ChatGPT&#39;s natural language capabilities to assist with GitHub Pull Request reviews.&lt;/p&gt;
        &lt;ul&gt;
        &lt;li&gt;&lt;strong&gt;For developers&lt;/strong&gt;: Analyze code changes and perform high-quality reviews with instant feedback on proposed modifications.&lt;/li&gt;
        &lt;li&gt;&lt;strong&gt;For organizations&lt;/strong&gt;: Ensure diffs adhere to best practices and coding standards, or automatically propose refactored alternatives (additional API requests may be required to define best practices).&lt;/li&gt;
        &lt;li&gt;&lt;strong&gt;Overall&lt;/strong&gt;: Boost productivity and ensure higher-quality, more secure code with this AI-powered Code Review assistant.&lt;/li&gt;
        &lt;/ul&gt;
        &lt;h3 id=&quot;example-use-cases&quot;&gt;&lt;a class=&quot;heading-link&quot; href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_github#example-use-cases&quot;&gt;&lt;strong&gt;Example Use Cases&lt;/strong&gt;:&lt;/a&gt;&lt;/h3&gt;
        &lt;ul&gt;
        &lt;li&gt;A reviewer seeks feedback on the quality and security of a proposed code change.&lt;/li&gt;
        &lt;li&gt;An organization encourages adherence to best practices and standards automatically during code review.&lt;/li&gt;
        &lt;/ul&gt;
        &lt;h2 id=&quot;demonstration-video&quot;&gt;&lt;a class=&quot;heading-link&quot; href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_github#demonstration-video&quot;&gt;Demonstration Video:&lt;/a&gt;&lt;/h2&gt;
        &lt;p&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=bcjybCh-x-Q&quot;&gt;&lt;img src=&quot;https://img.youtube.com/vi/bcjybCh-x-Q/0.jpg&quot; alt=&quot;Watch the video&quot; referrerpolicy=&quot;no-referrer&quot;&gt;&lt;/a&gt;&lt;/p&gt;
        &lt;h2 id=&quot;application-information&quot;&gt;&lt;a class=&quot;heading-link&quot; href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_github#application-information&quot;&gt;Application Information&lt;/a&gt;&lt;/h2&gt;
        &lt;h3 id=&quot;key-links&quot;&gt;&lt;a class=&quot;heading-link&quot; href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_github#key-links&quot;&gt;&lt;strong&gt;Key Links&lt;/strong&gt;&lt;/a&gt;&lt;/h3&gt;
        &lt;p&gt;Before starting, explore these resources:&lt;/p&gt;
        &lt;ul&gt;
        &lt;li&gt;&lt;a href=&quot;https://github.com/&quot;&gt;GitHub&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;https://docs.github.com/en/rest/pulls?apiVersion=2022-11-28&quot;&gt;GitHub API Documentation&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
        &lt;h3 id=&quot;prerequisites&quot;&gt;&lt;a class=&quot;heading-link&quot; href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_github#prerequisites&quot;&gt;&lt;strong&gt;Prerequisites&lt;/strong&gt;&lt;/a&gt;&lt;/h3&gt;
        &lt;p&gt;Ensure you have a repository with an open pull request.&lt;/p&gt;
        &lt;h2 id=&quot;application-setup&quot;&gt;&lt;a class=&quot;heading-link&quot; href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_github#application-setup&quot;&gt;Application Setup&lt;/a&gt;&lt;/h2&gt;
        &lt;h3 id=&quot;select-a-pull-request&quot;&gt;&lt;a class=&quot;heading-link&quot; href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_github#select-a-pull-request&quot;&gt;&lt;strong&gt;Select a Pull Request&lt;/strong&gt;&lt;/a&gt;&lt;/h3&gt;
        &lt;ol&gt;
        &lt;li&gt;Navigate to a repository, e.g., &lt;a href=&quot;https://github.com/microsoft/vscode/pull/229241&quot;&gt;example PR&lt;/a&gt;.&lt;!-- --&gt;
        &lt;ul&gt;
        &lt;li&gt;Note the owner (e.g., &quot;microsoft&quot;), repository name (e.g., &quot;vscode&quot;), and PR number (e.g., &quot;229241&quot;).&lt;/li&gt;
        &lt;li&gt;If the repository owner is an SSO organization, your token may need &lt;a href=&quot;https://docs.github.com/en/organizations/managing-programmatic-access-to-your-organization/managing-requests-for-personal-access-tokens-in-your-organization#managing-fine-grained-personal-access-token-requests&quot;&gt;approval&lt;/a&gt;.&lt;/li&gt;
        &lt;/ul&gt;
        &lt;/li&gt;
        &lt;li&gt;Review &lt;a href=&quot;https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/getting-started/best-practices-for-pull-requests&quot;&gt;how to perform a high-quality code review&lt;/a&gt;.&lt;/li&gt;
        &lt;/ol&gt;
        &lt;h3 id=&quot;generate-a-fine-grained-github-personal-access-token&quot;&gt;&lt;a class=&quot;heading-link&quot; href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_github#generate-a-fine-grained-github-personal-access-token&quot;&gt;&lt;strong&gt;Generate a &quot;Fine Grained&quot; GitHub Personal Access Token&lt;/strong&gt;&lt;/a&gt;&lt;/h3&gt;
        &lt;ol&gt;
        &lt;li&gt;Log in to GitHub and go to &lt;strong&gt;Settings&lt;/strong&gt;.&lt;/li&gt;
        &lt;li&gt;Navigate to &lt;strong&gt;Developer settings&lt;/strong&gt; &amp;gt; &lt;strong&gt;Fine Grained Personal access tokens&lt;/strong&gt;.&lt;/li&gt;
        &lt;li&gt;Click &lt;strong&gt;Generate new token&lt;/strong&gt;, name it, set an expiration date, and select the necessary scopes (e.g., &lt;code&gt;read:content&lt;/code&gt;, &lt;code&gt;read&amp;amp;write:pull_requests&lt;/code&gt;).&lt;/li&gt;
        &lt;li&gt;Copy and securely store the token.&lt;/li&gt;
        &lt;/ol&gt;
        &lt;h2 id=&quot;chatgpt-steps&quot;&gt;&lt;a class=&quot;heading-link&quot; href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_github#chatgpt-steps&quot;&gt;ChatGPT Steps&lt;/a&gt;&lt;/h2&gt;
        &lt;h3 id=&quot;custom-gpt-instructions&quot;&gt;&lt;a class=&quot;heading-link&quot; href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_github#custom-gpt-instructions&quot;&gt;&lt;strong&gt;Custom GPT Instructions&lt;/strong&gt;&lt;/a&gt;&lt;/h3&gt;
        &lt;p&gt;Once you&#39;ve created a Custom GPT, copy the following into the Instructions panel:&lt;/p&gt;
        &lt;div data-rehype-pretty-code-fragment=&quot;&quot;&gt;&lt;div class=&quot;relative&quot;&gt;&lt;pre&gt;&lt;code data-language=&quot;&quot; data-theme=&quot;default&quot; style=&quot;display:grid&quot;&gt;&lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#e1e4e8&quot;&gt;# **Context:** You support software developers by providing detailed information about their pull request diff content from repositories hosted on GitHub. You help them understand the quality, security and completeness implications of the pull request by providing concise feedback about the code changes based on known best practices. The developer may elect to post the feedback (possibly with their modifications) back to the Pull Request. Assume the developer is familiar with software development.&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#e1e4e8&quot;&gt;&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#e1e4e8&quot;&gt;# **Instructions:**&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#e1e4e8&quot;&gt;&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#e1e4e8&quot;&gt;## Scenarios&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#e1e4e8&quot;&gt;### - When the user asks for information about a specific pull request, follow this 5 step process:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#e1e4e8&quot;&gt;1. If you don&#39;t already have it, ask the user to specify the pull request owner, repository and pull request number they want assistance with and the particular area of focus (e.g., code performance, security vulnerabilities, and best practices).&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#e1e4e8&quot;&gt;2. Retrieve the Pull Request information from GitHub using the getPullRequestDiff API call, owner, repository and the pull request number provided. &lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#e1e4e8&quot;&gt;3. Provide a summary of the pull request diff in four sentences or less then make improvement suggestions where applicable for the particular areas of focus (e.g., code performance, security vulnerabilities, and best practices).&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#e1e4e8&quot;&gt;4. Ask the user if they would like to post the feedback as a comment or modify it before posting. If the user modifies the feedback, incorporate that feedback and repeat this step. &lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#e1e4e8&quot;&gt;5. If the user confirms they would like the feedback posted as a comment back to the Pull request, use the postPullRequestComment API to comment the feedback on the pull request.&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;button class=&quot;rounded p-1.5 hover:bg-muted/10 transition-all absolute top-2 right-2&quot;&gt;&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; width=&quot;24&quot; height=&quot;24&quot; viewBox=&quot;0 0 24 24&quot; fill=&quot;none&quot; stroke=&quot;currentColor&quot; stroke-width=&quot;2&quot; stroke-linecap=&quot;round&quot; stroke-linejoin=&quot;round&quot; class=&quot;h-5 w-5 stroke-1 stroke-gray-200&quot;&gt;&lt;rect width=&quot;14&quot; height=&quot;14&quot; x=&quot;8&quot; y=&quot;8&quot; rx=&quot;2&quot; ry=&quot;2&quot;&gt;&lt;/rect&gt;&lt;path d=&quot;M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2&quot;&gt;&lt;/path&gt;&lt;/svg&gt;&lt;/button&gt;&lt;/div&gt;&lt;/div&gt;
        &lt;h3 id=&quot;openapi-schema&quot;&gt;&lt;a class=&quot;heading-link&quot; href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_github#openapi-schema&quot;&gt;OpenAPI Schema&lt;/a&gt;&lt;/h3&gt;
        &lt;p&gt;Once you&#39;ve created a Custom GPT, copy the text below in the Actions panel. Have questions? Check out &lt;a href=&quot;https://platform.openai.com/docs/actions/getting-started&quot;&gt;Getting Started Example&lt;/a&gt; to see how this step works in more detail.&lt;/p&gt;
        &lt;p&gt;Below is an example of what connecting to GitHub to GET the Pull Request Diff and POST the Feedback to the Pull Request might look like.&lt;/p&gt;
        &lt;div data-rehype-pretty-code-fragment=&quot;&quot;&gt;&lt;div class=&quot;relative&quot;&gt;&lt;pre&gt;&lt;code data-language=&quot;javascript&quot; data-theme=&quot;default&quot; style=&quot;display:grid&quot;&gt;&lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;openapi&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#79B8FF&quot;&gt;3.1&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;color:#79B8FF&quot;&gt;0&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;info&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;title&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: GitHub Pull Request &lt;/span&gt;&lt;span style=&quot;color:#79B8FF&quot;&gt;API&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;description&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: Retrieve the diff &lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;of&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; a pull request and post comments back to it.&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;version&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#79B8FF&quot;&gt;1.0&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;color:#79B8FF&quot;&gt;0&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;servers&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;-&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;url&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;https&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;color:#6A737D&quot;&gt;//api.github.com&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;description&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: GitHub &lt;/span&gt;&lt;span style=&quot;color:#79B8FF&quot;&gt;API&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;paths&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#9ECBFF&quot;&gt;/&lt;/span&gt;&lt;span style=&quot;color:#DBEDFF&quot;&gt;repos&lt;/span&gt;&lt;span style=&quot;color:#9ECBFF&quot;&gt;/&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;{owner}&lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;/&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;{repo}&lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;/&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;pulls&lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;/&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;{pull_number}:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;get&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;operationId&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: getPullRequestDiff&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;summary&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: Get the diff &lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;of&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; a pull request.&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;parameters&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;-&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;name&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: owner&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;in&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: path&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;required&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#79B8FF&quot;&gt;true&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;schema&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;type&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: string&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;description&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: Owner &lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;of&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; the repository.&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;-&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;name&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: repo&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;in&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: path&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;required&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#79B8FF&quot;&gt;true&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;schema&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;type&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: string&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;description&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: Name &lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;of&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; the repository.&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;-&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;name&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: pull_number&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;in&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: path&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;required&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#79B8FF&quot;&gt;true&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;schema&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;type&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: integer&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;description&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: The number &lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;of&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; the pull request.&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;-&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;name&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: Accept&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;in&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: header&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;required&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#79B8FF&quot;&gt;true&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;schema&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;type&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: string&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;enum&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;-&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; application&lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;/&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;vnd.github.v3.diff&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;description&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: Media &lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;type&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;for&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; the diff format.&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; responses:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &quot;200&quot;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; description: Successfully retrieved the pull request diff.&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; content:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; text/plain:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; schema:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;type&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: string&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#9ECBFF&quot;&gt;&quot;404&quot;&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;description&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: Pull request not found.&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#9ECBFF&quot;&gt;/&lt;/span&gt;&lt;span style=&quot;color:#DBEDFF&quot;&gt;repos&lt;/span&gt;&lt;span style=&quot;color:#9ECBFF&quot;&gt;/&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;{owner}&lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;/&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;{repo}&lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;/&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;issues&lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;/&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;{issue_number}&lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;/&lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;comments&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;post&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;operationId&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: postPullRequestComment&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;summary&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: Post a comment to the pull request.&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;parameters&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;-&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;name&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: owner&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;in&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: path&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;required&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#79B8FF&quot;&gt;true&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;schema&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;type&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: string&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;description&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: Owner &lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;of&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; the repository.&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;-&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;name&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: repo&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;in&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: path&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;required&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#79B8FF&quot;&gt;true&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;schema&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;type&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: string&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;description&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: Name &lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;of&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; the repository.&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;-&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;name&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: issue_number&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;in&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: path&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;required&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#79B8FF&quot;&gt;true&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;schema&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;type&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: integer&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;description&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: The issue or pull request number.&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;requestBody&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;required&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#79B8FF&quot;&gt;true&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;content&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; application&lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;/&lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;json&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;schema&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;type&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: object&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;properties&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;body&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;type&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: string&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;description&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: The content &lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;of&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; the comment.&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;responses&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#9ECBFF&quot;&gt;&quot;201&quot;&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;description&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: Successfully created a comment.&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;content&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; application&lt;/span&gt;&lt;span style=&quot;color:#F97583&quot;&gt;/&lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;json&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;schema&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;type&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: object&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;properties&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;id&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;type&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: integer&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;body&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;type&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: string&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;user&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;type&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: object&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;properties&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;login&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;type&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: string&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;id&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;type&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: integer&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#9ECBFF&quot;&gt;&quot;404&quot;&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
        &lt;span data-line=&quot;&quot;&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt; &lt;/span&gt;&lt;span style=&quot;color:#B392F0&quot;&gt;description&lt;/span&gt;&lt;span style=&quot;color:#E1E4E8&quot;&gt;: Pull request not found.&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;button class=&quot;rounded p-1.5 hover:bg-muted/10 transition-all absolute top-2 right-2&quot;&gt;&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; width=&quot;24&quot; height=&quot;24&quot; viewBox=&quot;0 0 24 24&quot; fill=&quot;none&quot; stroke=&quot;currentColor&quot; stroke-width=&quot;2&quot; stroke-linecap=&quot;round&quot; stroke-linejoin=&quot;round&quot; class=&quot;h-5 w-5 stroke-1 stroke-gray-200&quot;&gt;&lt;rect width=&quot;14&quot; height=&quot;14&quot; x=&quot;8&quot; y=&quot;8&quot; rx=&quot;2&quot; ry=&quot;2&quot;&gt;&lt;/rect&gt;&lt;path d=&quot;M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2&quot;&gt;&lt;/path&gt;&lt;/svg&gt;&lt;/button&gt;&lt;/div&gt;&lt;/div&gt;
        &lt;h2 id=&quot;authentication-instructions&quot;&gt;&lt;a class=&quot;heading-link&quot; href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_github#authentication-instructions&quot;&gt;Authentication Instructions&lt;/a&gt;&lt;/h2&gt;
        &lt;p&gt;Below are instructions on setting up authentication with this 3rd party application. Have questions? Check out &lt;a href=&quot;https://platform.openai.com/docs/actions/getting-started&quot;&gt;Getting Started Example&lt;/a&gt; to see how this step works in more detail.&lt;/p&gt;
        &lt;h3 id=&quot;in-chatgpt-refer-to-step-2-in-the-getting-started-example&quot;&gt;&lt;a class=&quot;heading-link&quot; href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_github#in-chatgpt-refer-to-step-2-in-the-getting-started-example&quot;&gt;In ChatGPT (refer to Step 2 in the Getting Started Example)&lt;/a&gt;&lt;/h3&gt;
        &lt;p&gt;In ChatGPT, click on &quot;Authentication&quot; and choose &lt;strong&gt;&quot;Bearer&quot;&lt;/strong&gt;. Enter in the information below. Ensure your token has the permissions described in Application setup, above.&lt;/p&gt;
        &lt;ul&gt;
        &lt;li&gt;Authentication Type: API Key&lt;/li&gt;
        &lt;li&gt;Auth Type: Bearer&lt;/li&gt;
        &lt;li&gt;API Key
        &amp;lt;personal_access_token&amp;gt;&lt;/li&gt;
        &lt;/ul&gt;
        &lt;h3 id=&quot;test-the-gpt&quot;&gt;&lt;a class=&quot;heading-link&quot; href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_github#test-the-gpt&quot;&gt;Test the GPT&lt;/a&gt;&lt;/h3&gt;
        &lt;p&gt;You are now ready to test out the GPT. You can enter a simple prompt like &quot;Can you review my pull request? owner: &amp;lt;org_name&amp;gt;, repo: &amp;lt;repo_name&amp;gt;, pull request number: &amp;lt;PR_Number&amp;gt;&quot; and expect to see the following:&lt;/p&gt;
        &lt;p&gt;&lt;img src=&quot;https://cookbook.openai.com/images/landing_page.png&quot; alt=&quot;landing_page.png&quot; referrerpolicy=&quot;no-referrer&quot;&gt;&lt;/p&gt;
        &lt;ol&gt;
        &lt;li&gt;A summary of changes in the referenced pull request(PR).&lt;/li&gt;
        &lt;/ol&gt;
        &lt;p&gt;&lt;img src=&quot;https://cookbook.openai.com/images/first_interaction.png&quot; alt=&quot;First Interaction&quot; referrerpolicy=&quot;no-referrer&quot;&gt;&lt;/p&gt;
        &lt;ol start=&quot;2&quot;&gt;
        &lt;li&gt;Quality and Security feedback and suggestions to incorporate in the next iteration of the PR.&lt;/li&gt;
        &lt;/ol&gt;
        &lt;p&gt;&lt;img src=&quot;https://cookbook.openai.com/images/first_feedback.png&quot; alt=&quot;First Feedback&quot; referrerpolicy=&quot;no-referrer&quot;&gt;&lt;/p&gt;
        &lt;ol start=&quot;3&quot;&gt;
        &lt;li&gt;An option to iterate on the feedback or accept it and have the GPT post it directly to the PR as a comment from you.&lt;/li&gt;
        &lt;/ol&gt;
        &lt;p&gt;&lt;img src=&quot;https://cookbook.openai.com/images/final_result.png&quot; alt=&quot;First Interaction&quot; referrerpolicy=&quot;no-referrer&quot;&gt;&lt;/p&gt;
        &lt;p&gt;&lt;em&gt;Are there integrations that you’d like us to prioritize? Are there errors in our integrations? File a PR or issue in our github, and we’ll take a look.&lt;/em&gt;&lt;/p&gt;</description>
      <link>https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_github</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_github</guid>
      <pubDate>Tue, 22 Oct 2024 16:00:00 GMT</pubDate>
      <category>ChatGPT</category>
      <category>GPT actions library</category>
    </item>
    <item>
      <title>Voice Translation into Different Languages</title>
      <description>&lt;p&gt;Have you ever wanted to translate a podcast into your native language? Translating and dubbing audio content can make it more accessible to audiences worldwide. With GPT-4o&#39;s new audio-in and audio-out modality, this process is now easier than ever.&lt;/p&gt;
        &lt;p&gt;This guide will walk you through translating an English audio file into Hindi using OpenAI&#39;s GPT-4o audio modality API.&lt;/p&gt;
        &lt;p&gt;GPT-4o simplifies the dubbing process for audio content. Previously, you had to convert the audio to text and then translate the text into the target language before converting it back into audio. Now, with GPT-4o’s voice-to-voice capability, you can achieve this in a single step with audio input and output.&lt;/p&gt;
        &lt;p&gt;A note on semantics used in this Cookbook regarding &lt;strong&gt;Language&lt;/strong&gt; and written &lt;strong&gt;Script&lt;/strong&gt;. These words are generally used interchangeably, though it&#39;s important to understand the distinction, given the task at hand.&lt;/p&gt;
        &lt;p&gt;&lt;strong&gt;- Language&lt;/strong&gt; refers to the spoken or written system of communication. For instance, Hindi and Marathi are different languages, but both use the Devanagari script. Similarly, English and French are different languages, but are written in Latin script.&lt;/p&gt;
        &lt;p&gt;&lt;strong&gt;- Script&lt;/strong&gt; refers to the set of characters or symbols used to write the language. For example, Serbian language traditionally written in Cyrillic Script, is also written in Latin script.&lt;/p&gt;
        &lt;p&gt;GPT-4o audio-in and audio-out modality makes it easier to dub the audio from one language to another with one API call.&lt;/p&gt;
        &lt;p&gt;&lt;strong&gt;1. Transcribe&lt;/strong&gt; the source audio file into source language script using GPT-4o. This is an optional step that can be skipped if you already have the transcription of source audio content.&lt;/p&gt;
        &lt;p&gt;&lt;strong&gt;2. Dub&lt;/strong&gt; the audio file from source language directly to the target langauge.&lt;/p&gt;
        &lt;p&gt;&lt;strong&gt;3. Obtain Translation Benchmarks&lt;/strong&gt; using BLEU or ROUGE.&lt;/p&gt;
        &lt;p&gt;&lt;strong&gt;4. Interpret and improve&lt;/strong&gt; scores by adjusting prompting parameters in steps 1-3 as needed.&lt;/p&gt;
        &lt;p&gt;Before we get started, make sure you have your OpenAI API key configured as an environment variable, and necessary packages installed as outlined in the code cells below.&lt;/p&gt;</description>
      <link>https://cookbook.openai.com/examples/voice_solutions/voice_translation_into_different_languages_using_gpt-4o</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/voice_solutions/voice_translation_into_different_languages_using_gpt-4o</guid>
      <pubDate>Sun, 20 Oct 2024 16:00:00 GMT</pubDate>
      <category>Audio</category>
      <category>Completions</category>
    </item>
    <item>
      <title>Leveraging model distillation to fine-tune a model</title>
      <description>&lt;p&gt;OpenAI recently released &lt;strong&gt;Distillation&lt;/strong&gt; which allows to leverage the outputs of a (large) model to fine-tune another (smaller) model. This can significantly reduce the price and the latency for specific tasks as you move to a smaller model. In this cookbook we&#39;ll look at a dataset, distill the output of gpt-4o to gpt-4o-mini and show how we can get significantly better results than on a generic, non-distilled, 4o-mini.&lt;/p&gt;
        &lt;p&gt;We&#39;ll also leverage &lt;strong&gt;Structured Outputs&lt;/strong&gt; for a classification problem using a list of enum. We&#39;ll see how fine-tuned model can benefit from structured output and how it will impact the performance. We&#39;ll show that &lt;strong&gt;Structured Ouputs&lt;/strong&gt; work with all of those models, including the distilled one.&lt;/p&gt;
        &lt;p&gt;We&#39;ll first analyze the dataset, get the output of both 4o and 4o mini, highlighting the difference in performance of both models, then proceed to the distillation and analyze the performance of this distilled model.&lt;/p&gt;</description>
      <link>https://cookbook.openai.com/examples/leveraging_model_distillation_to_fine-tune_a_model</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/leveraging_model_distillation_to_fine-tune_a_model</guid>
      <pubDate>Tue, 15 Oct 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category>Fine-tuning</category>
    </item>
    <item>
      <title>Custom LLM as a Judge to Detect Hallucinations with Braintrust</title>
      <description>&lt;p&gt;Let&#39;s say you&#39;re working on a customer service bot and trying to evaluate the quality of its responses. Consider a question like &quot;What is your return policy?&quot; If the correct answer is &quot;You can return items within 30 days of purchase,&quot; but your bot generates &quot;You can return items within 30 days,&quot; how would you evaluate whether this is a good response?&lt;/p&gt;
        &lt;p&gt;A heuristic like the &lt;code&gt;Levenshtein&lt;/code&gt; string distance would indicate that the response is incorrect. However, a better approach is to use an LLM-as-a-judge to assess the accuracy of the response. LLM-as-a-judge is a technique that leverages an LLM to score the quality of answers. LLMs can reason about language beyond surface-level string comparisons, enabling them to evaluate answers more accurately.&lt;/p&gt;
        &lt;p&gt;In this cookbook, we&#39;ll walk through how to build an LLM-as-a-judge scorer that can detect hallucinations using &lt;a href=&quot;https://www.braintrust.dev/&quot;&gt;Braintrust&lt;/a&gt;, a third-party evaluation platform that is compatible with OpenAI&#39;s models.&lt;/p&gt;
        &lt;h2 id=&quot;installing-dependencies&quot;&gt;&lt;a class=&quot;heading-link&quot; href=&quot;https://cookbook.openai.com/examples/custom-llm-as-a-judge#installing-dependencies&quot;&gt;Installing dependencies&lt;/a&gt;&lt;/h2&gt;
        &lt;p&gt;Let&#39;s install a few basic dependencies. We&#39;ll use the CoQA dataset (via DuckDB), &lt;a href=&quot;https://www.braintrust.dev/&quot;&gt;Braintrust&lt;/a&gt; for evals, and &lt;a href=&quot;https://platform.openai.com/docs/models&quot;&gt;OpenAI&#39;s models&lt;/a&gt;. Please note that Braintrust is a third-party evaluation platform and you should review their &lt;a href=&quot;https://www.braintrust.dev/legal/terms-of-service&quot;&gt;terms of service and privacy policy&lt;/a&gt; before proceeding.&lt;/p&gt;</description>
      <link>https://cookbook.openai.com/examples/custom-llm-as-a-judge</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/custom-llm-as-a-judge</guid>
      <pubDate>Sun, 13 Oct 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
      <category></category>
    </item>
    <item>
      <title>Orchestrating Agents: Routines and Handoffs</title>
      <description>&lt;p&gt;When working with language models, quite often all you need for solid performance is a good prompt and the right tools. However, when dealing with many unique flows, things may get hairy. This cookbook will walk through one way to tackle this.&lt;/p&gt;
        &lt;p&gt;We&#39;ll introduce the notion of &lt;strong&gt;routines&lt;/strong&gt; and &lt;strong&gt;handoffs&lt;/strong&gt;, then walk through the implementation and show how they can be used to orchestrate multiple agents in a simple, powerful, and controllable way.&lt;/p&gt;
        &lt;p&gt;Finally, we provide a sample repo, &lt;a href=&quot;https://github.com/openai/swarm&quot;&gt;Swarm&lt;/a&gt;, that implements these ideas along with examples.&lt;/p&gt;</description>
      <link>https://cookbook.openai.com/examples/orchestrating_agents</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/orchestrating_agents</guid>
      <pubDate>Wed, 09 Oct 2024 16:00:00 GMT</pubDate>
      <category></category>
      <category>Completions</category>
      <category>Functions</category>
    </item>
    <item>
      <title>Building a Bring Your Own Browser (BYOB) Tool for Web Browsing and Summarization</title>
      <description>&lt;p&gt;&lt;strong&gt;Disclaimer: This cookbook is for educational purposes only. Ensure that you comply with all applicable laws and service terms when using web search and scraping technologies. This cookbook will restrict the search to openai.com domain to retrieve the public information to illustrate the concepts.&lt;/strong&gt;&lt;/p&gt;
        &lt;p&gt;Large Language Models (LLMs) such as GPT-4o have a knowledge cutoff date, which means they lack information about events that occurred after that point. In scenarios where the most recent data is essential, it&#39;s necessary to provide LLMs with access to current web information to ensure accurate and relevant responses.&lt;/p&gt;
        &lt;p&gt;In this guide, we will build a Bring Your Own Browser (BYOB) tool using Python to overcome this limitation. Our goal is to create a system that provides up-to-date answers in your application, including the most recent developments such as the latest product launches by OpenAI. By integrating web search capabilities with an LLM, we&#39;ll enable the model to generate responses based on the latest information available online.&lt;/p&gt;
        &lt;p&gt;While you can use any publicly available search APIs, we&#39;ll utilize Google&#39;s Custom Search API to perform web searches. The retrieved information from the search results will be processed and passed to the LLM to generate the final response through Retrieval-Augmented Generation (RAG).&lt;/p&gt;
        &lt;p&gt;&lt;strong&gt;Bring Your Own Browser (BYOB)&lt;/strong&gt; tools allow users to perform web browsing tasks programmatically. In this notebook, we&#39;ll create a BYOB tool that:&lt;/p&gt;
        &lt;p&gt;&lt;strong&gt;#1. Set Up a Search Engine:&lt;/strong&gt; Use a public search API, such as Google&#39;s Custom Search API, to perform web searches and obtain a list of relevant search results.&lt;/p&gt;
        &lt;p&gt;&lt;strong&gt;#2. Build a Search Dictionary:&lt;/strong&gt; Collect the title, URL, and a summary of each web page from the search results to create a structured dictionary of information.&lt;/p&gt;
        &lt;p&gt;&lt;strong&gt;#3. Generate a RAG Response:&lt;/strong&gt; Implement Retrieval-Augmented Generation (RAG) by passing the gathered information to the LLM, which then generates a final response to the user&#39;s query.&lt;/p&gt;</description>
      <link>https://cookbook.openai.com/examples/third_party/web_search_with_google_api_bring_your_own_browser_tool</link>
      <guid isPermaLink="false">https://cookbook.openai.com/examples/third_party/web_search_with_google_api_bring_your_own_browser_tool</guid>
      <pubDate>Wed, 25 Sep 2024 16:00:00 GMT</pubDate>
      <category>Completions</category>
    </item>
    <item>
      <title>GPT Actions library - Canvas Learning Management System</title>
      <description>&lt;h3 id=&quot;table-of-contents&quot;&gt;&lt;a class=&quot;heading-link&quot; href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_canvas#table-of-contents&quot;&gt;Table of Contents&lt;/a&gt;&lt;/h3&gt;
        &lt;ol&gt;
        &lt;li&gt;
        &lt;p&gt;&lt;a href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_canvas#general-app-information&quot;&gt;&lt;strong&gt;General App Information&lt;/strong&gt;&lt;/a&gt; - Overview of Canvas LMS, its functionality, and the role of ChatGPT&#39;s Custom Actions to enhance educational experiences through AI integration.&lt;/p&gt;
        &lt;/li&gt;
        &lt;li&gt;
        &lt;p&gt;&lt;a href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_canvas#authentication-from-chatgpt-to-canvas&quot;&gt;&lt;strong&gt;Authentication from ChatGPT to Canvas&lt;/strong&gt;&lt;/a&gt; - Explanation of authentication methods (OAuth and User Generated Access Tokens) for connecting ChatGPT to Canvas, with detailed instructions for setting up each option.&lt;/p&gt;
        &lt;/li&gt;
        &lt;li&gt;
        &lt;p&gt;&lt;a href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_canvas#sample-use-case-student-course-assistant&quot;&gt;&lt;strong&gt;Sample Use Case: Student Course Assistant&lt;/strong&gt;&lt;/a&gt; - Detailed example of using ChatGPT to assist students with course navigation, exam preparation, and personalized feedback, including specific API calls and workflows.&lt;/p&gt;
        &lt;/li&gt;
        &lt;li&gt;
        &lt;p&gt;&lt;a href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_canvas#other-use-cases-for-consideration&quot;&gt;&lt;strong&gt;Other Use Cases for Consideration&lt;/strong&gt;&lt;/a&gt; - Additional potential integrations using the Canvas API, such as classroom analytics and report generation.&lt;/p&gt;
        &lt;/li&gt;
        &lt;li&gt;
        &lt;p&gt;&lt;a href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_canvas#congratulations&quot;&gt;&lt;strong&gt;Congratulations&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;
        &lt;/li&gt;
        &lt;/ol&gt;
        &lt;h2 id=&quot;general-app-information&quot;&gt;&lt;a class=&quot;heading-link&quot; href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_canvas#general-app-information&quot;&gt;General App Information&lt;/a&gt;&lt;/h2&gt;
        &lt;p&gt;Canvas is a widely-used Learning Management System (LMS) designed to support online learning and teaching. It offers a robust set of tools for course management, content delivery, assessments, and student collaboration. Through the &lt;a href=&quot;https://canvas.instructure.com/doc/api/all_resources.html&quot;&gt;Canvas REST API&lt;/a&gt;, Canvas allows for extensive customization and integration with third-party applications, including AI-powered tools like ChatGPT.&lt;/p&gt;
        &lt;p&gt;ChatGPT’s Custom Actions with Canvas enable educators to leverage AI to enhance course content, automate tasks, and provide personalized learning journeys for students. Examples include virtual teaching assistants based on active courses, as the capabilities are well-suited for pulling information in from Canvas to create an educational dialogue. ChatGPT with Custom Actions is not meant for automating the entire Canvas experience nor act as a replacement to many of its capabilities better suited for completion in the Canvas app.&lt;/p&gt;
        &lt;h2 id=&quot;authentication-from-chatgpt-to-canvas&quot;&gt;&lt;a class=&quot;heading-link&quot; href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_canvas#authentication-from-chatgpt-to-canvas&quot;&gt;Authentication from ChatGPT to Canvas&lt;/a&gt;&lt;/h2&gt;
        &lt;p&gt;For a general overview on Authentication in Custom Actions, see the &lt;a href=&quot;https://platform.openai.com/docs/actions/authentication&quot;&gt;Action authentication documentation&lt;/a&gt;.&lt;/p&gt;
        &lt;p&gt;There are two options for authentication in Canvas: 1) OAuth and 2) User Generated Access Tokens.&lt;/p&gt;
        &lt;ul&gt;
        &lt;li&gt;For large-scale deployments, it is required to use OAuth for Action Authentication.&lt;/li&gt;
        &lt;li&gt;If the user is considering a single-user deployment or does not have access to Admin Settings, they may consider User Generated Access Tokens. Be aware that any request made by the action will be made using the token the user generated, so Canvas will register all requests as the user&#39;s activity and use the user&#39;s permissions to complete them.&lt;/li&gt;
        &lt;/ul&gt;
        &lt;h3 id=&quot;implementing-oauth-for-canvas&quot;&gt;&lt;a class=&quot;heading-link&quot; href=&quot;https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_canvas#implementing-oauth-for-canvas&quot;&gt;Implementing OAuth for Canvas&lt;/a&

github-actions[bot] avatar Oct 30 '24 04:10 github-actions[bot]