Skip to content

Examples and guides for using the OpenAI API

Run docs-editor across cookbook notebooks (#2864)

Vaibhav Srivastav0aaed0f1d32f
diff --git a/examples/Assistants_API_overview_python.ipynb b/examples/Assistants_API_overview_python.ipynb
index dc3a74af..d841b7af 100644
--- a/examples/Assistants_API_overview_python.ipynb
+++ b/examples/Assistants_API_overview_python.ipynb
@@ -680,7 +680,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "I've also defined a `create_thread_and_run` function that I can re-use (which is actually almost identical to the [`client.beta.threads.create_and_run`](https://platform.openai.com/docs/api-reference/runs/createThreadAndRun) compound function in our API ;) ). Finally, we can submit our mock user requests each to a new Thread.\n",
+ "I've also defined a `create_thread_and_run` function that I can reuse (which is actually almost identical to the [`client.beta.threads.create_and_run`](https://platform.openai.com/docs/api-reference/runs/createThreadAndRun) compound function in our API ;) ). Finally, we can submit our mock user requests each to a new Thread.\n",
"\n",
"Notice how all of these API calls are asynchronous operations; this means we actually get async behavior in our code without the use of async libraries! (e.g. `asyncio`)\n"
]
diff --git a/examples/Build_a_coding_agent_with_GPT-5.1.ipynb b/examples/Build_a_coding_agent_with_GPT-5.1.ipynb
index 9171d5d8..61466d25 100644
--- a/examples/Build_a_coding_agent_with_GPT-5.1.ipynb
+++ b/examples/Build_a_coding_agent_with_GPT-5.1.ipynb
@@ -930,7 +930,7 @@
"id": "fcbba5aa",
"metadata": {},
"source": [
- "### Connect to the the Context7 MCP server"
+ "### Connect to the Context7 MCP server"
]
},
{
diff --git a/examples/Classification_using_embeddings.ipynb b/examples/Classification_using_embeddings.ipynb
index 95366de7..7c0ec74c 100644
--- a/examples/Classification_using_embeddings.ipynb
+++ b/examples/Classification_using_embeddings.ipynb
@@ -107,7 +107,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Unsurprisingly 5-star and 1-star reviews seem to be easier to predict. Perhaps with more data, the nuances between 2-4 stars could be better predicted, but there's also probably more subjectivity in how people use the inbetween scores."
+ "Unsurprisingly 5-star and 1-star reviews seem to be easier to predict. Perhaps with more data, the nuances between 2-4 stars could be better predicted, but there's also probably more subjectivity in how people use the in-between scores."
]
}
],
diff --git a/examples/Clustering.ipynb b/examples/Clustering.ipynb
index 7ca3a017..ffc3502a 100644
--- a/examples/Clustering.ipynb
+++ b/examples/Clustering.ipynb
@@ -254,7 +254,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "It's important to note that clusters will not necessarily match what you intend to use them for. A larger amount of clusters will focus on more specific patterns, whereas a small number of clusters will usually focus on largest discrepencies in the data."
+ "It's important to note that clusters will not necessarily match what you intend to use them for. A larger number of clusters will focus on more specific patterns, whereas fewer clusters will usually focus on the largest discrepancies in the data."
]
}
],
diff --git a/examples/Creating_slides_with_Assistants_API_and_DALL-E3.ipynb b/examples/Creating_slides_with_Assistants_API_and_DALL-E3.ipynb
index b9ba22f5..bb15de47 100644
--- a/examples/Creating_slides_with_Assistants_API_and_DALL-E3.ipynb
+++ b/examples/Creating_slides_with_Assistants_API_and_DALL-E3.ipynb
@@ -221,7 +221,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Now, we're ready to create our Assistant. We can instruct our assistant to act as a data scientist, and take any queries we give it and run the necessary code to output the proper data visualization. The instructions parameter here is akin to system instructions in the ChatCompletions endpoint, and can help guide the assistant. We can also turn on the tool of Code Interpreter, so our Assistant will be able to code. Finally, we can specifiy any files we want to use, which in this case is just the `financial_data` file we created above."
+ "Now, we're ready to create our Assistant. We can instruct our assistant to act as a data scientist, and take any queries we give it and run the necessary code to output the proper data visualization. The instructions parameter here is akin to system instructions in the Chat Completions API, and can help guide the assistant. We can also turn on the tool of Code Interpreter, so our Assistant will be able to code. Finally, we can specify any files we want to use, which in this case is just the `financial_data` file we created above."
]
},
{
@@ -654,7 +654,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "We now have all the content we need to create the slides. While we could simply add a message asking for slides, but let's instead give the assistant a slide template, using the `python-pptx` library, to use. This will ensure we get a deck in the style we want. See the `Extensions` section at the end of the notebook for notes on creating the template."
+ "We now have all the content we need to create the slides. We could simply add a message asking for slides, but let's instead give the assistant a slide template to use with the `python-pptx` library. This will ensure we get a deck in the style we want. See the `Extensions` section at the end of the notebook for notes on creating the template."
]
},
{
@@ -792,7 +792,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Let's set a few quick variables for our slides. We want the company name, NotRealCorp, to be on the title slide, and the title of the presentation should 'Quartlerly financial planning metting, Q3, 2023'."
+ "Let's set a few variables for our slides. We want the company name, NotRealCorp, on the title slide, and the presentation should be titled 'Quarterly financial planning meeting, Q3, 2023'."
]
},
{
@@ -948,7 +948,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Woo! While these slides could use some formatting tweaks, we have made some great content using the Assistants API, GPT-4 and DALL·E-3. We were able to take a `.csv` file with financial data, and use our assisant to calculate profit by quarter across distribution channels, plot the results, identify insights and key takeaways from the visualization, and create a summarative title. And, given just a description of our company, NotRealCorp, we used DALL·E-3 to make an awesome title image. <br><br>\n",
+ "Woo! While these slides could use some formatting tweaks, we have made some great content using the Assistants API, GPT-4 and DALL·E-3. We were able to take a `.csv` file with financial data, and use our assistant to calculate profit by quarter across distribution channels, plot the results, identify insights and key takeaways from the visualization, and create a summary title. And, given just a description of our company, NotRealCorp, we used DALL·E-3 to make an awesome title image. <br><br>\n",
"While we are still a ways away from entirely automating this process without a human in the loop, hopefully this notebook can make the slide creation process a bit easier for you. More importantly, this notebook can ideally give you a glimpse into the potential of the assistants API! We're excited to see what you build."
]
},
diff --git a/examples/Customizing_embeddings.ipynb b/examples/Customizing_embeddings.ipynb
index a03bedcc..f341e2e4 100644
--- a/examples/Customizing_embeddings.ipynb
+++ b/examples/Customizing_embeddings.ipynb
@@ -63,7 +63,7 @@
"source": [
"## 1. Inputs\n",
"\n",
- "Most inputs are here. The key things to change are where to load your datset from, where to save a cache of embeddings to, and which embedding engine you want to use.\n",
+ "Most inputs are here. The key things to change are where to load your dataset from, where to save a cache of embeddings to, and which embedding engine you want to use.\n",
"\n",
"Depending on how your data is formatted, you'll want to rewrite the process_input_data function."
]
@@ -227,7 +227,7 @@
"source": [
"## 3. Split data into training test sets\n",
"\n",
- "Note that it's important to split data into training and test sets *before* generating synethetic negatives or positives. You don't want any text strings in the training data to show up in the test data. If there's contamination, the test metrics will look better than they'll actually be in production."
+ "Note that it's important to split data into training and test sets *before* generating synthetic negatives or positives. You don't want any text strings in the training data to show up in the test data. If there's contamination, the test metrics will look better than they'll actually be in production."
]
},
{
diff --git a/examples/Data-intensive-Realtime-apps.ipynb b/examples/Data-intensive-Realtime-apps.ipynb
index a9439013..753ab736 100644
--- a/examples/Data-intensive-Realtime-apps.ipynb
+++ b/examples/Data-intensive-Realtime-apps.ipynb
@@ -309,7 +309,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "**ii) Periodically remind the the model of its role and responsibilities**\n",
+ "**ii) Periodically remind the model of its role and responsibilities**\n",
"\n",
"Data-heavy payloads can quickly fill the context window. If you notice the model losing track of instructions or available tools, periodically remind it of its system prompt and tools by calling `session.update`—this keeps it focused on its role and responsibilities."
]
diff --git a/examples/Fine-tuned_classification.ipynb b/examples/Fine-tuned_classification.ipynb
index 96defa7f..17e44cb8 100644
--- a/examples/Fine-tuned_classification.ipynb
+++ b/examples/Fine-tuned_classification.ipynb
@@ -298,7 +298,7 @@
"## Fine-tuning\n",
"The tool suggests we run the following command to train the dataset. Since this is a classification task, we would like to know what the generalization performance on the provided validation set is for our classification use case.\n",
"\n",
- "We can simply copy the suggested command from the CLI tool. We specifically add `-m ada` to fine-tune a cheaper and faster ada model, which is usually comperable in performance to slower and more expensive models on classification use cases. "
+ "We can simply copy the suggested command from the CLI tool. We specifically add `-m ada` to fine-tune a cheaper and faster ada model, which is usually comparable in performance to slower and more expensive models on classification use cases. "
]
},
{
@@ -329,7 +329,7 @@
"source": [
"The model is successfully trained in about ten minutes. You can watch the finetune happen on [https://platform.openai.com/finetune/](https://platform.openai.com/finetune/)\n",
"\n",
- "You can also check on its status programatically:"
+ "You can also check on its status programmatically:"
]
},
{
diff --git a/examples/Function_calling_with_an_OpenAPI_spec.ipynb b/examples/Function_calling_with_an_OpenAPI_spec.ipynb
index 17cc1dfd..79571208 100644
--- a/examples/Function_calling_with_an_OpenAPI_spec.ipynb
+++ b/examples/Function_calling_with_an_OpenAPI_spec.ipynb
@@ -1 +1 @@
-{"cells":[{"attachments":{},"cell_type":"markdown","metadata":{"cell_id":"8317718bcd8b475e9b336514241d679e","deepnote_cell_type":"text-cell-h1","formattedRanges":[]},"source":["# Function-calling with an OpenAPI specification\n"]},{"attachments":{},"cell_type":"markdown","metadata":{"cell_id":"6f810c4e582c41a1bd3bdfc4263dee89","deepnote_cell_type":"text-cell-p","formattedRanges":[]},"source":["Much of the internet is powered by RESTful APIs. Giving GPT the ability to call them opens up a world of possibilities. This notebook demonstrates how GPTs can be used to intelligently call APIs. It leverages OpenAPI specifications and chained function calls.\n","\n","The [OpenAPI Specification (OAS)](https://swagger.io/specification/) is a universally accepted standard for describing the details of RESTful APIs in a format that machines can read and interpret. It enables both humans and computers to understand the capabilities of a service, and it can be leveraged to show GPT how to call APIs.\n","\n","This notebook is divided into two main sections:\n","\n","1. How to convert a sample OpenAPI specification into a list of function definitions for the chat completions API.\n","2. How to use the chat completions API to intelligently invoke these functions based on user instructions.\n","\n","We recommend familiariazing yourself with [function-calling](./How_to_call_functions_with_chat_models.ipynb) before proceding.\n"]},{"cell_type":"code","execution_count":1,"metadata":{"cell_id":"bf983b3e199d4ea6a2718e58a141bd88","deepnote_cell_type":"code","deepnote_to_be_reexecuted":false,"execution_millis":10617,"execution_start":1697419508239,"source_hash":"d6b9a6d3"},"outputs":[{"name":"stdout","output_type":"stream","text":["\u001b[33mDEPRECATION: textract 1.6.5 has a non-standard dependency specifier extract-msg<=0.29.*. pip 23.3 will enforce this behaviour change. A possible replacement is to upgrade to a newer version of textract or contact the author to suggest that they release a version with a conforming dependency specifiers. Discussion can be found at https://github.com/pypa/pip/issues/12063\u001b[0m\u001b[33m\n","\u001b[0m\n","\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.2.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m23.3.1\u001b[0m\n","\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n","\u001b[33mDEPRECATION: textract 1.6.5 has a non-standard dependency specifier extract-msg<=0.29.*. pip 23.3 will enforce this behaviour change. A possible replacement is to upgrade to a newer version of textract or contact the author to suggest that they release a version with a conforming dependency specifiers. Discussion can be found at https://github.com/pypa/pip/issues/12063\u001b[0m\u001b[33m\n","\u001b[0m\n","\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.2.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m23.3.1\u001b[0m\n","\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n"]}],"source":["!pip install -q jsonref # for resolving $ref's in the OpenAPI spec\n","!pip install -q openai"]},{"cell_type":"code","execution_count":7,"metadata":{"cell_id":"12fb12583cc74b7c842a1b4656b94f47","deepnote_cell_type":"code","deepnote_to_be_reexecuted":false,"execution_millis":10,"execution_start":1697419706563,"source_hash":"750280cb"},"outputs":[],"source":["import os\n","import json\n","import jsonref\n","from openai import OpenAI\n","import requests\n","from pprint import pp\n","\n","client = OpenAI(api_key=os.environ.get(\"OPENAI_API_KEY\", \"<your OpenAI API key if not set as env var>\"))"]},{"attachments":{},"cell_type":"markdown","metadata":{"cell_id":"76ae868e66b14cc48c9c447302ea268e","deepnote_cell_type":"text-cell-h2","formattedRanges":[]},"source":["## How to convert an OpenAPI specification into function definitions\n"]},{"attachments":{},"cell_type":"markdown","metadata":{"cell_id":"9cf167d2d5fe4d7eadb69ba18db4a696","deepnote_cell_type":"text-cell-p","formattedRanges":[]},"source":["The example OpenAPI spec we use here was created using `gpt-4`. We will transform this sample spec into a set of function definitions that can be supplied to the chat completion API. The model, based on the provided user instructions, generates a JSON object containing the necessary arguments to call these functions.\n","\n","Before we proceed, let's inspect this generated spec. OpenAPI specs include details about the API's endpoints, the operations they support, the parameters they accept, the requests they can handle, and the responses they return. The spec is defined in JSON format.\n","\n","The endpoints in the spec include operations for:\n","\n","- Listing all events\n","- Creating a new event\n","- Retrieving an event by ID\n","- Deleting an event by ID\n","- Updating an event name by ID\n","\n","Each operation in the spec has an `operationId`, which we will use as the function name when we parse the spec into function specifications. The spec also includes schemas that define the data types and structures of the parameters for each operation.\n","\n","You can see the schema here:\n"]},{"cell_type":"code","execution_count":3,"metadata":{"cell_id":"176efbfea4b546d28d9d9966342f286a","deepnote_cell_type":"code","deepnote_to_be_reexecuted":false,"execution_millis":231,"execution_start":1697419710160,"source_hash":"1ce3848"},"outputs":[{"data":{"text/plain":["{'openapi': '3.0.0',\n"," 'info': {'version': '1.0.0',\n"," 'title': 'Event Management API',\n"," 'description': 'An API for managing event data'},\n"," 'paths': {'/events': {'get': {'summary': 'List all events',\n"," 'operationId': 'listEvents',\n"," 'responses': {'200': {'description': 'A list of events',\n"," 'content': {'application/json': {'schema': {'type': 'array',\n"," 'items': {'type': 'object',\n"," 'properties': {'id': {'type': 'string'},\n"," 'name': {'type': 'string'},\n"," 'date': {'type': 'string', 'format': 'date-time'},\n"," 'location': {'type': 'string'}},\n"," 'required': ['name', 'date', 'location']}}}}}}},\n"," 'post': {'summary': 'Create a new event',\n"," 'operationId': 'createEvent',\n"," 'requestBody': {'required': True,\n"," 'content': {'application/json': {'schema': {'type': 'object',\n"," 'properties': {'id': {'type': 'string'},\n"," 'name': {'type': 'string'},\n"," 'date': {'type': 'string', 'format': 'date-time'},\n"," 'location': {'type': 'string'}},\n"," 'required': ['name', 'date', 'location']}}}},\n"," 'responses': {'201': {'description': 'The event was created',\n"," 'content': {'application/json': {'schema': {'type': 'object',\n"," 'properties': {'id': {'type': 'string'},\n"," 'name': {'type': 'string'},\n"," 'date': {'type': 'string', 'format': 'date-time'},\n"," 'location': {'type': 'string'}},\n"," 'required': ['name', 'date', 'location']}}}}}}},\n"," '/events/{id}': {'get': {'summary': 'Retrieve an event by ID',\n"," 'operationId': 'getEventById',\n"," 'parameters': [{'name': 'id',\n"," 'in': 'path',\n"," 'required': True,\n"," 'schema': {'type': 'string'}}],\n"," 'responses': {'200': {'description': 'The event',\n"," 'content': {'application/json': {'schema': {'type': 'object',\n"," 'properties': {'id': {'type': 'string'},\n"," 'name': {'type': 'string'},\n"," 'date': {'type': 'string', 'format': 'date-time'},\n"," 'location': {'type': 'string'}},\n"," 'required': ['name', 'date', 'location']}}}}}},\n"," 'delete': {'summary': 'Delete an event by ID',\n"," 'operationId': 'deleteEvent',\n"," 'parameters': [{'name': 'id',\n"," 'in': 'path',\n"," 'required': True,\n"," 'schema': {'type': 'string'}}],\n"," 'responses': {'204': {'description': 'The event was deleted'}}},\n"," 'patch': {'summary': \"Update an event's details by ID\",\n"," 'operationId': 'updateEventDetails',\n"," 'parameters': [{'name': 'id',\n"," 'in': 'path',\n"," 'required': True,\n"," 'schema': {'type': 'string'}}],\n"," 'requestBody': {'required': True,\n"," 'content': {'application/json': {'schema': {'type': 'object',\n"," 'properties': {'name': {'type': 'string'},\n"," 'date': {'type': 'string', 'format': 'date-time'},\n"," 'location': {'type': 'string'}},\n"," 'required': ['name', 'date', 'location']}}}},\n"," 'responses': {'200': {'description': \"The event's details were updated\",\n"," 'content': {'application/json': {'schema': {'type': 'object',\n"," 'properties': {'id': {'type': 'string'},\n"," 'name': {'type': 'string'},\n"," 'date': {'type': 'string', 'format': 'date-time'},\n"," 'location': {'type': 'string'}},\n"," 'required': ['name', 'date', 'location']}}}}}}}},\n"," 'components': {'schemas': {'Event': {'type': 'object',\n"," 'properties': {'id': {'type': 'string'},\n"," 'name': {'type': 'string'},\n"," 'date': {'type': 'string', 'format': 'date-time'},\n"," 'location': {'type': 'string'}},\n"," 'required': ['name', 'date', 'location']}}}}"]},"metadata":{},"output_type":"display_data"}],"source":["with open('./data/example_events_openapi.json', 'r') as f:\n"," openapi_spec = jsonref.loads(f.read()) # it's important to load with jsonref, as explained below\n","\n","display(openapi_spec)"]},{"attachments":{},"cell_type":"markdown","metadata":{"cell_id":"e3e39ad4ac854299bf62b5f7bb1bef45","deepnote_cell_type":"text-cell-p","formattedRanges":[]},"source":["Now that we have a good understanding of the OpenAPI spec, we can proceed to parse it into function specifications.\n","\n","We can write a simple `openapi_to_functions` function to generate a list of definitions, where each function is represented as a dictionary containing the following keys:\n","\n","- `name`: This corresponds to the operation identifier of the API endpoint as defined in the OpenAPI specification.\n","- `description`: This is a brief description or summary of the function, providing an overview of what the function does.\n","- `parameters`: This is a schema that defines the expected input parameters for the function. It provides information about the type of each parameter, whether it is required or optional, and other related details.\n","\n","For each of the endpoints defined in the schema, we need to do the following:\n","\n","1. **Resolve JSON references**: In an OpenAPI specification, it's common to use JSON references (also known as $ref) to avoid duplication. These references point to definitions that are used in multiple places. For example, if multiple API endpoints return the same object structure, that structure can be defined once and then referenced wherever it's needed. We need to resolve and replace these references with the content they point to.\n","\n","2. **Extract a name for the functions:** We will simply use the operationId as the function name. Alternatively, we could use the endpoint path and operation as the function name.\n","\n","3. **Extract a description and parameters:** We will iterate through the `description`, `summary`, `requestBody` and `parameters` fields to populate the function's description and parameters.\n","\n","Here's the implementation:\n"]},{"cell_type":"code","execution_count":9,"metadata":{"cell_id":"adbb17ca8a2a4fa2aa3f0213a0e211b6","deepnote_cell_type":"code","deepnote_to_be_reexecuted":false,"execution_millis":333,"execution_start":1697419853135,"source_hash":"ad112cb1"},"outputs":[{"name":"stdout","output_type":"stream","text":["{'type': 'function',\n"," 'function': {'name': 'listEvents',\n"," 'description': 'List all events',\n"," 'parameters': {'type': 'object', 'properties': {}}}}\n","\n","{'type': 'function',\n"," 'function': {'name': 'createEvent',\n"," 'description': 'Create a new event',\n"," 'parameters': {'type': 'object',\n"," 'properties': {'requestBody': {'type': 'object',\n"," 'properties': {'id': {'type': 'string'},\n"," 'name': {'type': 'string'},\n"," 'date': {'type': 'string',\n"," 'format': 'date-time'},\n"," 'location': {'type': 'string'}},\n"," 'required': ['name',\n"," 'date',\n"," 'location']}}}}}\n","\n","{'type': 'function',\n"," 'function': {'name': 'getEventById',\n"," 'description': 'Retrieve an event by ID',\n"," 'parameters': {'type': 'object',\n"," 'properties': {'parameters': {'type': 'object',\n"," 'properties': {'id': {'type': 'string'}}}}}}}\n","\n","{'type': 'function',\n"," 'function': {'name': 'deleteEvent',\n"," 'description': 'Delete an event by ID',\n"," 'parameters': {'type': 'object',\n"," 'properties': {'parameters': {'type': 'object',\n"," 'properties': {'id': {'type': 'string'}}}}}}}\n","\n","{'type': 'function',\n"," 'function': {'name': 'updateEventDetails',\n"," 'description': \"Update an event's details by ID\",\n"," 'parameters': {'type': 'object',\n"," 'properties': {'requestBody': {'type': 'object',\n"," 'properties': {'name': {'type': 'string'},\n"," 'date': {'type': 'string',\n"," 'format': 'date-time'},\n"," 'location': {'type': 'string'}},\n"," 'required': ['name',\n"," 'date',\n"," 'location']},\n"," 'parameters': {'type': 'object',\n"," 'properties': {'id': {'type': 'string'}}}}}}}\n","\n"]}],"source":["def openapi_to_functions(openapi_spec):\n"," functions = []\n","\n"," for path, methods in openapi_spec[\"paths\"].items():\n"," for method, spec_with_ref in methods.items():\n"," # 1. Resolve JSON references.\n"," spec = jsonref.replace_refs(spec_with_ref)\n","\n"," # 2. Extract a name for the functions.\n"," function_name = spec.get(\"operationId\")\n","\n"," # 3. Extract a description and parameters.\n"," desc = spec.get(\"description\") or spec.get(\"summary\", \"\")\n","\n"," schema = {\"type\": \"object\", \"properties\": {}}\n","\n"," req_body = (\n"," spec.get(\"requestBody\", {})\n"," .get(\"content\", {})\n"," .get(\"application/json\", {})\n"," .get(\"schema\")\n"," )\n"," if req_body:\n"," schema[\"properties\"][\"requestBody\"] = req_body\n","\n"," params = spec.get(\"parameters\", [])\n"," if params:\n"," param_properties = {\n"," param[\"name\"]: param[\"schema\"]\n"," for param in params\n"," if \"schema\" in param\n"," }\n"," schema[\"properties\"][\"parameters\"] = {\n"," \"type\": \"object\",\n"," \"properties\": param_properties,\n"," }\n","\n"," functions.append(\n"," {\"type\": \"function\", \"function\": {\"name\": function_name, \"description\": desc, \"parameters\": schema}}\n"," )\n","\n"," return functions\n","\n","\n","functions = openapi_to_functions(openapi_spec)\n","\n","for function in functions:\n"," pp(function)\n"," print()\n"]},{"attachments":{},"cell_type":"markdown","metadata":{"cell_id":"f03f1aacdade4ed9a422797d3cf79fbb","deepnote_cell_type":"text-cell-h2","formattedRanges":[]},"source":["## How to call these functions with GPT\n"]},{"attachments":{},"cell_type":"markdown","metadata":{"cell_id":"08712696b5fd4cafac7b4b496ee67c5a","deepnote_cell_type":"text-cell-p","formattedRanges":[]},"source":["Now that we have these function definitions, we can leverage GPT to call them intelligently based on user inputs.\n","\n","It's important to note that the chat completions API does not execute the function; instead, it generates the JSON that you can use to call the function in your own code.\n","\n","For more information on function-calling, refer to our dedicated [function-calling guide](./How_to_call_functions_with_chat_models.ipynb).\n"]},{"cell_type":"code","execution_count":23,"metadata":{"cell_id":"b8f7d0f157264694b958008f93aabf3f","deepnote_cell_type":"code","deepnote_to_be_reexecuted":false,"execution_millis":6442,"execution_start":1697419907347,"source_hash":"ac9ad493"},"outputs":[{"name":"stdout","output_type":"stream","text":["ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_jmlvEyMRMvOtB80adX9RbqIV', function=Function(arguments='{}', name='listEvents'), type='function')])\n","\n",">> Function call #: 1\n","\n","[ChatCompletionMessageToolCall(id='call_jmlvEyMRMvOtB80adX9RbqIV', function=Function(arguments='{}', name='listEvents'), type='function')]\n","ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_OOPOY7IHMq3T7Ib71JozlUQJ', function=Function(arguments='{\\n \"requestBody\": {\\n \"id\": \"1234\",\\n \"name\": \"AGI Party\",\\n \"date\": \"2022-12-31\",\\n \"location\": \"New York\"\\n }\\n}', name='createEvent'), type='function')])\n","\n",">> Function call #: 2\n","\n","[ChatCompletionMessageToolCall(id='call_OOPOY7IHMq3T7Ib71JozlUQJ', function=Function(arguments='{\\n \"requestBody\": {\\n \"id\": \"1234\",\\n \"name\": \"AGI Party\",\\n \"date\": \"2022-12-31\",\\n \"location\": \"New York\"\\n }\\n}', name='createEvent'), type='function')]\n","ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_Kxluu3fJSOsZNNCn3JIlWAAM', function=Function(arguments='{\\n \"parameters\": {\\n \"id\": \"2456\"\\n }\\n}', name='deleteEvent'), type='function')])\n","\n",">> Function call #: 3\n","\n","[ChatCompletionMessageToolCall(id='call_Kxluu3fJSOsZNNCn3JIlWAAM', function=Function(arguments='{\\n \"parameters\": {\\n \"id\": \"2456\"\\n }\\n}', name='deleteEvent'), type='function')]\n","ChatCompletionMessage(content='Here are the actions I performed:\\n\\n1. Retrieved all the events.\\n2. Created a new event named \"AGI Party\" with the ID \"1234\", scheduled for December 31, 2022, in New York.\\n3. Deleted the event with the ID \"2456\".', role='assistant', function_call=None, tool_calls=None)\n","\n",">> Function call #: 4\n","\n","None\n","\n",">> Message:\n","\n","Here are the actions I performed:\n","\n","1. Retrieved all the events.\n","2. Created a new event named \"AGI Party\" with the ID \"1234\", scheduled for December 31, 2022, in New York.\n","3. Deleted the event with the ID \"2456\".\n"]}],"source":["SYSTEM_MESSAGE = \"\"\"\n","You are a helpful assistant.\n","Respond to the following prompt by using function_call and then summarize actions.\n","Ask for clarification if a user request is ambiguous.\n","\"\"\"\n","\n","# Maximum number of function calls allowed to prevent infinite or lengthy loops\n","MAX_CALLS = 5\n","\n","\n","def get_openai_response(functions, messages):\n"," return client.chat.completions.create(\n"," model=\"gpt-3.5-turbo-16k\",\n"," tools=functions,\n"," tool_choice=\"auto\", # \"auto\" means the model can pick between generating a message or calling a function.\n"," temperature=0,\n"," messages=messages,\n"," )\n","\n","\n","def process_user_instruction(functions, instruction):\n"," num_calls = 0\n"," messages = [\n"," {\"content\": SYSTEM_MESSAGE, \"role\": \"system\"},\n"," {\"content\": instruction, \"role\": \"user\"},\n"," ]\n","\n"," while num_calls < MAX_CALLS:\n"," response = get_openai_response(functions, messages)\n"," message = response.choices[0].message\n"," print(message)\n"," try:\n"," print(f\"\\n>> Function call #: {num_calls + 1}\\n\")\n"," pp(message.tool_calls)\n"," messages.append(message)\n","\n"," # For the sake of this example, we'll simply add a message to simulate success.\n"," # Normally, you'd want to call the function here, and append the results to messages.\n"," messages.append(\n"," {\n"," \"role\": \"tool\",\n"," \"content\": \"success\",\n"," \"tool_call_id\": message.tool_calls[0].id,\n"," }\n"," )\n","\n"," num_calls += 1\n"," except:\n"," print(\"\\n>> Message:\\n\")\n"," print(message.content)\n"," break\n","\n"," if num_calls >= MAX_CALLS:\n"," print(f\"Reached max chained function calls: {MAX_CALLS}\")\n","\n","\n","USER_INSTRUCTION = \"\"\"\n","Instruction: Get all the events.\n","Then create a new event named AGI Party.\n","Then delete event with id 2456.\n","\"\"\"\n","\n","process_user_instruction(functions, USER_INSTRUCTION)\n"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["### Conclusion\n","\n","We have demonstrated how to convert OpenAPI specs into function specifications that can be given to GPT for it to intelligently call them, and shown how these can be chained together to perform complex operations.\n","\n","Possible extensions of this system could include handling more complex user instructions that require conditional logic or looping, integrating with real APIs to perform actual operations, and improving error handling and validation to ensure the instructions are feasible and the function calls are successful.\n"]}],"metadata":{"deepnote":{},"deepnote_execution_queue":[],"deepnote_notebook_id":"84d101406ec34e36a9cf96d0c0c25a7d","kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.11.5"},"orig_nbformat":2},"nbformat":4,"nbformat_minor":0}
+{"cells":[{"attachments":{},"cell_type":"markdown","metadata":{"cell_id":"8317718bcd8b475e9b336514241d679e","deepnote_cell_type":"text-cell-h1","formattedRanges":[]},"source":["# Function-calling with an OpenAPI specification\n"]},{"attachments":{},"cell_type":"markdown","metadata":{"cell_id":"6f810c4e582c41a1bd3bdfc4263dee89","deepnote_cell_type":"text-cell-p","formattedRanges":[]},"source":["Much of the internet is powered by RESTful APIs. Giving GPT the ability to call them opens up a world of possibilities. This notebook demonstrates how GPTs can be used to intelligently call APIs. It leverages OpenAPI specifications and chained function calls.\n","\n","The [OpenAPI Specification (OAS)](https://swagger.io/specification/) is a universally accepted standard for describing the details of RESTful APIs in a format that machines can read and interpret. It enables both humans and computers to understand the capabilities of a service, and it can be leveraged to show GPT how to call APIs.\n","\n","This notebook is divided into two main sections:\n","\n","1. How to convert a sample OpenAPI specification into a list of function definitions for the chat completions API.\n","2. How to use the chat completions API to intelligently invoke these functions based on user instructions.\n","\n","We recommend familiarizing yourself with [function-calling](./How_to_call_functions_with_chat_models.ipynb) before proceeding.\n"]},{"cell_type":"code","execution_count":1,"metadata":{"cell_id":"bf983b3e199d4ea6a2718e58a141bd88","deepnote_cell_type":"code","deepnote_to_be_reexecuted":false,"execution_millis":10617,"execution_start":1697419508239,"source_hash":"d6b9a6d3"},"outputs":[{"name":"stdout","output_type":"stream","text":["\u001b[33mDEPRECATION: textract 1.6.5 has a non-standard dependency specifier extract-msg<=0.29.*. pip 23.3 will enforce this behaviour change. A possible replacement is to upgrade to a newer version of textract or contact the author to suggest that they release a version with a conforming dependency specifiers. Discussion can be found at https://github.com/pypa/pip/issues/12063\u001b[0m\u001b[33m\n","\u001b[0m\n","\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.2.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m23.3.1\u001b[0m\n","\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n","\u001b[33mDEPRECATION: textract 1.6.5 has a non-standard dependency specifier extract-msg<=0.29.*. pip 23.3 will enforce this behaviour change. A possible replacement is to upgrade to a newer version of textract or contact the author to suggest that they release a version with a conforming dependency specifiers. Discussion can be found at https://github.com/pypa/pip/issues/12063\u001b[0m\u001b[33m\n","\u001b[0m\n","\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.2.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m23.3.1\u001b[0m\n","\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n"]}],"source":["!pip install -q jsonref # for resolving $ref's in the OpenAPI spec\n","!pip install -q openai"]},{"cell_type":"code","execution_count":7,"metadata":{"cell_id":"12fb12583cc74b7c842a1b4656b94f47","deepnote_cell_type":"code","deepnote_to_be_reexecuted":false,"execution_millis":10,"execution_start":1697419706563,"source_hash":"750280cb"},"outputs":[],"source":["import os\n","import json\n","import jsonref\n","from openai import OpenAI\n","import requests\n","from pprint import pp\n","\n","client = OpenAI(api_key=os.environ.get(\"OPENAI_API_KEY\", \"<your OpenAI API key if not set as env var>\"))"]},{"attachments":{},"cell_type":"markdown","metadata":{"cell_id":"76ae868e66b14cc48c9c447302ea268e","deepnote_cell_type":"text-cell-h2","formattedRanges":[]},"source":["## How to convert an OpenAPI specification into function definitions\n"]},{"attachments":{},"cell_type":"markdown","metadata":{"cell_id":"9cf167d2d5fe4d7eadb69ba18db4a696","deepnote_cell_type":"text-cell-p","formattedRanges":[]},"source":["The example OpenAPI spec we use here was created using `gpt-4`. We will transform this sample spec into a set of function definitions that can be supplied to the chat completion API. The model, based on the provided user instructions, generates a JSON object containing the necessary arguments to call these functions.\n","\n","Before we proceed, let's inspect this generated spec. OpenAPI specs include details about the API's endpoints, the operations they support, the parameters they accept, the requests they can handle, and the responses they return. The spec is defined in JSON format.\n","\n","The endpoints in the spec include operations for:\n","\n","- Listing all events\n","- Creating a new event\n","- Retrieving an event by ID\n","- Deleting an event by ID\n","- Updating an event name by ID\n","\n","Each operation in the spec has an `operationId`, which we will use as the function name when we parse the spec into function specifications. The spec also includes schemas that define the data types and structures of the parameters for each operation.\n","\n","You can see the schema here:\n"]},{"cell_type":"code","execution_count":3,"metadata":{"cell_id":"176efbfea4b546d28d9d9966342f286a","deepnote_cell_type":"code","deepnote_to_be_reexecuted":false,"execution_millis":231,"execution_start":1697419710160,"source_hash":"1ce3848"},"outputs":[{"data":{"text/plain":["{'openapi': '3.0.0',\n"," 'info': {'version': '1.0.0',\n"," 'title': 'Event Management API',\n"," 'description': 'An API for managing event data'},\n"," 'paths': {'/events': {'get': {'summary': 'List all events',\n"," 'operationId': 'listEvents',\n"," 'responses': {'200': {'description': 'A list of events',\n"," 'content': {'application/json': {'schema': {'type': 'array',\n"," 'items': {'type': 'object',\n"," 'properties': {'id': {'type': 'string'},\n"," 'name': {'type': 'string'},\n"," 'date': {'type': 'string', 'format': 'date-time'},\n"," 'location': {'type': 'string'}},\n"," 'required': ['name', 'date', 'location']}}}}}}},\n"," 'post': {'summary': 'Create a new event',\n"," 'operationId': 'createEvent',\n"," 'requestBody': {'required': True,\n"," 'content': {'application/json': {'schema': {'type': 'object',\n"," 'properties': {'id': {'type': 'string'},\n"," 'name': {'type': 'string'},\n"," 'date': {'type': 'string', 'format': 'date-time'},\n"," 'location': {'type': 'string'}},\n"," 'required': ['name', 'date', 'location']}}}},\n"," 'responses': {'201': {'description': 'The event was created',\n"," 'content': {'application/json': {'schema': {'type': 'object',\n"," 'properties': {'id': {'type': 'string'},\n"," 'name': {'type': 'string'},\n"," 'date': {'type': 'string', 'format': 'date-time'},\n"," 'location': {'type': 'string'}},\n"," 'required': ['name', 'date', 'location']}}}}}}},\n"," '/events/{id}': {'get': {'summary': 'Retrieve an event by ID',\n"," 'operationId': 'getEventById',\n"," 'parameters': [{'name': 'id',\n"," 'in': 'path',\n"," 'required': True,\n"," 'schema': {'type': 'string'}}],\n"," 'responses': {'200': {'description': 'The event',\n"," 'content': {'application/json': {'schema': {'type': 'object',\n"," 'properties': {'id': {'type': 'string'},\n"," 'name': {'type': 'string'},\n"," 'date': {'type': 'string', 'format': 'date-time'},\n"," 'location': {'type': 'string'}},\n"," 'required': ['name', 'date', 'location']}}}}}},\n"," 'delete': {'summary': 'Delete an event by ID',\n"," 'operationId': 'deleteEvent',\n"," 'parameters': [{'name': 'id',\n"," 'in': 'path',\n"," 'required': True,\n"," 'schema': {'type': 'string'}}],\n"," 'responses': {'204': {'description': 'The event was deleted'}}},\n"," 'patch': {'summary': \"Update an event's details by ID\",\n"," 'operationId': 'updateEventDetails',\n"," 'parameters': [{'name': 'id',\n"," 'in': 'path',\n"," 'required': True,\n"," 'schema': {'type': 'string'}}],\n"," 'requestBody': {'required': True,\n"," 'content': {'application/json': {'schema': {'type': 'object',\n"," 'properties': {'name': {'type': 'string'},\n"," 'date': {'type': 'string', 'format': 'date-time'},\n"," 'location': {'type': 'string'}},\n"," 'required': ['name', 'date', 'location']}}}},\n"," 'responses': {'200': {'description': \"The event's details were updated\",\n"," 'content': {'application/json': {'schema': {'type': 'object',\n"," 'properties': {'id': {'type': 'string'},\n"," 'name': {'type': 'string'},\n"," 'date': {'type': 'string', 'format': 'date-time'},\n"," 'location': {'type': 'string'}},\n"," 'required': ['name', 'date', 'location']}}}}}}}},\n"," 'components': {'schemas': {'Event': {'type': 'object',\n"," 'properties': {'id': {'type': 'string'},\n"," 'name': {'type': 'string'},\n"," 'date': {'type': 'string', 'format': 'date-time'},\n"," 'location': {'type': 'string'}},\n"," 'required': ['name', 'date', 'location']}}}}"]},"metadata":{},"output_type":"display_data"}],"source":["with open('./data/example_events_openapi.json', 'r') as f:\n"," openapi_spec = jsonref.loads(f.read()) # it's important to load with jsonref, as explained below\n","\n","display(openapi_spec)"]},{"attachments":{},"cell_type":"markdown","metadata":{"cell_id":"e3e39ad4ac854299bf62b5f7bb1bef45","deepnote_cell_type":"text-cell-p","formattedRanges":[]},"source":["Now that we have a good understanding of the OpenAPI spec, we can proceed to parse it into function specifications.\n","\n","We can write a simple `openapi_to_functions` function to generate a list of definitions, where each function is represented as a dictionary containing the following keys:\n","\n","- `name`: This corresponds to the operation identifier of the API endpoint as defined in the OpenAPI specification.\n","- `description`: This is a brief description or summary of the function, providing an overview of what the function does.\n","- `parameters`: This is a schema that defines the expected input parameters for the function. It provides information about the type of each parameter, whether it is required or optional, and other related details.\n","\n","For each of the endpoints defined in the schema, we need to do the following:\n","\n","1. **Resolve JSON references**: In an OpenAPI specification, it's common to use JSON references (also known as $ref) to avoid duplication. These references point to definitions that are used in multiple places. For example, if multiple API endpoints return the same object structure, that structure can be defined once and then referenced wherever it's needed. We need to resolve and replace these references with the content they point to.\n","\n","2. **Extract a name for the functions:** We will simply use the operationId as the function name. Alternatively, we could use the endpoint path and operation as the function name.\n","\n","3. **Extract a description and parameters:** We will iterate through the `description`, `summary`, `requestBody` and `parameters` fields to populate the function's description and parameters.\n","\n","Here's the implementation:\n"]},{"cell_type":"code","execution_count":9,"metadata":{"cell_id":"adbb17ca8a2a4fa2aa3f0213a0e211b6","deepnote_cell_type":"code","deepnote_to_be_reexecuted":false,"execution_millis":333,"execution_start":1697419853135,"source_hash":"ad112cb1"},"outputs":[{"name":"stdout","output_type":"stream","text":["{'type': 'function',\n"," 'function': {'name': 'listEvents',\n"," 'description': 'List all events',\n"," 'parameters': {'type': 'object', 'properties': {}}}}\n","\n","{'type': 'function',\n"," 'function': {'name': 'createEvent',\n"," 'description': 'Create a new event',\n"," 'parameters': {'type': 'object',\n"," 'properties': {'requestBody': {'type': 'object',\n"," 'properties': {'id': {'type': 'string'},\n"," 'name': {'type': 'string'},\n"," 'date': {'type': 'string',\n"," 'format': 'date-time'},\n"," 'location': {'type': 'string'}},\n"," 'required': ['name',\n"," 'date',\n"," 'location']}}}}}\n","\n","{'type': 'function',\n"," 'function': {'name': 'getEventById',\n"," 'description': 'Retrieve an event by ID',\n"," 'parameters': {'type': 'object',\n"," 'properties': {'parameters': {'type': 'object',\n"," 'properties': {'id': {'type': 'string'}}}}}}}\n","\n","{'type': 'function',\n"," 'function': {'name': 'deleteEvent',\n"," 'description': 'Delete an event by ID',\n"," 'parameters': {'type': 'object',\n"," 'properties': {'parameters': {'type': 'object',\n"," 'properties': {'id': {'type': 'string'}}}}}}}\n","\n","{'type': 'function',\n"," 'function': {'name': 'updateEventDetails',\n"," 'description': \"Update an event's details by ID\",\n"," 'parameters': {'type': 'object',\n"," 'properties': {'requestBody': {'type': 'object',\n"," 'properties': {'name': {'type': 'string'},\n"," 'date': {'type': 'string',\n"," 'format': 'date-time'},\n"," 'location': {'type': 'string'}},\n"," 'required': ['name',\n"," 'date',\n"," 'location']},\n"," 'parameters': {'type': 'object',\n"," 'properties': {'id': {'type': 'string'}}}}}}}\n","\n"]}],"source":["def openapi_to_functions(openapi_spec):\n"," functions = []\n","\n"," for path, methods in openapi_spec[\"paths\"].items():\n"," for method, spec_with_ref in methods.items():\n"," # 1. Resolve JSON references.\n"," spec = jsonref.replace_refs(spec_with_ref)\n","\n"," # 2. Extract a name for the functions.\n"," function_name = spec.get(\"operationId\")\n","\n"," # 3. Extract a description and parameters.\n"," desc = spec.get(\"description\") or spec.get(\"summary\", \"\")\n","\n"," schema = {\"type\": \"object\", \"properties\": {}}\n","\n"," req_body = (\n"," spec.get(\"requestBody\", {})\n"," .get(\"content\", {})\n"," .get(\"application/json\", {})\n"," .get(\"schema\")\n"," )\n"," if req_body:\n"," schema[\"properties\"][\"requestBody\"] = req_body\n","\n"," params = spec.get(\"parameters\", [])\n"," if params:\n"," param_properties = {\n"," param[\"name\"]: param[\"schema\"]\n"," for param in params\n"," if \"schema\" in param\n"," }\n"," schema[\"properties\"][\"parameters\"] = {\n"," \"type\": \"object\",\n"," \"properties\": param_properties,\n"," }\n","\n"," functions.append(\n"," {\"type\": \"function\", \"function\": {\"name\": function_name, \"description\": desc, \"parameters\": schema}}\n"," )\n","\n"," return functions\n","\n","\n","functions = openapi_to_functions(openapi_spec)\n","\n","for function in functions:\n"," pp(function)\n"," print()\n"]},{"attachments":{},"cell_type":"markdown","metadata":{"cell_id":"f03f1aacdade4ed9a422797d3cf79fbb","deepnote_cell_type":"text-cell-h2","formattedRanges":[]},"source":["## How to call these functions with GPT\n"]},{"attachments":{},"cell_type":"markdown","metadata":{"cell_id":"08712696b5fd4cafac7b4b496ee67c5a","deepnote_cell_type":"text-cell-p","formattedRanges":[]},"source":["Now that we have these function definitions, we can leverage GPT to call them intelligently based on user inputs.\n","\n","It's important to note that the chat completions API does not execute the function; instead, it generates the JSON that you can use to call the function in your own code.\n","\n","For more information on function-calling, refer to our dedicated [function-calling guide](./How_to_call_functions_with_chat_models.ipynb).\n"]},{"cell_type":"code","execution_count":23,"metadata":{"cell_id":"b8f7d0f157264694b958008f93aabf3f","deepnote_cell_type":"code","deepnote_to_be_reexecuted":false,"execution_millis":6442,"execution_start":1697419907347,"source_hash":"ac9ad493"},"outputs":[{"name":"stdout","output_type":"stream","text":["ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_jmlvEyMRMvOtB80adX9RbqIV', function=Function(arguments='{}', name='listEvents'), type='function')])\n","\n",">> Function call #: 1\n","\n","[ChatCompletionMessageToolCall(id='call_jmlvEyMRMvOtB80adX9RbqIV', function=Function(arguments='{}', name='listEvents'), type='function')]\n","ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_OOPOY7IHMq3T7Ib71JozlUQJ', function=Function(arguments='{\\n \"requestBody\": {\\n \"id\": \"1234\",\\n \"name\": \"AGI Party\",\\n \"date\": \"2022-12-31\",\\n \"location\": \"New York\"\\n }\\n}', name='createEvent'), type='function')])\n","\n",">> Function call #: 2\n","\n","[ChatCompletionMessageToolCall(id='call_OOPOY7IHMq3T7Ib71JozlUQJ', function=Function(arguments='{\\n \"requestBody\": {\\n \"id\": \"1234\",\\n \"name\": \"AGI Party\",\\n \"date\": \"2022-12-31\",\\n \"location\": \"New York\"\\n }\\n}', name='createEvent'), type='function')]\n","ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_Kxluu3fJSOsZNNCn3JIlWAAM', function=Function(arguments='{\\n \"parameters\": {\\n \"id\": \"2456\"\\n }\\n}', name='deleteEvent'), type='function')])\n","\n",">> Function call #: 3\n","\n","[ChatCompletionMessageToolCall(id='call_Kxluu3fJSOsZNNCn3JIlWAAM', function=Function(arguments='{\\n \"parameters\": {\\n \"id\": \"2456\"\\n }\\n}', name='deleteEvent'), type='function')]\n","ChatCompletionMessage(content='Here are the actions I performed:\\n\\n1. Retrieved all the events.\\n2. Created a new event named \"AGI Party\" with the ID \"1234\", scheduled for December 31, 2022, in New York.\\n3. Deleted the event with the ID \"2456\".', role='assistant', function_call=None, tool_calls=None)\n","\n",">> Function call #: 4\n","\n","None\n","\n",">> Message:\n","\n","Here are the actions I performed:\n","\n","1. Retrieved all the events.\n","2. Created a new event named \"AGI Party\" with the ID \"1234\", scheduled for December 31, 2022, in New York.\n","3. Deleted the event with the ID \"2456\".\n"]}],"source":["SYSTEM_MESSAGE = \"\"\"\n","You are a helpful assistant.\n","Respond to the following prompt by using function_call and then summarize actions.\n","Ask for clarification if a user request is ambiguous.\n","\"\"\"\n","\n","# Maximum number of function calls allowed to prevent infinite or lengthy loops\n","MAX_CALLS = 5\n","\n","\n","def get_openai_response(functions, messages):\n"," return client.chat.completions.create(\n"," model=\"gpt-3.5-turbo-16k\",\n"," tools=functions,\n"," tool_choice=\"auto\", # \"auto\" means the model can pick between generating a message or calling a function.\n"," temperature=0,\n"," messages=messages,\n"," )\n","\n","\n","def process_user_instruction(functions, instruction):\n"," num_calls = 0\n"," messages = [\n"," {\"content\": SYSTEM_MESSAGE, \"role\": \"system\"},\n"," {\"content\": instruction, \"role\": \"user\"},\n"," ]\n","\n"," while num_calls < MAX_CALLS:\n"," response = get_openai_response(functions, messages)\n"," message = response.choices[0].message\n"," print(message)\n"," try:\n"," print(f\"\\n>> Function call #: {num_calls + 1}\\n\")\n"," pp(message.tool_calls)\n"," messages.append(message)\n","\n"," # For the sake of this example, we'll simply add a message to simulate success.\n"," # Normally, you'd want to call the function here, and append the results to messages.\n"," messages.append(\n"," {\n"," \"role\": \"tool\",\n"," \"content\": \"success\",\n"," \"tool_call_id\": message.tool_calls[0].id,\n"," }\n"," )\n","\n"," num_calls += 1\n"," except:\n"," print(\"\\n>> Message:\\n\")\n"," print(message.content)\n"," break\n","\n"," if num_calls >= MAX_CALLS:\n"," print(f\"Reached max chained function calls: {MAX_CALLS}\")\n","\n","\n","USER_INSTRUCTION = \"\"\"\n","Instruction: Get all the events.\n","Then create a new event named AGI Party.\n","Then delete event with id 2456.\n","\"\"\"\n","\n","process_user_instruction(functions, USER_INSTRUCTION)\n"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["### Conclusion\n","\n","We have demonstrated how to convert OpenAPI specs into function specifications that can be given to GPT for it to intelligently call them, and shown how these can be chained together to perform complex operations.\n","\n","Possible extensions of this system could include handling more complex user instructions that require conditional logic or looping, integrating with real APIs to perform actual operations, and improving error handling and validation to ensure the instructions are feasible and the function calls are successful.\n"]}],"metadata":{"deepnote":{},"deepnote_execution_queue":[],"deepnote_notebook_id":"84d101406ec34e36a9cf96d0c0c25a7d","kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.11.5"},"orig_nbformat":2},"nbformat":4,"nbformat_minor":0}
diff --git a/examples/GPT_with_vision_for_video_understanding.ipynb b/examples/GPT_with_vision_for_video_understanding.ipynb
index e92d4a3f..3a1ed502 100644
--- a/examples/GPT_with_vision_for_video_understanding.ipynb
+++ b/examples/GPT_with_vision_for_video_understanding.ipynb
@@ -208,7 +208,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Now, we can work with the GPT-4o TTS model and provide it a set of instructions on how the voice should sound. You can play around with the voice models and instructers at [OpenAI.fm](openai.fm). We can then pass in the script we generated above with GPT-4.1-mini and generate audio of the voiceover:\n"
+ "Now, we can work with the GPT-4o TTS model and provide it a set of instructions on how the voice should sound. You can play around with the voice models and instructions at [OpenAI.fm](https://openai.fm). We can then pass in the script we generated above with GPT-4.1-mini and generate audio of the voiceover:\n"
]
},
{
diff --git a/examples/How_to_call_functions_with_chat_models.ipynb b/examples/How_to_call_functions_with_chat_models.ipynb
index af5cda94..9edb6c90 100644
--- a/examples/How_to_call_functions_with_chat_models.ipynb
+++ b/examples/How_to_call_functions_with_chat_models.ipynb
@@ -756,7 +756,7 @@
"source": [
"### Executing SQL queries\n",
"\n",
- "Now let's implement the function that will actually excute queries against the database."
+ "Now let's implement the function that will actually execute queries against the database."
]
},
{
diff --git a/examples/How_to_format_inputs_to_ChatGPT_models.ipynb b/examples/How_to_format_inputs_to_ChatGPT_models.ipynb
index d08fb9cc..ccc91eaa 100644
--- a/examples/How_to_format_inputs_to_ChatGPT_models.ipynb
+++ b/examples/How_to_format_inputs_to_ChatGPT_models.ipynb
@@ -480,7 +480,7 @@
"\n",
"As an example, one developer discovered an increase in accuracy when they inserted a user message that said \"Great job so far, these have been perfect\" to help condition the model into providing higher quality responses.\n",
"\n",
- "For more ideas on how to lift the reliability of the models, consider reading our guide on [techniques to increase reliability](../techniques_to_improve_reliability). It was written for non-chat models, but many of its principles still apply."
+ "For more ideas on how to lift the reliability of the models, consider reading our guide on [techniques to increase reliability](../articles/techniques_to_improve_reliability.md). It was written for non-chat models, but many of its principles still apply."
]
},
{
diff --git a/examples/How_to_use_moderation.ipynb b/examples/How_to_use_moderation.ipynb
index f01f5303..2ff3a22e 100644
--- a/examples/How_to_use_moderation.ipynb
+++ b/examples/How_to_use_moderation.ipynb
@@ -182,7 +182,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Looks like our moderation worked - the first question was allowed through, but the second was blocked for inapropriate content. Here is a similar example that works with images."
+ "Looks like our moderation worked - the first question was allowed through, but the second was blocked for inappropriate content. Here is a similar example that works with images."
]
},
{
diff --git a/examples/Leveraging_model_distillation_to_fine-tune_a_model.ipynb b/examples/Leveraging_model_distillation_to_fine-tune_a_model.ipynb
index 86f604cc..cb90f28f 100644
--- a/examples/Leveraging_model_distillation_to_fine-tune_a_model.ipynb
+++ b/examples/Leveraging_model_distillation_to_fine-tune_a_model.ipynb
@@ -63,11 +63,11 @@
"\n",
"For this cookbook, we'll load the data from the following Kaggle challenge: [https://www.kaggle.com/datasets/zynicide/wine-reviews](https://www.kaggle.com/datasets/zynicide/wine-reviews).\n",
"\n",
- "This dataset has a large number of rows and you're free to run this cookbook on the whole data, but as a biaised french wine-lover, I'll narrow down the dataset to only French wine to focus on less rows and grape varieties.\n",
+ "This dataset has many rows, and you can run this cookbook on the full dataset. As a biased French wine lover, I'll narrow the dataset to French wines so that we can focus on fewer rows and grape varieties.\n",
"\n",
- "We're looking at a classification problem where we'd like to guess the grape variety based on all other criterias available, including description, subregion and province that we'll include in the prompt. It gives a lot of information to the model, you'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.\n",
+ "We're looking at a classification problem where we'd like to predict the grape variety from the available criteria, including the description, subregion, and province, which we'll include in the prompt. This gives the model a lot of information. You can remove information that would make the task significantly easier, such as the region where the grape was produced, to see how well the model predicts the variety.\n",
"\n",
- "Let's filter the grape varieties that have less than 5 occurences in reviews.\n",
+ "Let's filter the grape varieties that have fewer than five occurrences in reviews.\n",
"\n",
"Let's proceed with a subset of 500 random rows from this dataset."
]
diff --git a/examples/Optimize_Prompts.ipynb b/examples/Optimize_Prompts.ipynb
index b87bf5fe..0d2e07f2 100644
--- a/examples/Optimize_Prompts.ipynb
+++ b/examples/Optimize_Prompts.ipynb
@@ -813,7 +813,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "This is particularly important because few-shot examples have a strong influence on how models respond. If examples don't follow the stated rules, the model may learn to ignore those rules in favor of mimicking the examples. By ensuring consistency between the prompt instructions and examples, the optimization system creats a more reliable prompt."
+ "This is particularly important because few-shot examples have a strong influence on how models respond. If examples don't follow the stated rules, the model may learn to ignore those rules in favor of mimicking the examples. By ensuring consistency between the prompt instructions and examples, the optimization system creates a more reliable prompt."
]
},
{
diff --git a/examples/Orchestrating_agents.ipynb b/examples/Orchestrating_agents.ipynb
index 9d28f87c..b0705ccd 100644
--- a/examples/Orchestrating_agents.ipynb
+++ b/examples/Orchestrating_agents.ipynb
@@ -46,7 +46,7 @@
"source": [
"# Routines\n",
"\n",
- "The notion of a \"routine\" is not strictly defined, and instead meant to capture the idea of a set of steps. Concretely, let's define a routine to be a list of instructions in natural langauge (which we'll represent with a system prompt), along with the tools necessary to complete them.\n",
+ "The notion of a \"routine\" is not strictly defined, and instead meant to capture the idea of a set of steps. Concretely, let's define a routine to be a list of instructions in natural language (which we'll represent with a system prompt), along with the tools necessary to complete them.\n",
"\n",
"\n",
"\n",
@@ -91,7 +91,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "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 \"soft\" adherance – the LLM can naturally steer the conversation without getting stuck in dead-ends.\n",
+ "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 routines, with the added benefit of \"soft\" adherence – the LLM can naturally steer the conversation without getting stuck in dead-ends.\n",
"\n"
]
},
@@ -438,7 +438,7 @@
"source": [
"# Handoffs\n",
"\n",
- "Let'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!\n",
+ "Let's define a **handoff** as an agent (or routine) handing off an active conversation to another agent, much like when you get transferred to someone else on a phone call. Except in this case, the agents have complete knowledge of your prior conversation!\n",
"\n",
"To see handoffs in action, let's start by defining a basic class for an Agent."
]
diff --git a/examples/Question_answering_using_embeddings.ipynb b/examples/Question_answering_using_embeddings.ipynb
index c7cf8a68..f095d7c7 100644
--- a/examples/Question_answering_using_embeddings.ipynb
+++ b/examples/Question_answering_using_embeddings.ipynb
@@ -215,7 +215,7 @@
"id": "1af18d66-d47a-496d-ae5f-4c5d53caa434",
"metadata": {},
"source": [
- "In this case, the model has no knowledge of 2024 and is unable to answer the question. In a similar way, if you ask a question pertaining to a recent political event (that occured in Nov 2024 for example), GPT-4o-mini models will not be able to answer due to its knowledge cut-off date of Oct 2023. "
+ "In this case, the model has no knowledge of 2024 and is unable to answer the question. In a similar way, if you ask a question pertaining to a recent political event (that occurred in Nov 2024 for example), GPT-4o-mini models will not be able to answer due to their knowledge cutoff date of Oct 2023. "
]
},
{
diff --git a/examples/Realtime_prompting_guide.ipynb b/examples/Realtime_prompting_guide.ipynb
index e3322a09..e14547d5 100644
--- a/examples/Realtime_prompting_guide.ipynb
+++ b/examples/Realtime_prompting_guide.ipynb
@@ -788,7 +788,7 @@
"id": "f5bc3747",
"metadata": {},
"source": [
- "*Tip: If you are following a conversation flow prompting strategy, you can specify which conversation state needs to apply the alpha-numeric pronunciations instruction.*\n",
+ "*Tip: If you are following a conversation flow prompting strategy, you can specify which conversation state needs to apply the alphanumeric pronunciations instruction.*\n",
"\n",
"### Example (instruction in conversation state)\n",
"*(taken from the conversation flow of the prompt of our [openai-realtime-agents](https://github.com/openai/openai-realtime-agents/blob/main/src/app/agentConfigs/customerServiceRetail/authentication.ts))*\n",
diff --git a/examples/Recommendation_using_embeddings.ipynb b/examples/Recommendation_using_embeddings.ipynb
index bd3f33a9..7e8c4fe7 100644
--- a/examples/Recommendation_using_embeddings.ipynb
+++ b/examples/Recommendation_using_embeddings.ipynb
@@ -204,7 +204,7 @@
"source": [
"### 3. Build cache to save embeddings\n",
"\n",
- "Before getting embeddings for these articles, let's set up a cache to save the embeddings we generate. In general, it's a good idea to save your embeddings so you can re-use them later. If you don't save them, you'll pay again each time you compute them again.\n",
+ "Before getting embeddings for these articles, let's set up a cache to save the embeddings we generate. In general, it's a good idea to save your embeddings so you can reuse them later. If you don't save them, you'll pay each time you recompute them.\n",
"\n",
"The cache is a dictionary that maps tuples of `(text, model)` to an embedding, which is a list of floats. The cache is saved as a Python pickle file."
]
diff --git a/examples/Reinforcement_Fine_Tuning.ipynb b/examples/Reinforcement_Fine_Tuning.ipynb
index 87d359d8..39bb10ae 100644
--- a/examples/Reinforcement_Fine_Tuning.ipynb
+++ b/examples/Reinforcement_Fine_Tuning.ipynb
@@ -8,10 +8,10 @@
"\n",
"*This guide is for developers and ML practitioners who already know their way around OpenAIʼs APIs, have a basic understanding of reinforcement fine-tuning (RFT), and wish to use their fine-tuned models for research or other appropriate uses. OpenAI’s services are not intended for the personalized treatment or diagnosis of any medical condition and are subject to our [applicable terms](https://openai.com/policies/).*\n",
"\n",
- "[Reinforcement fine-tuning (RFT)](https://platform.openai.com/docs/guides/reinforcement-fine-tuning) of reasoning models consists in running reinforcement learning on of top the models to improve their reasoning performance by exploring the solution space and reinforcing strategies that result in a higher reward. RFT helps the model make sharper decisions and interpret context more effectively. \n",
+ "[Reinforcement fine-tuning (RFT)](https://platform.openai.com/docs/guides/reinforcement-fine-tuning) of reasoning models consists of running reinforcement learning on top of the models to improve their reasoning performance by exploring the solution space and reinforcing strategies that result in a higher reward. RFT helps the model make sharper decisions and interpret context more effectively. \n",
"\n",
"\n",
- "In this guide, weʼll walk through how to apply RFT to the OpenAI `o4-mini` reasoning model, using a task from the life sciences research domain: predicting outcomes from doctor-patient transcripts and descriptions, which is a necessary assessment in many health research studies. We'll use a subset of the medical-o1-verifiable-problem [dataset](https://huggingface.co/datasets/FreedomIntelligence/medical-o1-verifiable-problem/viewer/default/train?row=0). You will learn key steps to take in order to succesfully run RFT jobs for your use-cases.\n",
+ "In this guide, weʼll walk through how to apply RFT to the OpenAI `o4-mini` reasoning model, using a task from the life sciences research domain: predicting outcomes from doctor-patient transcripts and descriptions, which is a necessary assessment in many health research studies. We'll use a subset of the medical-o1-verifiable-problem [dataset](https://huggingface.co/datasets/FreedomIntelligence/medical-o1-verifiable-problem/viewer/default/train?row=0). You will learn key steps to take in order to successfully run RFT jobs for your use cases.\n",
"\n",
"Here’s what we’ll cover:\n",
"\n",
@@ -247,9 +247,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "This combination lets us track both strict correctness and partial lexical overlap. The binary grader gives a crisp 0 or 1: did the model produce an exact match? The softer one gives more nuance-how close did the output come to the gold answer? We use both because outcomes are often phrased in multiple valid ways. For instance, a model might respond with “gouty arthritis” instead of “gout.” While a human evaluator could consider this partially acceptable, a strict string match would not. Combining exact and fuzzy scoring ensures a more accurate and fair assessment of model outputs. \n",
+ "This combination lets us track both strict correctness and partial lexical overlap. The binary grader gives a crisp 0 or 1: did the model produce an exact match? The softer one gives more nuance—how close did the output come to the gold answer? We use both because outcomes are often phrased in multiple valid ways. For instance, a model might respond with “gouty arthritis” instead of “gout.” While a human evaluator could consider this partially acceptable, a strict string match would not. Combining exact and fuzzy scoring ensures a more accurate and fair assessment of model outputs. \n",
"\n",
- "We build a helper function to preprend the examples with a system prompt."
+ "We build a helper function to prepend the examples with a system prompt."
]
},
{
@@ -975,7 +975,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Here is a snapshot of its training curves, where the green curve is the traning set reward and the blue curve is the test set reward:\n",
+ "Here is a snapshot of its training curves, where the green curve is the training set reward and the blue curve is the test set reward:\n",
"\n",
"![RFT String Grader](../images/rft_string_grader.png)"
]
@@ -1523,7 +1523,7 @@
"source": [
"On the [dashboard](https://platform.openai.com/finetune/) you can observe the reward plots - they let you watch overall performance improve across steps, while the per-grader charts break down specific components in the case of a *multi_grader*. Reasoning token usage trends (often decreasing as the model gets more confident) and step duration metrics give insight into efficiency. Grader latency and error count plots help ensure your grader stays performant and bug-free during the run.\n",
"\n",
- "Here is a snapshot of our training curves, where the green and orange curves are for the training set, while tbe blue and red curves are for the test subset:\n",
+ "Here is a snapshot of our training curves, where the green and orange curves are for the training set, while the blue and red curves are for the test subset:\n",
"\n",
"![RFT Dashboard Example](../images/rft_dashboard_modelgrader2.png)\n",
"\n",
diff --git a/examples/SDG1.ipynb b/examples/SDG1.ipynb
index bdf22886..da259886 100644
--- a/examples/SDG1.ipynb
+++ b/examples/SDG1.ipynb
@@ -2130,7 +2130,7 @@
"* Simply creating textual data\n",
"* Dealing with imbalanced or non-diverse textual data\n",
"\n",
- "In part 2 you will find find out techniques for better prompting an LLM to enhance textual synthetic data generation."
+ "In part 2 you will find out techniques for better prompting an LLM to enhance textual synthetic data generation."
]
},
{
diff --git a/examples/Search_reranking_with_cross-encoders.ipynb b/examples/Search_reranking_with_cross-encoders.ipynb
index 0fa0db7d..e4eeb9f2 100644
--- a/examples/Search_reranking_with_cross-encoders.ipynb
+++ b/examples/Search_reranking_with_cross-encoders.ipynb
@@ -19,7 +19,7 @@
"\n",
"The brute force approach of computing every pairwise relevance is expensive; its cost scales as ```D * Q```. This is known as **cross-encoding**.\n",
"\n",
- "A faster approach is **embeddings-based search**, in which an embedding is computed once for each document and query, and then re-used multiple times to cheaply compute pairwise relevance. Because embeddings are only computed once, its cost scales as ```D + Q```. This is known as **bi-encoding**.\n",
+ "A faster approach is **embeddings-based search**, in which an embedding is computed once for each document and query, and then reused multiple times to cheaply compute pairwise relevance. Because embeddings are only computed once, its cost scales as ```D + Q```. This is known as **bi-encoding**.\n",
"\n",
"Although embeddings-based search is faster, the quality can be worse. To get the best of both, one common approach is to use embeddings (or another bi-encoder) to cheaply identify top candidates, and then use GPT (or another cross-encoder) to expensively re-rank those top candidates. The cost of this hybrid approach scales as ```(D + Q) * cost of embedding + (N * Q) * cost of re-ranking```, where ```N``` is the number of candidates re-ranked.\n",
"\n",
diff --git a/examples/Using_logprobs.ipynb b/examples/Using_logprobs.ipynb
index e3aa394f..55e3e22a 100644
--- a/examples/Using_logprobs.ipynb
+++ b/examples/Using_logprobs.ipynb
@@ -7,40 +7,31 @@
"# Using logprobs for classification and Q&A evaluation\n",
"\n",
"This notebook demonstrates the use of the `logprobs` parameter in the Chat Completions API. When `logprobs` is enabled, the API returns the log probabilities of each output token, along with a limited number of the most likely tokens at each token position and their log probabilities. The relevant request parameters are:\n",
- "* `logprobs`: Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the content of message.\n",
- "* `top_logprobs`: An integer between 0 and 5 specifying the number of most likely tokens to return at each token position, each with an associated log probability. `logprobs` must be set to true if this parameter is used.\n",
+ "* `logprobs`: Whether to return log probabilities for the output tokens. If `true`, the response includes the log probability of each token in the message content.\n",
+ "* `top_logprobs`: An integer between 0 and 5 specifying the number of most likely tokens to return at each token position, each with an associated log probability. `logprobs` must be set to `true` if this parameter is used.\n",
"\n",
"Log probabilities of output tokens indicate the likelihood of each token occurring in the sequence given the context. To simplify, a logprob is `log(p)`, where `p` = probability of a token occurring at a specific position based on the previous tokens in the context. Some key points about `logprobs`:\n",
"* Higher log probabilities suggest a higher likelihood of the token in that context. This allows users to gauge the model's confidence in its output or explore alternative responses the model considered.\n",
"* Logprob can be any negative number or `0.0`. `0.0` corresponds to 100% probability.\n",
- "* Logprobs allow us to compute the joint probability of a sequence as the sum of the logprobs of the individual tokens. This is useful for scoring and ranking model outputs. Another common approach is to take the average per-token logprob of a sentence to choose the best generation.\n",
+ "* Logprobs allow us to compute the joint log probability of a sequence by summing the logprobs of its tokens. Exponentiating that sum gives the joint probability. This is useful for scoring and ranking model outputs. Another common approach is to take the average per-token logprob of a sentence to choose the best generation.\n",
"* We can examine the `logprobs` assigned to different candidate tokens to understand what options the model considered plausible or implausible.\n",
"\n",
"While there are a wide array of use cases for `logprobs`, this notebook will focus on its use for:\n",
"\n",
- "1. Classification tasks\n",
- "\n",
- "* Large Language Models excel at many classification tasks, but accurately measuring the model's confidence in its outputs can be challenging. `logprobs` provide a probability associated with each class prediction, enabling users to set their own classification or confidence thresholds.\n",
- "\n",
- "2. Retrieval (Q&A) evaluation\n",
- "\n",
- "* `logprobs` can assist with self-evaluation in retrieval applications. In the Q&A example, the model outputs a contrived `has_sufficient_context_for_answer` boolean, which can serve as a confidence score of whether the answer is contained in the retrieved content. Evaluations of this type can reduce retrieval-based hallucinations and enhance accuracy.\n",
- "\n",
- "3. Autocomplete\n",
- "* `logprobs` could help us decide how to suggest words as a user is typing.\n",
- "\n",
- "4. Token highlighting and outputting bytes\n",
- "* Users can easily create a token highlighter using the built in tokenization that comes with enabling `logprobs`. Additionally, the bytes parameter includes the ASCII encoding of each output character, which is particularly useful for reproducing emojis and special characters.\n",
- "\n",
- "5. Calculating perplexity\n",
- "* `logprobs` can be used to help us assess the model's overall confidence in a result and help us compare the confidence of results from different prompts."
+ "1. **Classification tasks:** Large language models excel at many classification tasks, but accurately measuring the model's confidence in its outputs can be challenging. `logprobs` provide a probability associated with each class prediction, enabling users to set classification or confidence thresholds.\n",
+ "2. **Retrieval (Q&A) evaluation:** `logprobs` can assist with self-evaluation in retrieval applications. In the Q&A example, the model outputs a contrived `has_sufficient_context_for_answer` boolean, which can serve as a confidence score for whether the answer is contained in the retrieved content. Evaluations of this type can reduce retrieval-based hallucinations and enhance accuracy.\n",
+ "3. **Autocomplete:** `logprobs` could help us decide when to suggest words as a user is typing.\n",
+ "4. **Token highlighting and outputting bytes:** Users can create a token highlighter using the built-in tokenization that comes with enabling `logprobs`. The `bytes` field also contains the UTF-8 byte values for each output token, which is particularly useful for reproducing emojis and special characters.\n",
+ "5. **Calculating perplexity:** `logprobs` can help us assess the model's overall confidence in a result and compare the confidence of results from different prompts."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "## 0. Imports and utils"
+ "## 0. Imports and utilities\n",
+ "\n",
+ "Set the `OPENAI_API_KEY` environment variable before running this notebook."
]
},
{
@@ -186,7 +177,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Here we can see the selected category for each headline. However, we have no visibility into the confidence of the model in its predictions. Let's rerun the same prompt but with `logprobs` enabled, and `top_logprobs` set to 2 (this will show us the 2 most likely output tokens for each token). Additionally we can also output the linear probability of each output token, in order to convert the log probability to the more easily interprable scale of 0-100%. "
+ "Here we can see the selected category for each headline. However, we have no visibility into the model's confidence in its predictions. Let's rerun the same prompt with `logprobs` enabled and `top_logprobs` set to 2, which shows the two most likely output tokens at each position. We can also convert each log probability into a linear probability on a more interpretable 0–100% scale."
]
},
{
@@ -308,7 +299,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "To reduce hallucinations, and the performance of our RAG-based Q&A system, we can use `logprobs` to evaluate how confident the model is in its retrieval."
+ "To reduce hallucinations and improve a RAG-based Q&A system, we can use `logprobs` to evaluate whether the model believes it has sufficient retrieved context."
]
},
{
@@ -350,7 +341,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Now, what we can do is ask the model to respond to the question, but then also evaluate its response. Specifically, we will ask the model to output a boolean `has_sufficient_context_for_answer`. We can then evaluate the `logprobs` to see just how confident the model is that its answer was contained in the provided context"
+ "Now, we can ask the model to evaluate whether the provided context is sufficient for a question. Specifically, we will ask the model to output a boolean `has_sufficient_context_for_answer`. We can then evaluate the `logprobs` to see how confident the model is in that classification."
]
},
{
@@ -432,9 +423,11 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "For the first two questions, our model asserts with (near) 100% confidence that the article has sufficient context to answer the posed questions.<br><br>\n",
- "On the other hand, for the more tricky questions which are less clearly answered in the article, the model is less confident that it has sufficient context. This is a great guardrail to help ensure our retrieved content is sufficient.<br><br>\n",
- "This self-evaluation can help reduce hallucinations, as you can restrict answers or re-prompt the user when your `sufficient_context_for_answer` log probability is below a certain threshold. Methods like this have been shown to significantly reduce RAG for Q&A hallucinations and errors ([Example](https://jfan001.medium.com/how-we-cut-the-rate-of-gpt-hallucinations-from-20-to-less-than-2-f3bfcc10e4ec)) "
+ "For the first two questions, the model returns `True` with nearly 100% confidence that the article contains sufficient context.\n",
+ "\n",
+ "For the partially covered questions, the model is also highly confident: it returns `False` with 99.14% probability for the Charles Dickens question and `True` with 99.59% probability for the Charles Babbage question. This shows that confidence measures certainty in the classification, not whether the classification is correct.\n",
+ "\n",
+ "This self-evaluation can serve as a guardrail, but validate its classifications and thresholds with task-specific evals before using it to restrict answers or ask follow-up questions. For an example of a related approach, see [How we cut the rate of GPT hallucinations](https://jfan001.medium.com/how-we-cut-the-rate-of-gpt-hallucinations-from-20-to-less-than-2-f3bfcc10e4ec)."
]
},
{
@@ -448,7 +441,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Another use case for `logprobs` are autocomplete systems. Without creating the entire autocomplete system end-to-end, let's demonstrate how `logprobs` could help us decide how to suggest words as a user is typing."
+ "Another use case for `logprobs` is autocomplete. Without creating an entire autocomplete system, let's demonstrate how `logprobs` could help us decide when to suggest words as a user is typing."
]
},
{
@@ -601,7 +594,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Let's quickly touch on creating a simple token highlighter with `logprobs`, and using the bytes parameter. First, we can create a function that counts and highlights each token. While this doesn't use the log probabilities, it uses the built in tokenization that comes with enabling `logprobs`."
+ "Let's create a simple token highlighter with `logprobs` and use the `bytes` field. First, we can create a function that counts and highlights each token. While this doesn't use the log probabilities, it uses the built-in tokenization that comes with enabling `logprobs`."
]
},
{
@@ -674,7 +667,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Next, let's reconstruct a sentence using the bytes parameter. With `logprobs` enabled, we are given both each token and the ASCII (decimal utf-8) values of the token string. These ASCII values can be helpful when handling tokens of or containing emojis or special characters."
+ "Next, let's reconstruct a sentence using the `bytes` field. With `logprobs` enabled, the response includes each token and the UTF-8 byte values for its text. These byte values are helpful when tokens contain emojis or other special characters."
]
},
{
@@ -800,9 +793,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Here, we see that while the first token was `\\xf0\\x9f\\x92'`, we can get its ASCII value and append it to a bytes array. Then, we can easily decode this array into a full sentence, and validate with our assert statement that the decoded bytes is the same as our completion message!\n",
+ "Here, the emoji is split across two tokens whose byte values combine into its UTF-8 sequence. By appending all token bytes to an array, we can decode the array into the full sentence and assert that it matches the completion message.\n",
"\n",
- "Additionally, we can get the joint probability of the entire completion, which is the exponentiated product of each token's log probability. This gives us how `likely` this given completion is given the prompt. Since, our prompt is quite directive (asking for a certain emoji and its name), the joint probability of this output is high! If we ask for a random output however, we'll see a much lower joint probability. This can also be a good tactic for developers during prompt engineering. "
+ "We can also calculate the joint probability of the completion by summing the token log probabilities and exponentiating the result. This indicates how likely the full completion is for the prompt. Because this prompt is directive, asking for a specific emoji and its name, the joint probability is high. A less constrained prompt may produce a lower joint probability, which can be a useful signal during prompt engineering."
]
},
{
diff --git a/examples/Visualizing_embeddings_in_3D.ipynb b/examples/Visualizing_embeddings_in_3D.ipynb
index 50f183c3..dc2d50dd 100644
--- a/examples/Visualizing_embeddings_in_3D.ipynb
+++ b/examples/Visualizing_embeddings_in_3D.ipynb
@@ -14,7 +14,7 @@
"id": "9c9ea9a8-675d-4e3a-a8f7-6f4563df84ad",
"metadata": {},
"source": [
- "The example uses [PCA](https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html) to reduce the dimensionality fo the embeddings from 1536 to 3. Then we can visualize the data points in a 3D plot. The small dataset `dbpedia_samples.jsonl` is curated by randomly sampling 200 samples from [DBpedia validation dataset](https://www.kaggle.com/danofer/dbpedia-classes?select=DBPEDIA_val.csv)."
+ "The example uses [PCA](https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html) to reduce the dimensionality of the embeddings from 1536 to 3. Then we can visualize the data points in a 3D plot. The small dataset `dbpedia_samples.jsonl` is curated by randomly sampling 200 samples from [DBpedia validation dataset](https://www.kaggle.com/danofer/dbpedia-classes?select=DBPEDIA_val.csv)."
]
},
{
diff --git a/examples/Whisper_correct_misspelling.ipynb b/examples/Whisper_correct_misspelling.ipynb
index 8de1eb4c..ce16796e 100644
--- a/examples/Whisper_correct_misspelling.ipynb
+++ b/examples/Whisper_correct_misspelling.ipynb
@@ -15,7 +15,7 @@
"\n",
"- We utilized GPT-4 to fix misspellings post transcription, again using the same list of correct spellings in the prompt.\n",
"\n",
- "These strategies aimed at ensuring precise transcription of unfamilar proper nouns.\n",
+ "These strategies aimed at ensuring precise transcription of unfamiliar proper nouns.\n",
"\n",
"## Setup\n",
"\n",
diff --git a/examples/agents_sdk/app_assistant_voice_agents.ipynb b/examples/agents_sdk/app_assistant_voice_agents.ipynb
index 0f9b2f64..533626f9 100644
--- a/examples/agents_sdk/app_assistant_voice_agents.ipynb
+++ b/examples/agents_sdk/app_assistant_voice_agents.ipynb
@@ -13,8 +13,8 @@
"Fortunately for you, three recent releases from OpenAI have made implementing this vision simpler than ever by providing the tools to build and orchestrate modular agentic workflows through voice with minimal configuration:\n",
"\n",
"- [**Responses API**](https://platform.openai.com/docs/api-reference/responses) - an agentic API for easy engagement with our frontier models through managed stateful conversations, tracing of responses to enable evaluation, and built-in tools for file search, web search, computer use, and more\n",
- "- [**Agents SDK**](https://openai.github.io/openai-agents-python/quickstart/) - a lightweight, customizable open source framework for building and orchestrating workflows across many different agents, enabling your assistant to route inputs to the appropriate agent and to scale to support many use cases\n",
- "- [**Voice agents**](https://openai.github.io/openai-agents-python/voice/quickstart/) - an extension of the Agents SDK to support the use of voice pipelines, enabling your agents to go from being text-base to being able to interpret and produce audio in just a few lines of code\n",
+ "- [**Agents SDK**](https://openai.github.io/openai-agents-python/quickstart/) - a lightweight, customizable open-source framework for building and orchestrating workflows across many different agents, enabling your assistant to route inputs to the appropriate agent and to scale to support many use cases\n",
+ "- [**Voice agents**](https://openai.github.io/openai-agents-python/voice/quickstart/) - an extension of the Agents SDK to support the use of voice pipelines, enabling your agents to go from being text-based to being able to interpret and produce audio in just a few lines of code\n",
"\n",
"This cookbook demonstrates how to build a simple in-app voice assistant for a fictitious consumer application using the tools above. We'll create a **Triage Agent** that greets the user, determines their intent, and routes requests to one of three specialised agents:\n",
"\n",
@@ -22,7 +22,7 @@
"- **Knowledge Agent** - utilises the file search tooling of the Responses API to retrieve information from an OpenAI managed vector database\n",
"- **Account Agent** - uses function calling to provide the ability to trigger custom actions via API\n",
"\n",
- "Finally, we'll convert this workflow into a live voice assistant using the AgentsSDK's Voice funtionality, capturing microphone input, performing speech‑to‑text, routing through our agents, and responding with text‑to‑speech."
+ "Finally, we'll convert this workflow into a live voice assistant using the Agents SDK's Voice functionality, capturing microphone input, performing speech‑to‑text, routing through our agents, and responding with text‑to‑speech."
]
},
{
@@ -63,15 +63,15 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "# Defining Agents & Tools\n",
+ "# Define agents and tools\n",
"\n",
- "Today we're going to be building an assitant for our fictitious consumer application, ACME shop, focussed on initially supporting use cases across three key use cases:\n",
+ "Today we're going to be building an assistant for our fictitious consumer application, ACME shop, focused on initially supporting three key use cases:\n",
"\n",
"- Answering real-time questions to inform purchasing decisions using web search\n",
"- Providing information on the available options in our product portfolio\n",
"- Providing account information to enable the user to understand their budget and spending\n",
"\n",
- "To achieve this we'll be using an agentic architecture. This allows us to split the functionality for each use case into a separate agent, in turn reducing the complexity/range of tasks that a single agent could be asked to complete and increasing accuracy. Our agent architecture is relatively simple focussing on the three use cases above, but the beauty of the Agents SDK is that it is incredibly easy to extend and add aditional agents to the workflow when you want to add new functionality:\n",
+ "To achieve this we'll be using an agentic architecture. This allows us to split the functionality for each use case into a separate agent, in turn reducing the complexity/range of tasks that a single agent could be asked to complete and increasing accuracy. Our agent architecture is relatively simple focussing on the three use cases above, but the beauty of the Agents SDK is that it is incredibly easy to extend and add additional agents to the workflow when you want to add new functionality:\n",
"\n",
"![Agent Architecture](../../images/app_assistant_voice_agents_arch.png)\n",
"\n"
@@ -377,7 +377,7 @@
"\n",
"Having designed our workflow, here in reality we would spend time evaluating the traces and iterating on the workflow to ensure it is as effective as possible. But let's assume we're happy with the workflow, so we can now start thinking about how to convert our in-app assistant from text-based to voice-based interactions.\n",
"\n",
- "To do this, we can simply leverage the classes provided by the [Agents SDK](https://openai.github.io/openai-agents-python/voice/quickstart/) to convert our text-based workflow into a a voice-based one. The `VoicePipeline` class provides an interface for transcribing audio input, executing a given agent workflow and generating a text to speech response for playback to the user, whilst the `SingleAgentVoiceWorkflow` class enables us to leverage the same agent workflow we used earlier for our text-based workflow. To provide and receive audio, we'll use the `sounddevice` library. \n",
+ "To do this, we can simply leverage the classes provided by the [Agents SDK](https://openai.github.io/openai-agents-python/voice/quickstart/) to convert our text-based workflow into a voice-based one. The `VoicePipeline` class provides an interface for transcribing audio input, executing a given agent workflow and generating a text-to-speech response for playback to the user, while the `SingleAgentVoiceWorkflow` class enables us to leverage the same agent workflow we used earlier for our text-based workflow. To provide and receive audio, we'll use the `sounddevice` library. \n",
"\n",
"End to end, the new workflow looks like this:\n",
"\n",
@@ -462,7 +462,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Executing the above code, gives us the following responses which correctly provide the same functionality as the text-based workflow."
+ "Executing the above code gives us the following responses which correctly provide the same functionality as the text-based workflow."
]
},
{
@@ -544,7 +544,7 @@
"source": [
"# Optimizing Voice\n",
"\n",
- "This is a great start, but we can do better. As we've simply converted our text-based agents into voice-based ones, the responses are not optimised in their output for either tone or format, meaning they feel robotic and unnatural.\n",
+ "This is a great start, but we can do better. As we've simply converted our text-based agents into voice-based ones, the responses are not optimized in their output for either tone or format, meaning they feel robotic and unnatural.\n",
"\n",
"To address this, we'll need to make a few changes to our prompts.\n",
"\n",
diff --git a/examples/agents_sdk/context_personalization.ipynb b/examples/agents_sdk/context_personalization.ipynb
index c6e5436d..161a7bdf 100644
--- a/examples/agents_sdk/context_personalization.ipynb
+++ b/examples/agents_sdk/context_personalization.ipynb
@@ -1120,7 +1120,7 @@
"id": "ca574df5",
"metadata": {},
"source": [
- "**Tip:** If user provides a new value for one of the fields in the profile, you can prompt the agent to use that as the latest information in the presedence rules for resolving the conflict."
+ "**Tip:** If a user provides a new value for one of the fields in the profile, you can prompt the agent to use that as the latest information in the precedence rules for resolving the conflict."
]
},
{
@@ -1644,7 +1644,7 @@
"id": "6231ae7d",
"metadata": {},
"source": [
- "**Tip:** You can build specific evals spesifically for this step to keep track of average numbers of consolidated/pruned memories to tune the consolidation aggresiveness over time."
+ "**Tip:** You can build specific evals specifically for this step to keep track of average number of consolidated or pruned memories to tune the consolidation aggressiveness over time."
]
},
{
diff --git a/examples/agents_sdk/evaluate_agents.ipynb b/examples/agents_sdk/evaluate_agents.ipynb
index 26d0fd17..4cf4612d 100644
--- a/examples/agents_sdk/evaluate_agents.ipynb
+++ b/examples/agents_sdk/evaluate_agents.ipynb
@@ -137,7 +137,7 @@
"id": "IWr-MQY7hKdM"
},
"source": [
- "Pydantic Logfire offers an instrumentation for the OpenAi Agent SDK. We use this to send traces to the [Langfuse OpenTelemetry Backend](https://langfuse.com/docs/opentelemetry/get-started)."
+ "Pydantic Logfire offers an instrumentation for the OpenAI Agents SDK. We use this to send traces to the [Langfuse OpenTelemetry Backend](https://langfuse.com/docs/opentelemetry/get-started)."
]
},
{
diff --git a/examples/agents_sdk/session_memory.ipynb b/examples/agents_sdk/session_memory.ipynb
index 4e71ae5b..cb604f89 100644
--- a/examples/agents_sdk/session_memory.ipynb
+++ b/examples/agents_sdk/session_memory.ipynb
@@ -55,7 +55,7 @@
"metadata": {},
"source": [
"\n",
- "#### Real-World Scenario\n",
+ "#### Real-world scenario\n",
"\n",
"We’ll ground the techniques in a practical example for one of the common long-running tasks, such as:\n",
"\n",
@@ -83,11 +83,11 @@
"\n",
" - **Best when**\n",
"\n",
- " - Your tasks in the conversation is indepentent from each other with non-overlapping context that does not reuqire carrying previous details further.\n",
+ " - Your tasks in the conversation are independent from each other with non-overlapping context that does not require carrying previous details forward.\n",
" - You need predictability, easy evals, and low latency (ops automations, CRM/API actions).\n",
" - The conversation’s useful context is local (recent steps matter far more than distant history).\n",
"\n",
- "- **Context Summarization** – compressing prior messages(assistant, user, tools, etc.) into structured, shorter summaries injected into the conversation history.\n",
+ "- **Context Summarization** – compressing prior messages (assistant, user, tools, etc.) into structured, shorter summaries injected into the conversation history.\n",
"\n",
" - **Pros**\n",
"\n",
@@ -105,8 +105,8 @@
"\n",
" - **Best when**\n",
"\n",
- " - You have use cases where your tasks needs context collected accross the flow such as planning/coaching, RAG-heavy analysis, policy Q&A.\n",
- " - You need continuity over long horizons and carry the important details further to solve related tasks.\n",
+ " - You have use cases where your tasks need context collected across the flow such as planning/coaching, RAG-heavy analysis, policy Q&A.\n",
+ " - You need continuity over long horizons and must retain important details to solve related tasks.\n",
" - Sessions exceed N turns but must preserve decisions, IDs, and constraints reliably.\n",
"<br>"
]
diff --git a/examples/azure/archive/chat_with_your_own_data.ipynb b/examples/azure/archive/chat_with_your_own_data.ipynb
index 1c8eca72..ee6f2e83 100644
--- a/examples/azure/archive/chat_with_your_own_data.ipynb
+++ b/examples/azure/archive/chat_with_your_own_data.ipynb
@@ -31,7 +31,7 @@
"metadata": {},
"source": [
"## Prerequisites\n",
- "To get started, we'll cover a few prequisites. \n",
+ "To get started, we'll cover a few prerequisites. \n",
"\n",
"To properly access the Azure OpenAI Service, we need to create the proper resources at the [Azure Portal](https://portal.azure.com) (you can check a detailed guide on how to do this in the [Microsoft Docs](https://learn.microsoft.com/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal))\n",
"\n",
diff --git a/examples/azure/chat.ipynb b/examples/azure/chat.ipynb
index d239e2ee..d8066293 100644
--- a/examples/azure/chat.ipynb
+++ b/examples/azure/chat.ipynb
@@ -91,7 +91,7 @@
"metadata": {},
"source": [
"#### Authentication using Azure Active Directory\n",
- "Let's now see how we can autheticate via Azure Active Directory. We'll start by installing the `azure-identity` library. This library will provide the token credentials we need to authenticate and help us build a token credential provider through the `get_bearer_token_provider` helper function. It's recommended to use `get_bearer_token_provider` over providing a static token to `AzureOpenAI` because this API will automatically cache and refresh tokens for you. \n",
+ "Let's now see how we can authenticate via Azure Active Directory. We'll start by installing the `azure-identity` library. This library will provide the token credentials we need to authenticate and help us build a token credential provider through the `get_bearer_token_provider` helper function. It's recommended to use `get_bearer_token_provider` over providing a static token to `AzureOpenAI` because this API will automatically cache and refresh tokens for you. \n",
"\n",
"For more information on how to set up Azure Active Directory authentication with Azure OpenAI, see the [documentation](https://learn.microsoft.com/azure/ai-services/openai/how-to/managed-identity)."
]
diff --git a/examples/chatgpt/gpt_actions_library/gpt_action_box.ipynb b/examples/chatgpt/gpt_actions_library/gpt_action_box.ipynb
index c6160b16..c8782554 100644
--- a/examples/chatgpt/gpt_actions_library/gpt_action_box.ipynb
+++ b/examples/chatgpt/gpt_actions_library/gpt_action_box.ipynb
@@ -21,21 +21,21 @@
"This page provides an instruction & guide for developers building a GPT Action for a specific application. Before you proceed, make sure to first familiarize yourself with the following information: \n",
"- [Introduction to GPT Actions](https://platform.openai.com/docs/actions)\n",
"- [Introduction to GPT Actions Library](https://platform.openai.com/docs/actions/actions-library)\n",
- "- [Example of Buliding a GPT Action from Scratch](https://platform.openai.com/docs/actions/getting-started)"
+ "- [Example of Building a GPT Action from Scratch](https://platform.openai.com/docs/actions/getting-started)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "This guide provides details on how to connect chatGPT with a Box.com account, the GPT requires two actions to pull data from Box. The GPT will interact with the Box API directly but requires middleware (ie Azure function) to properly format the response from Box to download and read the file contents. The azure function action is transparent to the end user, meaning the user will not need to explicity call the action. \n",
+ "This guide explains how to connect ChatGPT to a Box.com account. The GPT uses two actions to pull data from Box. It interacts with the Box API directly but requires middleware, such as an Azure Function, to format the response so ChatGPT can download and read the file contents. The Azure Function action is transparent to the end user, so the user does not need to call it explicitly. \n",
"\n",
- "- Action 1 : Box API Action - Leverages the Box API to query data from Box \n",
- "- Action 2 : Azure function - Formats response from Box enabling chatGPT to download the file directly from Box\n",
+ "- Action 1: Box API action - Leverages the Box API to query data from Box \n",
+ "- Action 2: Azure Function - Formats the response from Box, enabling ChatGPT to download the file directly from Box\n",
"\n",
"### Value + Example Business Use Cases\n",
"\n",
- "Existing Box customers can leverage these guidelines to query details about files, contents of files and any metadata related. This enables a OpenAI powered analysis of any content stored in Box such as visualizing data sets and creating summaries across multiple folders and files. This GPT can access folders, files and business process data such as metadata in Box. Additionally Box admins can use this GPT action for visibility into audit trails and health checks."
+ "Existing Box customers can leverage these guidelines to query details about files, contents of files and any metadata related. This enables OpenAI-powered analysis of any content stored in Box such as visualizing data sets and creating summaries across multiple folders and files. This GPT can access folders, files and business process data such as metadata in Box. Additionally, Box admins can use this GPT action for visibility into audit trails and health checks."
]
},
{
@@ -85,8 +85,8 @@
"- This requires a Box developer account to get started : https://developer.box.com/\n",
"- Follow the Box Developer site to create a custom app with OAuth 2.0 authentication type : https://developer.box.com/guides/getting-started/first-application/ \n",
"- Navigate to **Configuration** tab for the following values\n",
- " - OAuth 2.0 Credentials (**Client ID** / **Client Secret**) You will need both of these values for the chatGPT configuration\n",
- " - OAuth 2.0 **Redirect URIs** : You will fill this value in from chatGPT action configuration below\n",
+ " - OAuth 2.0 Credentials (**Client ID** / **Client Secret**) You will need both of these values for the ChatGPT configuration\n",
+ " - OAuth 2.0 **Redirect URIs** : You will fill this value in from ChatGPT action configuration below\n",
" - Application scopes (**Read all files and folders in Box**, **Manage Enterprise properties**) \n",
"\n",
"You will want to keep this window open, the Redirct URIs needs to be filled in from the gpt configuration.\n",
@@ -961,7 +961,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Make sure to follow the rest of the Azure guide for post authentication steps and chatGPT configuration : [Azure Cookbook Guide](https://cookbook.openai.com/examples/azure/functions)"
+ "Make sure to follow the rest of the Azure guide for post authentication steps and ChatGPT configuration : [Azure Cookbook Guide](https://cookbook.openai.com/examples/azure/functions)"
]
},
{
diff --git a/examples/chatgpt/gpt_actions_library/gpt_action_gmail.ipynb b/examples/chatgpt/gpt_actions_library/gpt_action_gmail.ipynb
index b16bd22d..40c0f46f 100644
--- a/examples/chatgpt/gpt_actions_library/gpt_action_gmail.ipynb
+++ b/examples/chatgpt/gpt_actions_library/gpt_action_gmail.ipynb
@@ -47,7 +47,7 @@
"**Example Use Cases**: \n",
"- Manage internal communications by summarizing lengthy emails and drafting responses based on previous email threads.\n",
"- Support agents can provide customers with instant responses adhering to a company’s communication guidelines, tone, and style.\n",
- "- Reference other GPTs , such as a data analsys GPT, and then ask for a draft/send of the consolidated analysis through email communication."
+ "- Reference other GPTs, such as a data analysis GPT, and then ask to draft or send the consolidated analysis by email."
]
},
{
diff --git a/examples/chatgpt/gpt_actions_library/gpt_action_googleads_adzviser.ipynb b/examples/chatgpt/gpt_actions_library/gpt_action_googleads_adzviser.ipynb
index 07bad46f..cc971c8f 100644
--- a/examples/chatgpt/gpt_actions_library/gpt_action_googleads_adzviser.ipynb
+++ b/examples/chatgpt/gpt_actions_library/gpt_action_googleads_adzviser.ipynb
@@ -88,7 +88,7 @@
"source": [
"Check out these links from the application before you get started:\n",
"- How to create a workspace on Adzviser: https://docs.adzviser.com/getStarted/workspace\n",
- "- Adzviser Custom GPT Documentaion: https://docs.adzviser.com/chatgpt/expert\n",
+ "- Adzviser Custom GPT Documentation: https://docs.adzviser.com/chatgpt/expert\n",
"- Google Ads prompt library: https://docs.adzviser.com/chatgpt/googleAdsPromptTemplates"
]
},
diff --git a/examples/chatgpt/gpt_actions_library/gpt_action_jira.ipynb b/examples/chatgpt/gpt_actions_library/gpt_action_jira.ipynb
index 25cc3791..09fbe69f 100644
--- a/examples/chatgpt/gpt_actions_library/gpt_action_jira.ipynb
+++ b/examples/chatgpt/gpt_actions_library/gpt_action_jira.ipynb
@@ -21,7 +21,7 @@
"This page provides an instruction & guide for developers building a GPT Action for a specific application. Before you proceed, make sure to first familiarize yourself with the following information: \n",
"- [Introduction to GPT Actions](https://platform.openai.com/docs/actions)\n",
"- [Introduction to GPT Actions Library](https://platform.openai.com/docs/actions/actions-library)\n",
- "- [Example of Buliding a GPT Action from Scratch](https://platform.openai.com/docs/actions/getting-started)"
+ "- [Example of Building a GPT Action from Scratch](https://platform.openai.com/docs/actions/getting-started)"
]
},
{
diff --git a/examples/chatgpt/gpt_actions_library/gpt_action_notion.ipynb b/examples/chatgpt/gpt_actions_library/gpt_action_notion.ipynb
index 0ed61dd4..72a91444 100644
--- a/examples/chatgpt/gpt_actions_library/gpt_action_notion.ipynb
+++ b/examples/chatgpt/gpt_actions_library/gpt_action_notion.ipynb
@@ -21,7 +21,7 @@
"This page provides an instruction & guide for developers building a GPT Action for a specific application. Before you proceed, make sure to first familiarize yourself with the following information: \n",
"- [Introduction to GPT Actions](https://platform.openai.com/docs/actions)\n",
"- [Introduction to GPT Actions Library](https://platform.openai.com/docs/actions/actions-library)\n",
- "- [Example of Buliding a GPT Action from Scratch](https://platform.openai.com/docs/actions/getting-started)"
+ "- [Example of Building a GPT Action from Scratch](https://platform.openai.com/docs/actions/getting-started)"
]
},
{
diff --git a/examples/chatgpt/gpt_actions_library/gpt_action_outlook.ipynb b/examples/chatgpt/gpt_actions_library/gpt_action_outlook.ipynb
index 4bde0245..099677b1 100644
--- a/examples/chatgpt/gpt_actions_library/gpt_action_outlook.ipynb
+++ b/examples/chatgpt/gpt_actions_library/gpt_action_outlook.ipynb
@@ -21,7 +21,7 @@
"This page provides an instruction & guide for developers building a GPT Action for a specific application. Before you proceed, make sure to first familiarize yourself with the following information: \n",
"- [Introduction to GPT Actions](https://platform.openai.com/docs/actions)\n",
"- [Introduction to GPT Actions Library](https://platform.openai.com/docs/actions/actions-library)\n",
- "- [Example of Buliding a GPT Action from Scratch](https://platform.openai.com/docs/actions/getting-started)"
+ "- [Example of Building a GPT Action from Scratch](https://platform.openai.com/docs/actions/getting-started)"
]
},
{
@@ -393,7 +393,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "1. <b>App Registration</b>: The first step is to register a new App registration in the [Azure Portal](portal.azure.com) which will be used to integrate OAuth between our application and Azure Active Directory/Entra ID. Simply provide the application with a relevant name, leaving the Redirect URI blank for now as we will return to this, and save."
+ "1. <b>App Registration</b>: The first step is to register a new App registration in the [Azure Portal](https://portal.azure.com) which will be used to integrate OAuth between our application and Azure Active Directory/Entra ID. Simply provide the application with a relevant name, leaving the Redirect URI blank for now as we will return to this, and save."
]
},
{
diff --git a/examples/chatgpt/gpt_actions_library/gpt_action_redshift.ipynb b/examples/chatgpt/gpt_actions_library/gpt_action_redshift.ipynb
index 44786494..d2887b7a 100644
--- a/examples/chatgpt/gpt_actions_library/gpt_action_redshift.ipynb
+++ b/examples/chatgpt/gpt_actions_library/gpt_action_redshift.ipynb
@@ -217,7 +217,7 @@
"source": [
"### Retrieve VPC information\n",
"\n",
- "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 > Workgroup configuration > `your_workgroup` > Data access, or through the CLI:"
+ "We will need to connect our function to Redshift, therefore we need to find the network used by Redshift. You can find this on your Redshift interface in the AWS console, under Amazon Redshift Serverless > Workgroup configuration > `your_workgroup` > Data access, or through the CLI:"
]
},
{
diff --git a/examples/chatgpt/gpt_actions_library/gpt_action_salesforce.ipynb b/examples/chatgpt/gpt_actions_library/gpt_action_salesforce.ipynb
index 32e4eaf3..1d20395f 100644
--- a/examples/chatgpt/gpt_actions_library/gpt_action_salesforce.ipynb
+++ b/examples/chatgpt/gpt_actions_library/gpt_action_salesforce.ipynb
@@ -14,7 +14,7 @@
"This page provides an instruction & guide for developers building a GPT Action for a specific application. Before you proceed, make sure to first familiarize yourself with the following information: \n",
"- [Introduction to GPT Actions](https://platform.openai.com/docs/actions/introduction)\n",
"- [Introduction to GPT Actions Library](https://platform.openai.com/docs/actions/actions-library)\n",
- "- [Example of Buliding a GPT Action from Scratch](https://platform.openai.com/docs/actions/getting-started)"
+ "- [Example of Building a GPT Action from Scratch](https://platform.openai.com/docs/actions/getting-started)"
]
},
{
@@ -40,7 +40,7 @@
"**Example Use Cases**: \n",
"- Reduce average response time to customers\n",
"- Reduce time to troubleshoot cases or issues\n",
- "- Ensure more consistent brand voice in reponse to customers when combined with knowledge and instructions in the GPT"
+ "- Ensure more consistent brand voice in response to customers when combined with knowledge and instructions in the GPT"
]
},
{
diff --git a/examples/chatgpt/gpt_actions_library/gpt_action_sharepoint_doc.ipynb b/examples/chatgpt/gpt_actions_library/gpt_action_sharepoint_doc.ipynb
index e12af032..80bddf24 100644
--- a/examples/chatgpt/gpt_actions_library/gpt_action_sharepoint_doc.ipynb
+++ b/examples/chatgpt/gpt_actions_library/gpt_action_sharepoint_doc.ipynb
@@ -348,7 +348,7 @@
" }\n",
" // Initialize the Graph Client using the initGraphClient function defined above\n",
" let client = initGraphClient(accessToken);\n",
- " // this is the search body to be used in the Microsft Graph Search API: https://learn.microsoft.com/en-us/graph/search-concept-files\n",
+ " // this is the search body to be used in the Microsoft Graph Search API: https://learn.microsoft.com/en-us/graph/search-concept-files\n",
" const requestBody = {\n",
" requests: [\n",
" {\n",
diff --git a/examples/chatgpt/gpt_actions_library/gpt_action_sharepoint_text.ipynb b/examples/chatgpt/gpt_actions_library/gpt_action_sharepoint_text.ipynb
index 42dd550b..a7a393c8 100644
--- a/examples/chatgpt/gpt_actions_library/gpt_action_sharepoint_text.ipynb
+++ b/examples/chatgpt/gpt_actions_library/gpt_action_sharepoint_text.ipynb
@@ -412,7 +412,7 @@
" }\n",
" // Initialize the Graph Client using the initGraphClient function defined above\n",
" let client = initGraphClient(accessToken);\n",
- " // this is the search body to be used in the Microsft Graph Search API: https://learn.microsoft.com/en-us/graph/search-concept-files\n",
+ " // this is the search body to be used in the Microsoft Graph Search API: https://learn.microsoft.com/en-us/graph/search-concept-files\n",
" const requestBody = {\n",
" requests: [\n",
" {\n",
@@ -460,7 +460,7 @@
" const { name, id } = hit.resource;\n",
" // We use the below to grab the URL of the file to include in the response\n",
" const webUrl = hit.resource.webUrl.replace(/\\s/g, \"%20\");\n",
- " // The Microsoft Graph API ranks the reponses, so we use this to order it\n",
+ " // The Microsoft Graph API ranks the responses, so we use this to order it\n",
" const rank = hit.rank;\n",
" // The below is where the file lives\n",
" const driveId = hit.resource.parentReference.driveId;\n",
diff --git a/examples/chatgpt/gpt_actions_library/gpt_action_snowflake_direct.ipynb b/examples/chatgpt/gpt_actions_library/gpt_action_snowflake_direct.ipynb
index cc1c692a..f954458b 100644
--- a/examples/chatgpt/gpt_actions_library/gpt_action_snowflake_direct.ipynb
+++ b/examples/chatgpt/gpt_actions_library/gpt_action_snowflake_direct.ipynb
@@ -27,7 +27,7 @@
"source": [
"This particular GPT Action provides an overview of how to connect to a Snowflake Data Warehouse. This Action takes a user’s question, scans the relevant tables to gather the data schema, then writes a SQL query to answer the user’s question.\n",
"\n",
- "Note: This cookbook returns back a [ResultSet SQL statement](https://docs.snowflake.com/en/developer-guide/sql-api/handling-responses#getting-the-data-from-the-results), rather than the full result that is not limited by GPT Actions application/json payload limit. For production and advanced use-case, a middleware is required to return back a CSV file. You can follow instructions in the [GPT Actions - Snowflake Middleware cookbook](../gpt_actions_library/gpt_action_snowflake_middleware) to implement this flow instead."
+ "Note: This cookbook returns a [ResultSet SQL statement](https://docs.snowflake.com/en/developer-guide/sql-api/handling-responses#getting-the-data-from-the-results) rather than the complete result, which may exceed the GPT Actions `application/json` payload limit. For production and advanced use cases, use middleware to return a CSV file. Follow the [GPT Actions - Snowflake Middleware cookbook](gpt_action_snowflake_middleware.ipynb) to implement this flow."
]
},
{
diff --git a/examples/chatgpt/gpt_actions_library/gpt_action_snowflake_middleware.ipynb b/examples/chatgpt/gpt_actions_library/gpt_action_snowflake_middleware.ipynb
index 74ca771e..72ef4086 100644
--- a/examples/chatgpt/gpt_actions_library/gpt_action_snowflake_middleware.ipynb
+++ b/examples/chatgpt/gpt_actions_library/gpt_action_snowflake_middleware.ipynb
@@ -17,7 +17,7 @@
"\n",
"* [Introduction to GPT Actions](https://platform.openai.com/docs/actions)\n",
"* [Introduction to GPT Actions Library](https://platform.openai.com/docs/actions/actions-library)\n",
- "* [Example of Buliding a GPT Action from Scratch](https://platform.openai.com/docs/actions/getting-started)"
+ "* [Example of Building a GPT Action from Scratch](https://platform.openai.com/docs/actions/getting-started)"
]
},
{
@@ -280,7 +280,7 @@
"source": [
"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. \n",
"\n",
- "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.\n",
+ "In 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.\n",
"\n",
"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."
]
@@ -645,9 +645,9 @@
"metadata": {},
"source": [
"* 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.\n",
- "* _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.\n",
+ "* _Why is the Azure Function App required 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.\n",
"* _My company uses a different cloud provider than Azure._ For connecting other middleware functions to ChatGPT via GPT action, please refer to other [AWS](https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_middleware_aws_function) or [GCP](https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_middleware_google_cloud_function) 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. \n",
- "* _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:\n",
+ "* _How do I limit the datasets that my GPT has access to?_ It can be important to limit the scope of access ChatGPT has within Snowflake. There are a few ways to do this:\n",
" * 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\n",
" * In your middleware function you can add sanity checks to verify the tables accessed are approved by for that application\n",
" * You may want to generate an entirely new Database/Warehouse specific to integrating with ChatGPT that is scrubbed of anything sensitive, such as PII.\n",
diff --git a/examples/chatgpt/gpt_actions_library/gpt_action_sql_database.ipynb b/examples/chatgpt/gpt_actions_library/gpt_action_sql_database.ipynb
index c99d2825..d67c9f95 100644
--- a/examples/chatgpt/gpt_actions_library/gpt_action_sql_database.ipynb
+++ b/examples/chatgpt/gpt_actions_library/gpt_action_sql_database.ipynb
@@ -52,7 +52,7 @@
"1. Accept database queries via REST API requests\n",
"2. Forward queries to the integrated SQL database\n",
"3. Convert database responses in to CSV files\n",
- "4. Return CSV files to the requestor\n",
+ "4. Return CSV files to the requester\n",
"\n",
"There are two main approaches to designing the first function:\n",
"\n",
diff --git a/examples/chatgpt/gpt_actions_library/gpt_middleware_aws_function.ipynb b/examples/chatgpt/gpt_actions_library/gpt_middleware_aws_function.ipynb
index 594b8979..5853d669 100644
--- a/examples/chatgpt/gpt_actions_library/gpt_middleware_aws_function.ipynb
+++ b/examples/chatgpt/gpt_actions_library/gpt_middleware_aws_function.ipynb
@@ -373,7 +373,7 @@
"\n",
"![../../../images/aws_lambda_19.png](../../../images/aws_lambda_19.png)\n",
"\n",
- "You will be redirected to AWS Cognito page, which you can log-in in using the credentials previously set-up.\n",
+ "You will be redirected to AWS Cognito page, which you can log in with the credentials previously set-up.\n",
"\n",
"If you now ask the GPT to run the same action, it will answer correctly as you're now authenticated and able to run this function!\n",
"\n",
diff --git a/examples/chatgpt/gpt_actions_library/gpt_middleware_azure_function.ipynb b/examples/chatgpt/gpt_actions_library/gpt_middleware_azure_function.ipynb
index 4236cccf..7b85aa9e 100644
--- a/examples/chatgpt/gpt_actions_library/gpt_middleware_azure_function.ipynb
+++ b/examples/chatgpt/gpt_actions_library/gpt_middleware_azure_function.ipynb
@@ -203,7 +203,7 @@
"\n",
" 1. Under the **Web** section, you’ll notice one callback URI was added automatically. Add the Postman redirect URI (<https://oauth.pstmn.io/v1/callback>) for testing.\n",
"\n",
- "7) On the left-hand side, go to **Overview**. Copy the **application (client) ID** and and the **directory (tenant) ID** and **save for later as** `CLIENT_ID` **and** `TENANT_ID`**.**"
+ "7) On the left-hand side, go to **Overview**. Copy the **application (client) ID** and the **directory (tenant) ID** and **save for later as** `CLIENT_ID` **and** `TENANT_ID`**.**"
]
},
{
@@ -287,7 +287,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "This should be done separately and is specific to your app. See the [Sharepoint Cookbook]((https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_sharepoint_doc)) for an example of that. "
+ "This should be done separately and is specific to your app. See the [SharePoint Cookbook](https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_sharepoint_doc) for an example of that. "
]
},
{
@@ -334,7 +334,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "*This is application specific. See [Sharepoint Cookbook]((https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_sharepoint_doc)) for an example*"
+ "*This is application specific. See [SharePoint Cookbook](https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_action_sharepoint_doc) for an example*"
]
},
{
@@ -355,7 +355,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Below is an example of what connecting to this Middlware might look like. You'll need to insert your application's & function's information in this section. "
+ "Below is an example of what connecting to this Middleware might look like. You'll need to insert your application's & function's information in this section. "
]
},
{
diff --git a/examples/chatgpt/rag-quickstart/azure/Azure_AI_Search_with_Azure_Functions_and_GPT_Actions_in_ChatGPT.ipynb b/examples/chatgpt/rag-quickstart/azure/Azure_AI_Search_with_Azure_Functions_and_GPT_Actions_in_ChatGPT.ipynb
index 6a537075..d9204cbe 100644
--- a/examples/chatgpt/rag-quickstart/azure/Azure_AI_Search_with_Azure_Functions_and_GPT_Actions_in_ChatGPT.ipynb
+++ b/examples/chatgpt/rag-quickstart/azure/Azure_AI_Search_with_Azure_Functions_and_GPT_Actions_in_ChatGPT.ipynb
@@ -13,7 +13,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "This notebook provides step by step instuctions on using Azure AI Search (f.k.a Azure Cognitive Search) as a vector database with OpenAI embeddings, then creating an Azure Function on top to plug into a Custom GPT in ChatGPT. \n",
+ "This notebook provides step-by-step instructions on using Azure AI Search (f.k.a Azure Cognitive Search) as a vector database with OpenAI embeddings, then creating an Azure Function on top to plug into a Custom GPT in ChatGPT. \n",
"\n",
"This can be a solution for customers looking to set up RAG infrastructure contained within Azure, and exposing it as an endpoint to integrate that with other platforms such as ChatGPT.\n",
"\n",
diff --git a/examples/chatgpt/rag-quickstart/gcp/Getting_started_with_bigquery_vector_search_and_openai.ipynb b/examples/chatgpt/rag-quickstart/gcp/Getting_started_with_bigquery_vector_search_and_openai.ipynb
index 157b7ba1..329f24df 100644
--- a/examples/chatgpt/rag-quickstart/gcp/Getting_started_with_bigquery_vector_search_and_openai.ipynb
+++ b/examples/chatgpt/rag-quickstart/gcp/Getting_started_with_bigquery_vector_search_and_openai.ipynb
@@ -231,7 +231,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "We are going to use some techniques highlighted in [this cookbook](khttps://github.com/openai/openai-cookbook/blob/main/examples/Embedding_long_inputs.ipynb). This is a quick way to embed text, without taking into account variables like sections, using our vision model to describe images/graphs/diagrams, overlapping text between chunks for longer documents, etc. "
+ "We are going to use some techniques highlighted in [this cookbook](https://github.com/openai/openai-cookbook/blob/main/examples/Embedding_long_inputs.ipynb). This is a quick way to embed text, without taking into account variables like sections, using our vision model to describe images/graphs/diagrams, overlapping text between chunks for longer documents, etc. "
]
},
{
@@ -895,13 +895,13 @@
"source": [
"# Recap\n",
"\n",
- "We've now succesfully integrated GCP BigQuery Vector Search with GPT Actions in ChatGPT by doing the following:\n",
+ "We've now successfully integrated GCP BigQuery Vector Search with GPT Actions in ChatGPT by doing the following:\n",
"1. Embedded docs using OpenAI's embeddings, while adding some additional metadata using gpt-4o.\n",
"2. Uploaded that data to GCP BigQuery (raw data and vectors of embeddings)\n",
"3. Created an endpoint on GCP Functions to retrieve those\n",
"4. Incorporated it into a custom GPT.\n",
"\n",
- "Our GPT can now retrieve informaiton to help answer user queries, making it much more accurate and customized to our data. Here's the GPT in action:"
+ "Our GPT can now retrieve information to help answer user queries, making it much more accurate and customized to our data. Here's the GPT in action:"
]
},
{
diff --git a/examples/chatgpt/rag-quickstart/pinecone-retool/gpt-action-pinecone-retool-rag.ipynb b/examples/chatgpt/rag-quickstart/pinecone-retool/gpt-action-pinecone-retool-rag.ipynb
index 247f35a6..71df4656 100644
--- a/examples/chatgpt/rag-quickstart/pinecone-retool/gpt-action-pinecone-retool-rag.ipynb
+++ b/examples/chatgpt/rag-quickstart/pinecone-retool/gpt-action-pinecone-retool-rag.ipynb
@@ -22,7 +22,7 @@
"## Table of Contents\n",
"\n",
"1. [Setup Pinecone](#setup-pinecone)\n",
- "2. [Setup Noteboook](#setup-notebook)\n",
+ "2. [Setup Notebook](#setup-notebook)\n",
"3. [Prepare Data](#prepare-data)\n",
"4. [Create a Pinecone Index](#create-a-pinecone-index)\n",
"5. [Populate the Pinecone Index](#populate-the-pinecone-index)\n",
@@ -234,7 +234,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "The vectors should now be visible in the Pincone Dashbaord. \n",
+ "The vectors should now be visible in the Pinecone Dashboard. \n",
"\n",
"To test the search functionality we can query the index. Below we are taking a sample question, running this through the same embedding function and then checking the index for matching vectors.\n",
"\n",
diff --git a/examples/codex/codex_mcp_agents_sdk/building_consistent_workflows_codex_cli_agents_sdk.ipynb b/examples/codex/codex_mcp_agents_sdk/building_consistent_workflows_codex_cli_agents_sdk.ipynb
index 3818ca2f..0c716012 100644
--- a/examples/codex/codex_mcp_agents_sdk/building_consistent_workflows_codex_cli_agents_sdk.ipynb
+++ b/examples/codex/codex_mcp_agents_sdk/building_consistent_workflows_codex_cli_agents_sdk.ipynb
@@ -6,7 +6,7 @@
"metadata": {},
"source": [
"# Building Consistent Workflows with Codex CLI & Agents SDK\n",
- "### Ensuring Repeatable, Traceable, and Scaleable Agentic Development\n",
+ "### Ensuring Repeatable, Traceable, and Scalable Agentic Development\n",
"\n",
"## Introduction\n",
"Developers strive for consistency in everything they do. With Codex CLI and the Agents SDK, that consistency can now scale like never before. Whether you’re refactoring a large codebase, rolling out new features, or introducing a new testing framework, Codex integrates seamlessly into CLI, IDE, and cloud workflows to automate and enforce repeatable development patterns. \n",
@@ -200,7 +200,7 @@
"- **Backend Developer**: Implements APIs and logic. \n",
"- **Tester**: Validates outputs against acceptance criteria. \n",
"\n",
- "In this example, we intentionally have the Project Manager agent enforce gating logic between each of the specialized downstream agents. This ensures that artifacts exist before handoffs are made. This mirrors real world enterprise workflows such as JIRA task orchestration, long-chained rollouts, and QA sign-offs. \n",
+ "In this example, we intentionally have the Project Manager agent enforce gating logic between each of the specialized downstream agents. This ensures that artifacts exist before handoffs are made. This mirrors real-world enterprise workflows such as JIRA task orchestration, long-chained rollouts, and QA sign-offs. \n",
"\n",
"<div align=\"center\">\n",
" <img src=\"/images/multi_agent_codex_workflow.png\" alt=\"Multi-Agent Codex Workflow with Codex MCP\" style=\"max-width: 100%; width: 960px;\" />\n",
@@ -209,7 +209,7 @@
"</div>\n",
"\n",
"\n",
- "In this structure, each of our agents serve a specialized purpose. The Project Manager is overall responsible for coordinating across all other agents and ensuring the overall task is complete.\n",
+ "In this structure, each of our agents serves a specialized purpose. The Project Manager is overall responsible for coordinating across all other agents and ensuring the overall task is complete.\n",
"\n",
"## Define the Codex CLI MCP Server\n",
"We set up our MCP Server to initialize Codex CLI just as we did in the single agent example.\n",
@@ -232,7 +232,7 @@
"\n",
"\n",
"## Define each specialized agent\n",
- "Below we define each of our specialized agents and provide access to our Codex MCP server. Notice that we are also passing the `RECOMMMENDED_PROMPT_PREFIX` to each agent that helps the system optimize for handoffs between agents. \n",
+ "Below we define each of our specialized agents and provide access to our Codex MCP server. Notice that we are also passing the `RECOMMENDED_PROMPT_PREFIX` to each agent that helps the system optimize for handoffs between agents. \n",
"\n",
"```python\n",
"# Downstream agents are defined first for clarity, then PM references them in handoffs.\n",
@@ -404,7 +404,7 @@
"\"\"\"\n",
"```\n",
"\n",
- "Next, run your system, sit back, and you’ll see the agents go to work and create a game in a few minutes! We've included the fully executable code below. Once it's finished, you'll notice the creation of the following files directory. Note that this multi-agent orchestration usually took about 11 mintues to fully complete.\n",
+ "Next, run your system, sit back, and you’ll see the agents go to work and create a game in a few minutes! We've included the fully executable code below. Once it's finished, you'll notice the creation of the following files directory. Note that this multi-agent orchestration usually took about 11 minutes to fully complete.\n",
"\n",
"```markdown\n",
"root_directory/\n",
diff --git a/examples/custom_image_embedding_search.ipynb b/examples/custom_image_embedding_search.ipynb
index 7b51abd0..0dc70a07 100644
--- a/examples/custom_image_embedding_search.ipynb
+++ b/examples/custom_image_embedding_search.ipynb
@@ -413,7 +413,7 @@
"id": "eV8LaOncGH3j"
},
"source": [
- "Now let's perform similarity search to find the two most similar images in our knowledge base. We do this by getting the embeddings of a user inputted image_path, retrieving the indexes and distances of the similar iamges in our database. Distance will be our proxy metric for similarity and a smaller distance means more similar. We then sort based on distance in descending order."
+ "Now let's perform similarity search to find the two most similar images in our knowledge base. We do this by embedding a user-provided `image_path` and retrieving the indices and similarity scores for images in our database. A larger score indicates greater similarity, so we sort the scores in descending order."
]
},
{
@@ -438,7 +438,7 @@
"id": "0O-GYQ-1QAqm"
},
"source": [
- "We require the indices as we will use this to search through our image_directory and selecting the image at the location of the index to feed into the vision model for RAG."
+ "We use the indices to search `image_directory` and select the corresponding images to pass to the vision model for RAG."
]
},
{
diff --git a/examples/deep_research_api/introduction_to_deep_research_api.ipynb b/examples/deep_research_api/introduction_to_deep_research_api.ipynb
index 4d77945f..312628bc 100644
--- a/examples/deep_research_api/introduction_to_deep_research_api.ipynb
+++ b/examples/deep_research_api/introduction_to_deep_research_api.ipynb
@@ -78,10 +78,10 @@
"Let’s walk through an example of a Deep Research API call. Imagine we’re working at a healthcare financial services firm tasked with producing an in-depth report on the economic implications of recent medications used to treat type 2 diabetes and obesity—particularly semaglutide. Our goal is to synthesize clinical outcomes, cost-effectiveness, and regional pricing data into a structured, citation-backed analysis that could inform investment, payer strategy, or policy recommendations.\n",
"\n",
"To get started, let's:\n",
- "- Put our role in the system message, outlining what type of report we'd like to generate\n",
- "- Set the summary paramter to \"auto\" for now for the best available summary. (If you'd like for your report to more detailed, you can set summary to detailed)\n",
- "- Include the required tool web_search_preview and optionally add code_interpreter.\n",
- "- Set the background parameter to True. Since a Deep Research task can take several minutes to execute, enabling background mode will allow you to run the request asynchronously without having to worry about timeouts or other connectivity issues."
+ "- Put our role in the system message, outlining the type of report we'd like to generate.\n",
+ "- Set the `summary` parameter to `\"auto\"` for the best available summary. To request a more detailed report, set `summary` to `\"detailed\"`.\n",
+ "- Include the required `web_search_preview` tool and optionally add `code_interpreter`.\n",
+ "- Set the `background` parameter to `True`. Since a Deep Research task can take several minutes to execute, enabling background mode will allow you to run the request asynchronously without having to worry about timeouts or other connectivity issues."
]
},
{
diff --git a/examples/deep_research_api/introduction_to_deep_research_api_agents.ipynb b/examples/deep_research_api/introduction_to_deep_research_api_agents.ipynb
index 7a57f526..7e465a7b 100644
--- a/examples/deep_research_api/introduction_to_deep_research_api_agents.ipynb
+++ b/examples/deep_research_api/introduction_to_deep_research_api_agents.ipynb
@@ -54,7 +54,7 @@
"\n",
"**Zero Data Retention**\n",
"\n",
- "We disable Data Retention through the os.environ setting below. This allows Enterprises to operate in a Zero Data Retention environment with Deep Research. If Data Retention is _not_ an active constraint for you, then consider keeping it enabled so you can have automated tracability for your agent workflows and deep integration with other platform tools like evaluations and fine tuning."
+ "We disable Data Retention through the os.environ setting below. This allows Enterprises to operate in a Zero Data Retention environment with Deep Research. If Data Retention is _not_ an active constraint for you, then consider keeping it enabled so you can have automated traceability for your agent workflows and deep integration with other platform tools like evaluations and fine tuning."
]
},
{
@@ -163,7 +163,7 @@
"\n",
"## Sub-Agent Prompt enrichment\n",
"\n",
- "The supporting Agent prompts are specifically designed to improve the quality of the final research output by providing structure and rigor to the users intial query."
+ "The supporting Agent prompts are specifically designed to improve the quality of the final research output by providing structure and rigor to the user's initial query."
]
},
{
diff --git a/examples/evaluation/Evaluate_RAG_with_LlamaIndex.ipynb b/examples/evaluation/Evaluate_RAG_with_LlamaIndex.ipynb
index f54e4872..5cf279a7 100644
--- a/examples/evaluation/Evaluate_RAG_with_LlamaIndex.ipynb
+++ b/examples/evaluation/Evaluate_RAG_with_LlamaIndex.ipynb
@@ -645,7 +645,7 @@
"source": [
"We will use `gpt-3.5-turbo` for generating response for a given query and `gpt-4` for evaluation.\n",
"\n",
- "Let's create service_context seperately for `gpt-3.5-turbo` and `gpt-4`."
+ "Let's create service_context separately for `gpt-3.5-turbo` and `gpt-4`."
]
},
{
diff --git a/examples/evaluation/Getting_Started_with_OpenAI_Evals.ipynb b/examples/evaluation/Getting_Started_with_OpenAI_Evals.ipynb
index a628fc8b..18091d97 100644
--- a/examples/evaluation/Getting_Started_with_OpenAI_Evals.ipynb
+++ b/examples/evaluation/Getting_Started_with_OpenAI_Evals.ipynb
@@ -359,7 +359,7 @@
"source": [
"## Running an evaluation\n",
"\n",
- "We can run this eval using the `oaieval` CLI. To get setup, install the library: `pip install .` (if you are running the [OpenAI Evals library](github.com/openai/evals) locally) or `pip install oaieval` if you are running an existing eval.\n",
+ "We can run this eval using the `oaieval` CLI. To get setup, install the library: `pip install .` (if you are running the [OpenAI Evals library](https://github.com/openai/evals) locally) or `pip install oaieval` if you are running an existing eval.\n",
"\n",
"Then, run the eval using the CLI: `oaieval gpt-3.5-turbo spider-sql`\n",
"\n",
@@ -1237,7 +1237,7 @@
"source": [
"Building out effective evals is a core part of the development cycle of LLM-based applications. The OpenAI Evals framework provides the core structure of building evals out of the box, and allows you to quickly spin up new tests for your various use cases. In this guide, we demonstrated step-by-step how to create an eval, run it, and analyze the results.\n",
"\n",
- "The example shown in this guide represent a straightfoward use case for evals. As you continue to explore this framework, we recommend you explore creating more complex model-graded evals for actual production use cases. Happy evaluating!"
+ "The example shown in this guide represents a straightforward use case for evals. As you continue to explore this framework, we recommend you explore creating more complex model-graded evals for actual production use cases. Happy evaluating!"
]
}
],
diff --git a/examples/evaluation/How_to_eval_abstractive_summarization.ipynb b/examples/evaluation/How_to_eval_abstractive_summarization.ipynb
index 15b2a1f7..bf70933e 100644
--- a/examples/evaluation/How_to_eval_abstractive_summarization.ipynb
+++ b/examples/evaluation/How_to_eval_abstractive_summarization.ipynb
@@ -18,7 +18,7 @@
"\n",
"In this notebook we delve into the evaluation techniques for abstractive summarization tasks using a simple example. We explore traditional evaluation methods like [ROUGE](https://aclanthology.org/W04-1013/) and [BERTScore](https://arxiv.org/abs/1904.09675), in addition to showcasing a more novel approach using LLMs as evaluators.\n",
"\n",
- "Evaluating the quality of summaries is a time-consuming process, as it involves different quality metrics such as coherence, conciseness, readability and content. Traditional automatic evaluation metrics such as `ROUGE` and `BERTScore` and others are concrete and reliable, but they may not correlate well with the actual quality of summaries. They show relatively low correlation with human judgments, especially for open-ended generation tasks ([Liu et al., 2023](https://arxiv.org/pdf/2303.16634.pdf)). There's a growing need to lean on human evaluations, user feedback, or model-based metrics while being vigilant about potential biases. While human judgment provides invaluable insights, it is often not scalable and can be cost-prohibitive.\n",
+ "Evaluating the quality of summaries is a time-consuming process, as it involves different quality metrics such as coherence, conciseness, readability and content. Traditional automatic evaluation metrics such as `ROUGE`, `BERTScore`, and others are concrete and reliable, but they may not correlate well with the actual quality of summaries. They show relatively low correlation with human judgments, especially for open-ended generation tasks ([Liu et al., 2023](https://arxiv.org/pdf/2303.16634.pdf)). There's a growing need to lean on human evaluations, user feedback, or model-based metrics while being vigilant about potential biases. While human judgment provides invaluable insights, it is often not scalable and can be cost-prohibitive.\n",
"\n",
"In addition to these traditional metrics, we showcase a method ([G-Eval](https://arxiv.org/pdf/2303.16634.pdf)) that leverages Large Language Models (LLMs) as a novel, reference-free metric for assessing abstractive summaries. In this case, we use `gpt-4` to score candidate outputs. `gpt-4` has effectively learned an internal model of language quality that allows it to differentiate between fluent, coherent text and low-quality text. Harnessing this internal scoring mechanism allows auto-evaluation of new candidate outputs generated by an LLM.\n"
]
@@ -445,7 +445,7 @@
"source": [
"## Evaluating using GPT-4\n",
"\n",
- "Here we implement an example **reference-free** text evaluator using `gpt-4`, inspired by the [G-Eval]((https://arxiv.org/pdf/2303.16634.pdf)) framework which evaluates the quality of generated text using large language models. Unlike metrics like `ROUGE` or `BERTScore` that rely on comparison to reference summaries, the `gpt-4` based evaluator assesses the quality of generated content based solely on the input prompt and text, without any ground truth references. This makes it applicable to new datasets and tasks where human references are sparse or unavailable. \n",
+ "Here we implement an example **reference-free** text evaluator using `gpt-4`, inspired by the [G-Eval](https://arxiv.org/pdf/2303.16634.pdf) framework which evaluates the quality of generated text using large language models. Unlike metrics like `ROUGE` or `BERTScore` that rely on comparison to reference summaries, the `gpt-4` based evaluator assesses the quality of generated content based solely on the input prompt and text, without any ground truth references. This makes it applicable to new datasets and tasks where human references are sparse or unavailable. \n",
"\n",
"Here's an overview of this method:\n",
"\n",
diff --git a/examples/evaluation/How_to_evaluate_LLMs_for_SQL_generation.ipynb b/examples/evaluation/How_to_evaluate_LLMs_for_SQL_generation.ipynb
index 9acfc05d..ac179e68 100644
--- a/examples/evaluation/How_to_evaluate_LLMs_for_SQL_generation.ipynb
+++ b/examples/evaluation/How_to_evaluate_LLMs_for_SQL_generation.ipynb
@@ -7,7 +7,7 @@
"source": [
"# How to test and evaluate LLMs for SQL generation\n",
"\n",
- "LLMs are fundamentally non-deterministic in their responses, this attribute makes them wonderfully creative and dynamic in their responses. However, this trait poses significant challenges in achieving consistency, a crucial aspect for integrating LLMs into production environments.\n",
+ "LLMs are fundamentally nondeterministic. This attribute makes their responses creative and dynamic. However, this trait poses significant challenges in achieving consistency, a crucial aspect for integrating LLMs into production environments.\n",
"\n",
"The key to harnessing the potential of LLMs in practical applications lies in consistent and systematic evaluation. This enables the identification and rectification of inconsistencies and helps with monitoring progress over time as the application evolves.\n",
"\n",
@@ -21,9 +21,9 @@
"\n",
"This example focuses on a natural language to SQL use case - code generation use cases fit well with this approach when you combine **code validation** with **code execution**, so your application can test code for real as it is generated to ensure consistency.\n",
"\n",
- "Although this notebook uses SQL generation usecase to demonstrate the concept, the approach is generic and can be applied to a wide variety of LLM driven applications.\n",
+ "Although this notebook uses SQL generation use case to demonstrate the concept, the approach is generic and can be applied to a wide variety of LLM-driven applications.\n",
"\n",
- "We will use two versions of a prompt to perform SQL generation. We will then use the unit tests and evaluation functions to test the perforamance of the prompts. Specifically, in this demonstration, we will evaluate:\n",
+ "We will use two versions of a prompt to perform SQL generation. We will then use the unit tests and evaluation functions to test the performance of the prompts. Specifically, in this demonstration, we will evaluate:\n",
"\n",
"1. The consistency of JSON response.\n",
"2. Syntactic correctness of SQL in response.\n",
@@ -110,7 +110,7 @@
"2. Answer, expressed in SQL designed to answer the question in natural language.\n",
"3. Context, expressed as a CREATE SQL statement, that describes the table that may be used to answer the question.\n",
"\n",
- "In our demonstration today, we will use LLM to attempt to answer the question (in natural language). The LLM will be expected to generate a CREATE SQL statement to create a context suitable to answer the user question and a coresponding SELECT SQL query designed to answer the user question completely.\n",
+ "In our demonstration today, we will use LLM to attempt to answer the question (in natural language). The LLM will be expected to generate a CREATE SQL statement to create a context suitable to answer the user question and a corresponding SELECT SQL query designed to answer the user question completely.\n",
"\n",
"The dataset looks like this:"
]
@@ -406,7 +406,7 @@
"id": "a5fdc420-94cc-4e47-80e1-82bf51e44f2a",
"metadata": {},
"source": [
- "As expected, we get an exception thrown from the `test_valid_schema` fucntion."
+ "As expected, we get an exception thrown from the `test_valid_schema` function."
]
},
{
@@ -416,14 +416,14 @@
"source": [
"### Test SQL queries\n",
"\n",
- "Next we'll validate the correctness of the SQL. This test will be desined to validate:\n",
+ "Next we'll validate the correctness of the SQL. This test is designed to validate:\n",
"\n",
"1. The CREATE SQL returned in GPT response is syntactically correct.\n",
"2. The SELECT SQL returned in the GPT response is syntactically correct.\n",
"\n",
- "To achieve this, we will use a sqlite instance. We will direct the retured SQL functions to a sqlite instance. If the SQL statements are valid, sqlite instance will accept and execute the statements; otherwise we will expect an exception to be thrown.\n",
+ "To achieve this, we will use a SQLite instance. We will send the returned SQL statements to the SQLite instance. If the statements are valid, SQLite will accept and execute them; otherwise we will expect an exception to be thrown.\n",
"\n",
- "`create_connection` function below will setup a sqlite instance (in-memory by default) and create a connection to be used later."
+ "The `create_connection` function below will set up a SQLite instance (in-memory by default) and create a connection to be used later."
]
},
{
@@ -937,7 +937,7 @@
"source": [
"We can now group the outcomes of:\n",
"* the **unit tests**, which test the structure of response; and\n",
- "* the **evaluation**, which checks if the SQL is syntatically correct."
+ "* the **evaluation**, which checks if the SQL is syntactically correct."
]
},
{
diff --git a/examples/evaluation/use-cases/mcp_eval_notebook.ipynb b/examples/evaluation/use-cases/mcp_eval_notebook.ipynb
index 5448d566..44481d0c 100644
--- a/examples/evaluation/use-cases/mcp_eval_notebook.ipynb
+++ b/examples/evaluation/use-cases/mcp_eval_notebook.ipynb
@@ -820,7 +820,7 @@
"<br><br><br>\n",
"\n",
"\n",
- "If you guessed that the model would now call to MCP tool everytime and get every answer correct, you are right!"
+ "If you guessed that the model would now call the MCP tool every time and get every answer correct, you are right!"
]
},
{
diff --git a/examples/fine-tuned_qa/ft_retrieval_augmented_generation_qdrant.ipynb b/examples/fine-tuned_qa/ft_retrieval_augmented_generation_qdrant.ipynb
index eb86b85b..52b10e24 100644
--- a/examples/fine-tuned_qa/ft_retrieval_augmented_generation_qdrant.ipynb
+++ b/examples/fine-tuned_qa/ft_retrieval_augmented_generation_qdrant.ipynb
@@ -256,7 +256,7 @@
"source": [
"### 3.2 Answering using Zero Shot Prompt\n",
"\n",
- "Next, you'll need some re-usable functions which make an OpenAI API Call and return the answer. You'll use the `ChatCompletion.create` endpoint of the API, which takes a prompt and returns the completed text."
+ "Next, you'll need some reusable functions which make an OpenAI API Call and return the answer. You'll use the `ChatCompletion.create` endpoint of the API, which takes a prompt and returns the completed text."
]
},
{
@@ -538,7 +538,7 @@
"\n",
"### 4.2 Fine-Tune OpenAI Model\n",
"\n",
- "If you're new to OpenAI Model Fine-Tuning, please refer to the [How to finetune Chat models](https://github.com/openai/openai-cookbook/blob/448a0595b84ced3bebc9a1568b625e748f9c1d60/examples/How_to_finetune_chat_models.ipynb) notebook. You can also refer to the [OpenAI Fine-Tuning Docs](platform.openai.com/docs/guides/fine-tuning/use-a-fine-tuned-model) for more details."
+ "If you're new to OpenAI Model Fine-Tuning, please refer to the [How to finetune Chat models](https://github.com/openai/openai-cookbook/blob/448a0595b84ced3bebc9a1568b625e748f9c1d60/examples/How_to_finetune_chat_models.ipynb) notebook. You can also refer to the [OpenAI fine-tuning docs](https://developers.openai.com/api/docs/guides/model-optimization) for more details."
]
},
{
diff --git a/examples/gpt-5/gpt-5_new_params_and_tools.ipynb b/examples/gpt-5/gpt-5_new_params_and_tools.ipynb
index ce389b09..7797b60f 100644
--- a/examples/gpt-5/gpt-5_new_params_and_tools.ipynb
+++ b/examples/gpt-5/gpt-5_new_params_and_tools.ipynb
@@ -503,7 +503,7 @@
"id": "fa48bbeb",
"metadata": {},
"source": [
- "Medium verboisty, generated richer code with additioanl explanations. Let's do the same with high. "
+ "Medium verbosity generated richer code with additional explanations. Next, let's try high verbosity. "
]
},
{
diff --git a/examples/gpt-5/gpt-5_prompting_guide.ipynb b/examples/gpt-5/gpt-5_prompting_guide.ipynb
index adafcf21..954e2952 100644
--- a/examples/gpt-5/gpt-5_prompting_guide.ipynb
+++ b/examples/gpt-5/gpt-5_prompting_guide.ipynb
@@ -445,7 +445,7 @@
"- After user confirmation, the order status will be kept 'pending'. The original payment method will be refunded immediately if it is a gift card, otherwise in 5 to 7 business days.\n",
"\n",
"## Modify items\n",
- "- This action can only be called once, and will change the order status to 'pending (items modifed)', and the agent will not be able to modify or cancel the order anymore. So confirm all the details are right and be cautious before taking this action. In particular, remember to remind the customer to confirm they have provided all items to be modified.\n",
+ "- This action can only be called once, and will change the order status to 'pending (items modified)', and the agent will not be able to modify or cancel the order anymore. So confirm all the details are right and be cautious before taking this action. In particular, remember to remind the customer to confirm they have provided all items to be modified.\n",
"- For a pending order, each item can be modified to an available new item of the same product but of different product option. There cannot be any change of product types, e.g. modify shirt to shoe.\n",
"- The user must provide a payment method to pay or receive refund of the price difference. If the user provides a gift card, it must have enough balance to cover the price difference.\n",
"\n",
diff --git a/examples/gpt-5/prompt-optimization-cookbook.ipynb b/examples/gpt-5/prompt-optimization-cookbook.ipynb
index d423fb9f..ffdca197 100644
--- a/examples/gpt-5/prompt-optimization-cookbook.ipynb
+++ b/examples/gpt-5/prompt-optimization-cookbook.ipynb
@@ -13,13 +13,13 @@
"id": "a3942231",
"metadata": {},
"source": [
- "The GPT-5 Family of models are the smartest models we’ve released to date, representing a step change in the models’ capabilities across the board. GPT-5 is particularly specialized in agentic task performance, coding, and steerability, making it a great fit for everyone from curious users to advanced researchers. \n",
+ "The GPT-5 family of models is the smartest models we’ve released to date, representing a step change in the models’ capabilities across the board. GPT-5 is particularly specialized in agentic task performance, coding, and steerability, making it a great fit for everyone from curious users to advanced researchers. \n",
"\n",
- "GPT-5 will benefit from all the traditional [prompting best practices](https://cookbook.openai.com/examples/gpt-5/gpt-5_prompting_guide), but to make optimizations and migrations easier, we are introducing the **[GPT-5 Prompt Optimizer](https://platform.openai.com/chat/edit?optimize=true)** in our Playground to help users get started on **improving existing prompts** and **migrating prompts** for GPT-5 and other OpenAI models.\n",
+ "GPT-5 will benefit from all the traditional [prompting best practices](https://cookbook.openai.com/examples/gpt-5/gpt-5_prompting_guide), but to make optimizations and migrations easier, we are introducing the **[GPT-5 Prompt Optimizer](https://platform.openai.com/chat/edit?optimize=true)** in our Playground to help users get started on **improving existing prompts** and **migrating prompts** for GPT-5 and other OpenAI models.\n",
"\n",
"![Prompt Optimizer demo](../../images/prompt-optimizer-3-22s.gif)\n",
"\n",
- "In this cookbook we will show you how to use the Prompt Optimzer to get spun up quickly to solve your tasks with GPT-5, while demonstrating how prompt optimize can have measurable improvements. "
+ "In this cookbook we will show you how to use the Prompt Optimizer to get spun up quickly to solve your tasks with GPT-5, while demonstrating how prompt optimization can yield measurable improvements. "
]
},
{
diff --git a/examples/gpt-5/prompt_personalities.ipynb b/examples/gpt-5/prompt_personalities.ipynb
index eb2d6dac..fccf5666 100644
--- a/examples/gpt-5/prompt_personalities.ipynb
+++ b/examples/gpt-5/prompt_personalities.ipynb
@@ -186,7 +186,7 @@
"id": "b720a3d2",
"metadata": {},
"source": [
- "For efficient personality, let's take example of when you just need a list of ingedients for a dish: **Grocery list for cooking tomato soup**"
+ "For the efficient personality, consider a case where you need only a list of ingredients for a dish: **Grocery list for cooking tomato soup**"
]
},
{
diff --git a/examples/mcp/databricks_mcp_cookbook.ipynb b/examples/mcp/databricks_mcp_cookbook.ipynb
index de1dcb7d..a94f53ef 100644
--- a/examples/mcp/databricks_mcp_cookbook.ipynb
+++ b/examples/mcp/databricks_mcp_cookbook.ipynb
@@ -141,7 +141,7 @@
"\n",
"![Pharma Network](../../images/pharma_network.png)\n",
"\n",
- "Answering supply-chain operations questions requires modelling how upstream bottlenecks cascade through production, logistics, and fulfilment so that stakeholders can shorten lead times, avoid excess stock, and control costs. The notebooks turn these raw feeds into governed, callable artefacts:\n",
+ "Answering supply-chain operations questions requires modelling how upstream bottlenecks cascade through production, logistics, and fulfillment so that stakeholders can shorten lead times, avoid excess stock, and control costs. The notebooks turn these raw feeds into governed, callable artefacts:\n",
"- Demand forecasting & aggregation ([notebook 2](https://github.com/lara-openai/databricks-supply-chain/blob/main/02_Fine_Grained_Demand_Forecasting.py)): Generates one-week-ahead SKU demand for every wholesaler and distribution center with a Holt-Winters seasonal model (or any preferred time-series approach). It leverages Spark’s parallelisation for large-scale forecasting tasks by using Pandas UDFs (taking your single node data science code and distributing it across multiple nodes). Forecasts are then rolled up to DC-level totals for each product. The output is a table  product_demand_forecasted with aggregate forecasts at the distribution center level.\n",
"- Raw-material planning ([notebook 3](https://github.com/lara-openai/databricks-supply-chain/blob/main/03_Derive_Raw_Material_Demand.py)): Constructs a product-to-material using graph processing, propagating demand up the bill-of-materials hierarchy to calculate component requirements at scale. We transform the bill‑of‑materials into a graph so product forecasts can be translated into precise raw‑material requirements, yielding two tables: raw_material_demand and raw_material_supply.\n",
"- Transportation optimisation ([notebook 4](https://github.com/lara-openai/databricks-supply-chain/blob/main/04_Optimize_Transportation.py)): Minimises plant to distribution center transportation cost under capacity and demand constraints, leveraging Pandas UDFs, outputting recommendations in shipment_recommendations.\n",
@@ -812,7 +812,7 @@
"- Databricks Managed MCP [documentation](https://docs.databricks.com/aws/en/generative-ai/agent-framework/mcp)\n",
"- OpenAI Agent SDK [documentation](https://openai.github.io/openai-agents-python/)\n",
"- OpenAI Agent Guardrails [documentation](https://openai.github.io/openai-agents-python/guardrails/)\n",
- "- Openai-agents-python example [snippets](https://github.com/openai/openai-agents-python/tree/main/examples/mcp/streamablehttp_example)"
+ "- `openai-agents-python` example [snippets](https://github.com/openai/openai-agents-python/tree/main/examples/mcp/streamablehttp_example)"
]
}
],
diff --git a/examples/mcp/mcp_tool_guide.ipynb b/examples/mcp/mcp_tool_guide.ipynb
index 18a1f601..0ced67e8 100644
--- a/examples/mcp/mcp_tool_guide.ipynb
+++ b/examples/mcp/mcp_tool_guide.ipynb
@@ -408,9 +408,9 @@
"source": [
"### Prompting guidelines to improve MCP tool calls\n",
"\n",
- "Depending on your use case you might find that the model invokes many MCP calls, for instance when using catalog-search tools. To avoid endless iterations over large product inventories it’s helpful to instruct the model to limit it’s search to N items and to offer to continue only when the user explicitly asks for more information. This keeps responses focused and snappy.\n",
+ "Depending on your use case you might find that the model invokes many MCP calls, for instance when using catalog-search tools. To avoid endless iterations over large product inventories it’s helpful to instruct the model to limit its search to N items and to offer to continue only when the user explicitly asks for more information. This keeps responses focused and snappy.\n",
"\n",
- "If the MCP servers you’re using include exhaustive `mcp_list_tools`, it’s also worth Including some targeted few-shot examples to show the model how to choose the correct server and to stop once it has what it needs, instead of issuing redundant calls.\n",
+ "If the MCP servers you’re using include exhaustive `mcp_list_tools`, it’s also worth including some targeted few-shot examples to show the model how to choose the correct server and to stop once it has what it needs, instead of issuing redundant calls.\n",
"\n",
"Finally, adding guidance to remind the model that if essential information (size, color, product line, etc.) is missing from the user query, it should ask a follow-up question rather than launching a broad search. This small prompt nudge reduces unnecessary tool calls and improves answer quality. Here’s a sample prompt that shows how these guidelines come together:"
]
diff --git a/examples/multimodal/Using_GPT4_Vision_With_Function_Calling.ipynb b/examples/multimodal/Using_GPT4_Vision_With_Function_Calling.ipynb
index 8291ad08..07ff5e15 100644
--- a/examples/multimodal/Using_GPT4_Vision_With_Function_Calling.ipynb
+++ b/examples/multimodal/Using_GPT4_Vision_With_Function_Calling.ipynb
@@ -9,7 +9,7 @@
"source": [
"# How to use GPT-4o Vision with Function Calling \n",
"\n",
- "The GPT-4o, available as gpt-4o-2024-11-20 as of Novemeber 2024, now enables function calling with vision capabilities, better reasoning and a knowledge cutoff date of Oct 2023. Using images with function calling will unlock multimodal use cases and the ability to use reasoning, allowing you to go beyond OCR and image descriptions.\n",
+ "The GPT-4o, available as gpt-4o-2024-11-20 as of November 2024, now enables function calling with vision capabilities, better reasoning and a knowledge cutoff date of Oct 2023. Using images with function calling will unlock multimodal use cases and the ability to use reasoning, allowing you to go beyond OCR and image descriptions.\n",
"\n",
"We will go through two examples to demonstrate the use of function calling with GPT-4o with Vision:\n",
"\n",
diff --git a/examples/multimodal/Vision_Fine_tuning_on_GPT4o_for_Visual_Question_Answering.ipynb b/examples/multimodal/Vision_Fine_tuning_on_GPT4o_for_Visual_Question_Answering.ipynb
index 8050aaa2..faafe956 100644
--- a/examples/multimodal/Vision_Fine_tuning_on_GPT4o_for_Visual_Question_Answering.ipynb
+++ b/examples/multimodal/Vision_Fine_tuning_on_GPT4o_for_Visual_Question_Answering.ipynb
@@ -269,7 +269,7 @@
"source": [
"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.\n",
"\n",
- "This function allows us to control the quality of the image encoding, which can be useful if we want to reduce the size of the file. 100 is the highest quality, and 1 is the lowest. The maximum file size for a fine-tuning job is 1GB, but we are unlikely to see improvements with a very large amount of training data. Nevertheless, we can use the `quality` parameter to reduce the size of the file if needed to accomodate file size limits."
+ "This function allows us to control the quality of the image encoding, which can be useful if we want to reduce the size of the file. 100 is the highest quality, and 1 is the lowest. The maximum file size for a fine-tuning job is 1GB, but we are unlikely to see improvements with a very large amount of training data. Nevertheless, we can use the `quality` parameter to reduce the size of the file if needed to accommodate file size limits."
]
},
{
@@ -749,7 +749,7 @@
"However, there are also cases where the model’s **predicted answers** are close to the **ground truth**, while not matching 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.\n",
"\n",
"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:\n",
- "* **Very Similar**: The predicted answer exactly matches the ground truth and there is no important information omitted, although there may be some minor ommissions or discrepancies in punctuation.\n",
+ "* **Very Similar**: The predicted answer exactly matches the ground truth and no important information is omitted, although there may be some minor omissions or discrepancies in punctuation.\n",
"\n",
"* **Mostly Similar**: The predicted answer closely aligns with the ground truth, perhaps with some missing words or phrases.\n",
"\n",
@@ -1118,9 +1118,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "It appears that the largest performance gains for the fine-tuned model are for questions in the **Genre** category e.g. \"What type of book is this?\" or \"What is the genre of this book?\". This might be indicative of the benefits of fine-tuning in general in that we teach the model to classify genres based on the categories present in the training data. However, it also highlights the model's strong visual undserstanding capabilties, since we are able to identify the genre based on the visual content of the book cover alone.\n",
+ "It appears that the largest performance gains for the fine-tuned model are for questions in the **Genre** category, such as \"What type of book is this?\" or \"What is the genre of this book?\" This may demonstrate a benefit of fine-tuning: we teach the model to classify genres based on the categories present in the training data. It also highlights the model's strong visual understanding capabilities, since the model can identify the genre from the visual content of the book cover alone.\n",
"\n",
- "Additionally, we see significant lift in the **Title** category, which suggests that fine-tuning has boosted the model's OCR capbilities and its ability to understand the layout and structure of the book cover to extract the relevant information.\n",
+ "Additionally, we see significant lift in the **Title** category, which suggests that fine-tuning has boosted the model's OCR capabilities and its ability to understand the layout and structure of the book cover to extract the relevant information.\n",
"\n",
"Finally, let's compare the distribution of similarity ratings between the fine-tuned model and the non-fine-tuned model to allow for variations in phrasing and wording."
]
diff --git a/examples/multimodal/image_evals.ipynb b/examples/multimodal/image_evals.ipynb
index 45efc373..e82560be 100644
--- a/examples/multimodal/image_evals.ipynb
+++ b/examples/multimodal/image_evals.ipynb
@@ -978,7 +978,7 @@
" load. \n",
"4. **Exact CTA text** (primary button text must be exactly “Place\n",
" Order”) - tests in-image text rendering fidelity. \n",
- "5. **Secondary action presence (i**nclude both “Edit Cart” and “Change\n",
+ "5. **Secondary action presence** (include both “Edit Cart” and “Change\n",
" payment method”) - tests secondary actions remain visually\n",
" subordinate. \n",
"6. **Placement constraint** (require order total directly above the\n",
diff --git a/examples/o1/Using_chained_calls_for_o1_structured_outputs.ipynb b/examples/o1/Using_chained_calls_for_o1_structured_outputs.ipynb
index 854b868a..24451386 100644
--- a/examples/o1/Using_chained_calls_for_o1_structured_outputs.ipynb
+++ b/examples/o1/Using_chained_calls_for_o1_structured_outputs.ipynb
@@ -226,9 +226,9 @@
"source": [
"# Conclusion\n",
"\n",
- "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.\n",
+ "Structured outputs allow your code to have reliable type-safety and simpler prompting. In addition, it allows you to reuse your object schemas for easier integration into your existing workflows.\n",
"\n",
- "The o1 class of models currently doesn'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."
+ "The o1 class of models currently doesn't have structured outputs support, but we can reuse 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."
]
}
],
diff --git a/examples/o1/Using_reasoning_for_routine_generation.ipynb b/examples/o1/Using_reasoning_for_routine_generation.ipynb
index 31dc3c04..8449de66 100644
--- a/examples/o1/Using_reasoning_for_routine_generation.ipynb
+++ b/examples/o1/Using_reasoning_for_routine_generation.ipynb
@@ -61,7 +61,7 @@
"- Converting the policy from an external facing document to an internal SOP routine\n",
"- Breaking down the policy in specific actions and sub-actions\n",
"- Outlining specific conditions for moving between steps\n",
- "- Determing where external knowledge/actions may be required, and defining functions that we could use to get that information"
+ "- Determining where external knowledge/actions may be required, and defining functions that we could use to get that information"
]
},
{
diff --git a/examples/object_oriented_agentic_approach/Secure_code_interpreter_tool_for_LLM_agents.ipynb b/examples/object_oriented_agentic_approach/Secure_code_interpreter_tool_for_LLM_agents.ipynb
index d5d87c83..45b58c47 100644
--- a/examples/object_oriented_agentic_approach/Secure_code_interpreter_tool_for_LLM_agents.ipynb
+++ b/examples/object_oriented_agentic_approach/Secure_code_interpreter_tool_for_LLM_agents.ipynb
@@ -67,7 +67,7 @@
"- Do higher fines correlate with lower average speeds or reduced accidents? (Correlation/Regression)\n",
"- and so on ...\n",
"\n",
- "Using the traditional **Predefined Tool Calling** approach, developer would need to pre-define the function for each of these questions. This limits the LLM's ability to answer any other questions not defined in the pre-defined set of functions. We overcome this limitation by using the **Dynamic Tool Calling** approach where the LLM generates code and uses a Code Interpretter tool to execute the code. "
+ "Using the traditional **Predefined Tool Calling** approach, a developer would need to pre-define the function for each of these questions. This limits the LLM's ability to answer any other questions not defined in the pre-defined set of functions. We overcome this limitation by using the **Dynamic Tool Calling** approach where the LLM generates code and uses a Code Interpreter tool to execute the code. "
]
},
{
@@ -76,7 +76,7 @@
"metadata": {},
"source": [
"## Overview\n",
- "Let's dive into the steps to build this Agentic Applicaiton with Dynamically generated tool calling. There are three components to this application:"
+ "Let's dive into the steps to build this Agentic Application with Dynamically generated tool calling. There are three components to this application:"
]
},
{
@@ -254,7 +254,7 @@
"- Uses gpt-4o model.\n",
"\n",
"2.\t**Agent 2: Python Code Generator and Executor (with Dynamically Generated Tool Calling and Code Execution)**\n",
- "- Recieve the file content's context from Agent 1.\n",
+ "- Receive the file content's context from Agent 1.\n",
"- Instructions to generate a Python script to answer the user's question.\n",
"- Has access to the code interpreter within the Docker container, which is used to execute Python code.\n",
"- Has access only to the file system inside the Docker container (not the host).\n",
@@ -306,7 +306,7 @@
"source": [
"**Define Agent 1: FileAccessAgent with FileAccessTool**\n",
"\n",
- "Let's start with definin the FileAccessTool that inherits from the ToolInterface class. The **FileAccessTool** tool is defined in the [file_access_tool.py](https://github.com/openai/openai-cookbook/blob/main/examples/object_oriented_agentic_approach/resources/registry/tools/file_access_tool.py) file in the `resources/registry/tools` directory.\n",
+ "Let's start with defining the FileAccessTool that inherits from the ToolInterface class. The **FileAccessTool** tool is defined in the [file_access_tool.py](https://github.com/openai/openai-cookbook/blob/main/examples/object_oriented_agentic_approach/resources/registry/tools/file_access_tool.py) file in the `resources/registry/tools` directory.\n",
"\n",
"- FileAccessTool implements the ToolInterface class, which ensures that the tools will have a consistent interface. \n",
"- Binding the tool definition for the OpenAI Function Calling API in the `get_definition` method and the tool's `run` method ensures maintainability, scalability, and reusability. "
@@ -317,7 +317,7 @@
"id": "643f349e",
"metadata": {},
"source": [
- "Now, let's define the **FileAccessAgent** that extends the BaseAgent class and bind the **FileAccessTool** to the agent. The FileAccessAgent is defined in the [file_acess_agent.py](https://github.com/openai/openai-cookbook/blob/main/examples/object_oriented_agentic_approach/resources/registry/agents/file_access_agent.py) file in `resources/registry/agents` directory. The FileAccessAgent is:\n",
+ "Now, let's define the **FileAccessAgent** that extends the BaseAgent class and bind the **FileAccessTool** to the agent. The FileAccessAgent is defined in the [file_access_agent.py](https://github.com/openai/openai-cookbook/blob/main/examples/object_oriented_agentic_approach/resources/registry/agents/file_access_agent.py) file in `resources/registry/agents` directory. The FileAccessAgent is:\n",
"\n",
"- A concrete implementation of the BaseAgent class. \n",
"- Initialized with the developer prompt, model name, logger, and language model interface. These values can be overridden by the developer if needed. \n",
diff --git a/examples/partners/eval_driven_system_design/receipt_inspection.ipynb b/examples/partners/eval_driven_system_design/receipt_inspection.ipynb
index ac5c5917..2736a800 100644
--- a/examples/partners/eval_driven_system_design/receipt_inspection.ipynb
+++ b/examples/partners/eval_driven_system_design/receipt_inspection.ipynb
@@ -781,7 +781,7 @@
"check for a specific field in a structured output, or a more holistic check that\n",
"judges an output in its entirety. Some graders can work without context, and evaluate an\n",
"output in isolation (for example, an LLM judge that is evaluating if a paragraph is rude\n",
- "or inappropriate). Others can evaluate based on the input and output, while while the\n",
+ "or inappropriate). Others can evaluate based on the input and output, while the\n",
"ones we're using here rely on an output and a ground-truth (correct) output to compare\n",
"against.\n",
"\n",
@@ -1355,7 +1355,7 @@
"\n",
"Above, we noted that we get merchant names wrong 85% of the time, more than any other\n",
"output we're evaluating. This looks pretty bad, and it's probably something we can\n",
- "improve dramaticaly with only a little work, but instead let's start from the endpoint\n",
+ "improve dramatically with only a little work, but instead let's start from the endpoint\n",
"of our business metrics and work backwards to see what issues caused incorrect\n",
"decisions.\n",
"\n",
@@ -1375,7 +1375,7 @@
"explaining the decision process in more detail and providing an analogous example would\n",
"correct the error.\n",
"\n",
- "In the second case, the purchase is some tools from a home improvement score. The tools\n",
+ "In the second case, the purchase is some tools from a home improvement store. The tools\n",
"don't have anything to do with normal driving, so this receipt should be audited as a\n",
"\"non-travel-related expense\". In this case our model *correctly* identifies it as an\n",
"expense that's not travel-related, but then reasons incorrectly about that fact,\n",
@@ -1615,7 +1615,7 @@
" travel-related expense.\n",
"```\n",
"\n",
- "2. We added more proscriptive guidance on how to evaluate for a math error.\n",
+ "2. We added more prescriptive guidance on how to evaluate for a math error.\n",
" Specifically, we added the bullet points:\n",
"\n",
"```\n",
@@ -1642,7 +1642,6 @@
"```\n",
"\n",
"4. We added three examples, JSON input/output pairs wrapped in XML tags.\n",
- "3. We added three examples, JSON input/output pairs wrapped in XML tags.\n",
"\n",
"With our prompt revisions, we'll regenerate the data to evaluate and re-run the same\n",
"eval to compare our results:"
diff --git a/examples/partners/mcp_powered_voice_agents/mcp_powered_agents_cookbook.ipynb b/examples/partners/mcp_powered_voice_agents/mcp_powered_agents_cookbook.ipynb
index 3008b80c..a161e4fb 100644
--- a/examples/partners/mcp_powered_voice_agents/mcp_powered_agents_cookbook.ipynb
+++ b/examples/partners/mcp_powered_voice_agents/mcp_powered_agents_cookbook.ipynb
@@ -304,7 +304,7 @@
"\n",
"While implementing custom MCPs servers is relatively straightforward, the power of MCP is the ability to use pre-defined servers that others have built and maintain. Using existing implementations enables more rapid development, has a consistent interface with other tools, and makes data integration more seamless. \n",
"\n",
- "For our database lookup tool, we use the prebuilt [SQLite server](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/sqlite) implementation. As you will see below, we can implement this simply with just a comand line prompt and providing it with a `*.db` file with the data."
+ "For our database lookup tool, we use the prebuilt [SQLite server](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/sqlite) implementation. As you will see below, we can implement this simply with just a command line prompt and providing it with a `*.db` file with the data."
]
},
{
diff --git a/examples/partners/self_evolving_agents/autonomous_agent_retraining.ipynb b/examples/partners/self_evolving_agents/autonomous_agent_retraining.ipynb
index 7a127b07..c8692d0f 100644
--- a/examples/partners/self_evolving_agents/autonomous_agent_retraining.ipynb
+++ b/examples/partners/self_evolving_agents/autonomous_agent_retraining.ipynb
@@ -83,7 +83,7 @@
"\n",
"For the remainder of this cookbook, we implemented a simplified version of the Summarizer agent (see the section **Agent Setup** below). Alternatively, you can reuse the code for the agent created with AgentBuilder. If you’d like to reproduce the agent directly from the AgentBuilder UI, here are the key prompts and parameters used:\n",
"\n",
- "- **Summarizer agent:** This agent used the file search tool, where the [CMC PDF](\"data/c13_pyruvate_sample_CMC_from_UCSF.pdf\") was uploaded to the vector store.\n",
+ "- **Summarizer agent:** This agent used the file search tool, where the [CMC PDF](data/c13_pyruvate_sample_CMC_from_UCSF.pdf) was uploaded to the vector store.\n",
"> _Prompt:_ \"Summarize section {{workflow.input_as_text}} from {{state.cmc_pdf}} uploaded to the vector store.\"\n",
"\n",
"- **Compliance Checker agent:**\n",
@@ -1874,7 +1874,7 @@
"source": [
"## Contributors\n",
"\n",
- "This cookbook is based on a joint collaboration between [Bain](www.bain.com) and [OpenAI](openai.com). \n",
+ "This cookbook is based on a joint collaboration between [Bain](https://www.bain.com) and [OpenAI](https://openai.com). \n",
"\n",
"[Calvin Maguranis](https://www.linkedin.com/in/calvin-maguranis-b9956045/) \n",
"[Fanny Perraudeau](https://www.linkedin.com/in/fanny-sabran-perraudeau-494b7573/) \n",
diff --git a/examples/partners/temporal_agents_with_knowledge_graphs/temporal_agents.ipynb b/examples/partners/temporal_agents_with_knowledge_graphs/temporal_agents.ipynb
index c86e13c2..4f8c7b1f 100644
--- a/examples/partners/temporal_agents_with_knowledge_graphs/temporal_agents.ipynb
+++ b/examples/partners/temporal_agents_with_knowledge_graphs/temporal_agents.ipynb
@@ -421,7 +421,7 @@
" Labels each statement as <strong>Atemporal</strong>, <strong>Static</strong>, or <strong>Dynamic</strong>:\n",
" </p>\n",
" <ul style=\"margin-top: 0.5em; margin-bottom: 0.5em; padding-left: 1em;\">\n",
- " <li style=\"margin-bottom: 0.5em;\"><em>Atemporal</em> statements never change (e.g., “The speed of light in a vaccuum is ≈3×10⁸ m s⁻¹”).</li>\n",
+ " <li style=\"margin-bottom: 0.5em;\"><em>Atemporal</em> statements never change (e.g., “The speed of light in a vacuum is ≈3×10⁸ m s⁻¹”).</li>\n",
" <li style=\"margin-bottom: 0.5em;\"><em>Static</em> statements are valid from a point in time but do not change afterwards (e.g., \"Person YY was CEO of Company XX on October 23rd 2014.\").</li>\n",
" <li><em>Dynamic</em> statements evolve (e.g., \"Person YY is CEO of Company XX.\").</li>\n",
" </ul>\n",
@@ -674,9 +674,9 @@
"\n",
"Before we get to processing this data, let’s set up our database. \n",
"\n",
- "For convenience within a notebook format, we've chosen SQLite as our database for this implementation. In the \"Prototype to Production\" section, and in [Appendix section A.1 \"Storing and Retrieving High-Volume Graph Data\"](./Appendix.ipynb) we go into more detail of considerations around different dataset choices in a production environment. \n",
+ "For convenience within a notebook format, we've chosen SQLite as our database for this implementation. In the \"Prototype to Production\" section and [Appendix section A.1, \"Storing and Retrieving High-Volume Graph Data\"](#a1-storing-and-retrieving-high-volume-graph-data), we discuss considerations for different dataset choices in a production environment. \n",
"\n",
- "If you are running this cookbook locally, you may chose to set `memory = False` to save the database to storage, the default file path `my_database.db` will be used to store your database or you may pass your own `db_path` arg into `make_connection`.\n",
+ "If you are running this cookbook locally, you may choose to set `memory = False` to save the database to storage. The default file path, `my_database.db`, will be used, or you may pass your own `db_path` argument to `make_connection`.\n",
"\n",
"We will set up several tables to store the following information:\n",
"- Transcripts\n",
@@ -710,7 +710,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Before diving into buidling the `Chunker` class itself, we begin by defining our first data models. As is generally considered good practice when working with Python, [Pydantic](https://docs.pydantic.dev/latest/) is used to ensure type safety and clarity in our model definitions. Pydantic provides a clean, declarative way to define data structures whilst automatically validating and parsing input data, making our data models both robust and easy to work with."
+ "Before diving into building the `Chunker` class itself, we begin by defining our first data models. As is generally considered good practice when working with Python, [Pydantic](https://docs.pydantic.dev/latest/) is used to ensure type safety and clarity in our model definitions. Pydantic provides a clean, declarative way to define data structures whilst automatically validating and parsing input data, making our data models both robust and easy to work with."
]
},
{
@@ -1958,7 +1958,7 @@
"\n",
"To define your own predicates:\n",
"1. First, run your pipeline with `PREDICATE_DEFINITIONS = {}` on a representative sample of your documents. This initial run will derive a noisy graph with many non-standardized and overlapping predicates\n",
- "2. Next, drop some of your intial results into [ChatGPT](https://chatgpt.com/) or manually review them to merge similar predicate classes. This process helps to eliminate duplicates such as `IS_CEO` and `IS_CEO_OF`\n",
+ "2. Next, drop some of your initial results into [ChatGPT](https://chatgpt.com/) or manually review them to merge similar predicate classes. This process helps to eliminate duplicates such as `IS_CEO` and `IS_CEO_OF`\n",
"3. Finally, carefully review and refine this list of predicates to ensure clarity and precision. These finalized predicate definitions will then guide your extraction process and ensure a consistent extraction pipeline"
]
},
@@ -2065,7 +2065,7 @@
"The `RawEntity` model represents an Entity as extracted from the `Statement`. This serves as a precursor for the more detailed triplet representation in `Entity` which we introduce next. \n",
"\n",
"Core fields: \n",
- "- `entity_idx`: An integer to differentiate extracted entites from the statement (links to `RawTriplet`)\n",
+ "- `entity_idx`: An integer to differentiate extracted entities from the statement (links to `RawTriplet`)\n",
"- `name`: The name of the entity extracted e.g. `AMD`\n",
"- `type`: The type of entity extracted e.g. `Company`\n",
"- `description`: The textual description of the entity e.g. `Technology company know for manufacturing semiconductors`"
@@ -4049,7 +4049,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "We can then ingest the rest of the Transcripts. Note that this code has not been optimised to be production ready and on average takes 2-5 mins per Transcript. This bulk ingestion using the data in /transcripts (~30 files) will take up to 2 hours to run. Optimizing this is a critical step in scaling to production. We outline some methods you can use to approach this in the Appendix in [A.3 \"Implementing Concurrency in the Ingestion Pipeline\"](./Appendix.ipynb), including batch chunking, entity clustering, and more. "
+ "We can then ingest the rest of the Transcripts. Note that this code has not been optimised to be production ready and on average takes 2-5 mins per Transcript. This bulk ingestion using the data in /transcripts (~30 files) will take up to 2 hours to run. Optimizing this is a critical step in scaling to production. We outline some methods you can use to approach this in Appendix section [A.3, \"Implementing Concurrency in the Ingestion Pipeline\"](#a3-implementing-concurrency-in-the-ingestion-pipeline), including batch chunking, entity clustering, and more. "
]
},
{
@@ -4956,7 +4956,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "The approach presented above offers a foundational implementation of a Temporal Agent for knowledge graph construction. However, it does not fully address complexities or all possible edge cases encountered in real-world applications. Below, we outline several possible enhancements that could be used to further improve the robustness and applicability of this implementation. In the later \"Prototype to Production\" section, we expand on these enhancements by suggesting additional considerations essential for deploying such agents effectively in production environments. Further details on scaling to production are included in the [Appendix](./Appendix.ipynb)."
+ "The approach presented above offers a foundational implementation of a Temporal Agent for knowledge graph construction. However, it does not fully address complexities or all possible edge cases encountered in real-world applications. Below, we outline several possible enhancements that could be used to further improve the robustness and applicability of this implementation. In the later \"Prototype to Production\" section, we expand on these enhancements by suggesting additional considerations essential for deploying such agents effectively in production environments. Further details on scaling to production are included in the [Appendix](#appendix)."
]
},
{
@@ -4987,7 +4987,7 @@
"metadata": {},
"source": [
"#### Date Extraction\n",
- "The implementation in this cookbook does not explictly record assumptions made during date disambiguation. \n",
+ "The implementation in this cookbook does not explicitly record assumptions made during date disambiguation. \n",
"\n",
"In the absence of an explicit publication date, the present date is used implicitly as a reference. For some workflows, this assumption may have to be changed to meet the needs of the end users. \n",
"\n",
@@ -5780,7 +5780,7 @@
"metadata": {},
"source": [
"##### Trend analysis\n",
- "The `trend_analysis` tool is designed to compare how specific metrics or signals evolve over time—often across multiple companies and/or topics. It exposes a structured interface that lets the agent specify the time window, subject set, and target metric, then delegates the comparison logic to a specialised agent for handling this analysis. In this case we utilised o4-mini with high reasoning effort as this is a 'harder' anaysis task.\n",
+ "The `trend_analysis` tool is designed to compare how specific metrics or signals evolve over time—often across multiple companies and/or topics. It exposes a structured interface that lets the agent specify the time window, subject set, and target metric, then delegates the comparison logic to a specialised agent for handling this analysis. In this case we utilised o4-mini with high reasoning effort as this is a 'harder' analysis task.\n",
"\n",
"This allows us to build a highly focused and optimised pipeline for dealing with comparison-style tasks. Whilst this could be built into the core orchestrator itself, it's often more manageable to split this into specialised tools so they can be more easily swapped out or updated later without much concern for impact on the wider system."
]
@@ -6105,7 +6105,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "[Appendix section A.5. \"Scaling and Productionizing our Retrieval Agent\"](./Appendix.ipynb) outlines some guidelines for how one could take the Retrieval Agent we've built up to production."
+ "[Appendix section A.5, \"Scaling and Productionizing our Retrieval Agent\"](#a5-scaling-and-productionizing-our-retrieval-agent) outlines guidelines for taking the Retrieval Agent we've built into production."
]
},
{
@@ -6223,7 +6223,7 @@
"source": [
"Transitioning your knowledge graph system from a proof-of-concept to a robust, production-grade pipeline requires you to address several key points:\n",
"- **Storing and retrieving high-volume graph data**\n",
- "- **Mananging and pruning datasets**\n",
+ "- **Managing and pruning datasets**\n",
"- **Implementing concurrency in the ingestion pipeline**\n",
"- **Minimizing token cost**\n",
"- **Scaling retrieval agents**\n",
@@ -6527,7 +6527,7 @@
"##### Best practices\n",
"- `flat` for debugging or small datasets\n",
"- `ivfflat` when you want tunable accuracy with good speed\n",
- "- `ivfpq` when memory efficieny is critical\n",
+ "- `ivfpq` when memory efficiency is critical\n",
"- `hnsw` when optimizing for lowest latency on massive collections\n",
"\n",
"##### Other vector database options in the ecosystem\n",
@@ -6758,7 +6758,7 @@
"Avoid redundant API calls by memoizing responses to brittle sub-prompts.\n",
"\n",
"Implementation Strategy:\n",
- "- **Cache Frequent Queries**: For example, repeated prompts like \"Extract entities from this statement\" on identicial statements\n",
+ "- **Cache Frequent Queries**: For example, repeated prompts like \"Extract entities from this statement\" on identical statements\n",
"- **Use Hash Keys**: Generate a unique cache key using the MD5 hash of the statement text: `md5(statement_text)`\n",
"- **Storage Options**: Redis for scalable persistence or in-memory LRU cache for simplicity and speed\n",
"- **Bypass API Calls**: If a statement is found in cache, skip the API call"
diff --git a/examples/reasoning_function_calls.ipynb b/examples/reasoning_function_calls.ipynb
index 935eed28..70b4bcd1 100644
--- a/examples/reasoning_function_calls.ipynb
+++ b/examples/reasoning_function_calls.ipynb
@@ -337,7 +337,7 @@
"As such, we ought to define a general pattern which we can use to handle arbitrarily complex reasoning workflows:\n",
"* At each step in the conversation, initialise a loop\n",
"* If the response contains function calls, we must assume the reasoning is ongoing and we should feed the function results (and any intermediate reasoning) back into the model for further inference\n",
- "* If there are no function calls and we instead receive a Reponse.output with a type of 'message', we can safely assume the agent has finished reasoning and we can break out of the loop"
+ "* If there are no function calls and we instead receive a response.output with a type of 'message', we can safely assume the agent has finished reasoning and we can break out of the loop"
]
},
{
@@ -546,7 +546,7 @@
"Let's run through the example above again, orchestrating the messages ourselves and tracking token usage.\n",
"\n",
"---\n",
- "*Note that the code below is structured for readibility - in practice you may wish to consider a more sophisticated workflow to handle edge cases*"
+ "*Note that the code below is structured for readability - in practice you may wish to consider a more sophisticated workflow to handle edge cases*"
]
},
{
diff --git a/examples/third_party/GPT_finetuning_with_wandb.ipynb b/examples/third_party/GPT_finetuning_with_wandb.ipynb
index 3a305118..852bc66a 100644
--- a/examples/third_party/GPT_finetuning_with_wandb.ipynb
+++ b/examples/third_party/GPT_finetuning_with_wandb.ipynb
@@ -109,7 +109,7 @@
"id": "X7h1WmYRU2dr"
},
"source": [
- "Start your Weigths & Biases run. If you don't have an account you can sign up for one for free at www.wandb.ai"
+ "Start your Weights & Biases run. If you don't have an account you can sign up for one for free at www.wandb.ai"
]
},
{
@@ -325,7 +325,7 @@
"id": "2Ul1lOV8U2dt"
},
"source": [
- "### Save the data to Weigths & Biases\n",
+ "### Save the data to Weights & Biases\n",
"\n",
"Save the data in a train and test file first"
]
@@ -571,7 +571,7 @@
"id": "C83jxUI9U2dt"
},
"source": [
- "Log our data to Weigths & Biases Artifacts for storage and versioning"
+ "Log our data to Weights & Biases Artifacts for storage and versioning"
]
},
{
@@ -856,7 +856,7 @@
"id": "Dh86AmJuU2du"
},
"source": [
- "Then we upload the training data to OpenAI. OpenAi has to process the data, so this will take a few minutes depending on the size of your dataset."
+ "Then we upload the training data to OpenAI. OpenAI has to process the data, so this will take a few minutes depending on the size of your dataset."
]
},
{
@@ -994,7 +994,7 @@
"id": "f-X8R7ILU2du"
},
"source": [
- "**Thats it!**\n",
+ "**That's it!**\n",
"\n",
"Now your model is training on OpenAI's machines. To get the current state of your fine-tuning job, run:"
]
@@ -1349,7 +1349,7 @@
"id": "xfX_af2EU2dz"
},
"source": [
- "## Run evalution and log the results"
+ "## Run evaluation and log the results"
]
},
{
@@ -1805,7 +1805,7 @@
"id": "A9nh4b15U2d1"
},
"source": [
- "And thats it! In this example we have prepared our data, logged it to Weights & Biases, fine-tuned an OpenAI model using that data, logged the results to Weights & Biases and then run evaluation on the fine-tuned model.\n",
+ "And that's it! In this example we have prepared our data, logged it to Weights & Biases, fine-tuned an OpenAI model using that data, logged the results to Weights & Biases and then run evaluation on the fine-tuned model.\n",
"\n",
"From here you can start to train on larger or more complex tasks, or else explore other ways to modify ChatGPT-3.5 such as giving it a different tone and style or response.\n"
]
diff --git a/examples/third_party/How_to_automate_S3_storage_with_functions.ipynb b/examples/third_party/How_to_automate_S3_storage_with_functions.ipynb
index df0fabde..614b2861 100644
--- a/examples/third_party/How_to_automate_S3_storage_with_functions.ipynb
+++ b/examples/third_party/How_to_automate_S3_storage_with_functions.ipynb
@@ -18,7 +18,7 @@
"This code demonstrates how to interact with ChatGPT functions to perform tasks related to Amazon S3 buckets. The notebook covers S3 bucket key functionalities such as running simple listing commands, searching for a specific file in all buckets, uploading a file to a bucket, and downloading a file from a bucket. The OpenAI Chat API understands the user instructions, generates the natural language responses, and extracts appropriate function calls based on the user's input.\n",
"\n",
"**Requirements**:\n",
- "To run the notebook generate AWS access key with S3 bucket writing permission and store them in a local environment file alongside the Openai key. The \"`.env`\" file format:\n",
+ "To run the notebook generate AWS access key with S3 bucket writing permission and store them in a local environment file alongside the OpenAI key. The \"`.env`\" file format:\n",
"```\n",
"AWS_ACCESS_KEY_ID=<your-key>\n",
"AWS_SECRET_ACCESS_KEY=<your-key>\n",
diff --git a/examples/third_party/Visualizing_embeddings_in_wandb.ipynb b/examples/third_party/Visualizing_embeddings_in_wandb.ipynb
index 6cb58aa4..7bdc3ea7 100644
--- a/examples/third_party/Visualizing_embeddings_in_wandb.ipynb
+++ b/examples/third_party/Visualizing_embeddings_in_wandb.ipynb
@@ -7,7 +7,7 @@
"source": [
"## Visualizing embeddings in W&B\n",
"\n",
- "We will upload the data to [Weights & Biases](http://wandb.ai) and use an [Embedding Projector](https://docs.wandb.ai/ref/app/features/panels/weave/embedding-projector) to visualize the embeddings using common dimension reduction algorithms like PCA, UMAP, and t-SNE. The dataset is created in the [Get_embeddings_from_dataset Notebook](Get_embeddings_from_dataset.ipynb)."
+ "We will upload the data to [Weights & Biases](http://wandb.ai) and use an [Embedding Projector](https://docs.wandb.ai/ref/app/features/panels/weave/embedding-projector) to visualize the embeddings using common dimension reduction algorithms like PCA, UMAP, and t-SNE. The dataset is created in the [Get_embeddings_from_dataset Notebook](../Get_embeddings_from_dataset.ipynb)."
]
},
{
diff --git a/examples/vector_databases/azuresearch/Getting_started_with_azure_ai_search_and_openai.ipynb b/examples/vector_databases/azuresearch/Getting_started_with_azure_ai_search_and_openai.ipynb
index 194ce17e..3d8adfb0 100644
--- a/examples/vector_databases/azuresearch/Getting_started_with_azure_ai_search_and_openai.ipynb
+++ b/examples/vector_databases/azuresearch/Getting_started_with_azure_ai_search_and_openai.ipynb
@@ -13,7 +13,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "This notebook provides step by step instuctions on using Azure AI Search (f.k.a Azure Cognitive Search) as a vector database with OpenAI embeddings. Azure AI Search is a cloud search service that gives developers infrastructure, APIs, and tools for building a rich search experience over private, heterogeneous content in web, mobile, and enterprise applications.\n",
+ "This notebook provides step-by-step instructions on using Azure AI Search (f.k.a Azure Cognitive Search) as a vector database with OpenAI embeddings. Azure AI Search is a cloud search service that gives developers infrastructure, APIs, and tools for building a rich search experience over private, heterogeneous content in web, mobile, and enterprise applications.\n",
"\n",
"## Prerequistites:\n",
"For the purposes of this exercise you must have the following:\n",
diff --git a/examples/vector_databases/cassandra_astradb/Philosophical_Quotes_AstraPy.ipynb b/examples/vector_databases/cassandra_astradb/Philosophical_Quotes_AstraPy.ipynb
index ace1c8ba..d399f307 100644
--- a/examples/vector_databases/cassandra_astradb/Philosophical_Quotes_AstraPy.ipynb
+++ b/examples/vector_databases/cassandra_astradb/Philosophical_Quotes_AstraPy.ipynb
@@ -469,7 +469,7 @@
"source": [
"For the quote-search functionality, you need first to make the input quote into a vector, and then use it to query the store (besides handling the optional metadata into the search call, that is).\n",
"\n",
- "Encapsulate the search-engine functionality into a function for ease of re-use. At its core is the `vector_find` method of the collection:"
+ "Encapsulate the search-engine functionality into a function for ease of reuse. At its core is the `vector_find` method of the collection:"
]
},
{
diff --git a/examples/vector_databases/cassandra_astradb/Philosophical_Quotes_CQL.ipynb b/examples/vector_databases/cassandra_astradb/Philosophical_Quotes_CQL.ipynb
index e6b6ea40..be00729c 100644
--- a/examples/vector_databases/cassandra_astradb/Philosophical_Quotes_CQL.ipynb
+++ b/examples/vector_databases/cassandra_astradb/Philosophical_Quotes_CQL.ipynb
@@ -683,7 +683,7 @@
"source": [
"For the quote-search functionality, you need first to make the input quote into a vector, and then use it to query the store (besides handling the optional metadata into the search call, that is).\n",
"\n",
- "Encapsulate the search-engine functionality into a function for ease of re-use:"
+ "Encapsulate the search-engine functionality into a function for ease of reuse:"
]
},
{
@@ -853,7 +853,7 @@
"\n",
"To get a feeling on how this works, try the following query and play with the choice of quote and threshold to compare the results:\n",
"\n",
- "_Note (for the mathematically inclined): this value is **a rescaling between zero and one** of the cosine difference between the vectors, i.e. of the scalar product divided by the product of the norms of the two vectors. In other words, this is 0 for opposite-facing vecors and +1 for parallel vectors. For other measures of similarity, check the [documentation](https://docs.datastax.com/en/astra-serverless/docs/vector-search/cql.html#_create_the_vector_schema_and_load_the_data_into_the_database) -- and keep in mind that the metric in the `SELECT` query should match the one used when creating the index earlier for meaningful, ordered results._"
+ "_Note (for the mathematically inclined): this value rescales cosine similarity from the range -1 to 1 into the range 0 to 1. Cosine similarity is the scalar product divided by the product of the vector norms. The rescaled value is 0 for opposite-facing vectors and 1 for parallel vectors. For other similarity measures, check the [documentation](https://docs.datastax.com/en/astra-serverless/docs/vector-search/cql.html#_create_the_vector_schema_and_load_the_data_into_the_database), and keep in mind that the metric in the `SELECT` query should match the one used when creating the index for meaningful, ordered results._"
]
},
{
diff --git a/examples/vector_databases/cassandra_astradb/Philosophical_Quotes_cassIO.ipynb b/examples/vector_databases/cassandra_astradb/Philosophical_Quotes_cassIO.ipynb
index 6e400cc3..31d90df3 100644
--- a/examples/vector_databases/cassandra_astradb/Philosophical_Quotes_cassIO.ipynb
+++ b/examples/vector_databases/cassandra_astradb/Philosophical_Quotes_cassIO.ipynb
@@ -135,7 +135,7 @@
"\n",
" Make sure you have both strings -- which are obtained in the [Astra UI](https://astra.datastax.com) once you sign in. For more information, see here: [database ID](https://awesome-astra.github.io/docs/pages/astra/faq/#where-should-i-find-a-database-identifier) and [Token](https://awesome-astra.github.io/docs/pages/astra/create-token/#c-procedure).\n",
"\n",
- "If you want to _connect to a Cassandra cluster_ (which however must [support](https://cassandra.apache.org/doc/trunk/cassandra/vector-search/overview.html) Vector Search), replace with `cassio.init(session=..., keyspace=...)` with suitable Session and keyspace name for your cluster."
+ "If you want to _connect to a Cassandra cluster_ (which however must [support](https://cassandra.apache.org/doc/trunk/cassandra/vector-search/overview.html) Vector Search), replace it with `cassio.init(session=..., keyspace=...)`, using a suitable session and keyspace name for your cluster."
]
},
{
@@ -481,7 +481,7 @@
"source": [
"For the quote-search functionality, you need first to make the input quote into a vector, and then use it to query the store (besides handling the optional metadata into the search call, that is).\n",
"\n",
- "Encapsulate the search-engine functionality into a function for ease of re-use:"
+ "Encapsulate the search-engine functionality into a function for ease of reuse:"
]
},
{
@@ -899,7 +899,7 @@
"\n",
"Compared to what you have seen earlier, there is a crucial difference in that now the quote's author is stored as the _partition id_ for the inserted row, instead of being added to the catch-all \"metadata\" dictionary.\n",
"\n",
- "While you are at it, by way of demonstration, you will insert all quotes by a given author _concurrently_: with CassIO, this is done by usng the asynchronous `put_async` method for each quote, collecting the resulting list of `Future` objects, and calling the `result()` method on them all afterwards, to ensure they all have executed. Cassandra / Astra DB well supports a high degree of concurrency in I/O operations.\n",
+ "While you are at it, by way of demonstration, you will insert all quotes by a given author _concurrently_: with CassIO, this is done by using the asynchronous `put_async` method for each quote, collecting the resulting list of `Future` objects, and calling the `result()` method on them all afterwards, to ensure they all have executed. Cassandra / Astra DB well supports a high degree of concurrency in I/O operations.\n",
"\n",
"_(Note: one could have cached the embeddings computed previously to save a few API tokens -- here, however, we wanted to keep the code easier to inspect.)_"
]
diff --git a/examples/vector_databases/elasticsearch/elasticsearch-retrieval-augmented-generation.ipynb b/examples/vector_databases/elasticsearch/elasticsearch-retrieval-augmented-generation.ipynb
index 802491ac..a55bcb41 100644
--- a/examples/vector_databases/elasticsearch/elasticsearch-retrieval-augmented-generation.ipynb
+++ b/examples/vector_databases/elasticsearch/elasticsearch-retrieval-augmented-generation.ipynb
@@ -13,7 +13,7 @@
"id": "e0f537af",
"metadata": {},
"source": [
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](openai/openai-cookbook/blob/main/examples/vector_databases/elasticsearch/elasticsearch-retrieval-augmented-generation.ipynb)\n"
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/openai/openai-cookbook/blob/main/examples/vector_databases/elasticsearch/elasticsearch-retrieval-augmented-generation.ipynb)\n"
]
},
{
diff --git a/examples/vector_databases/elasticsearch/elasticsearch-semantic-search.ipynb b/examples/vector_databases/elasticsearch/elasticsearch-semantic-search.ipynb
index b5efb2a1..ce260d53 100644
--- a/examples/vector_databases/elasticsearch/elasticsearch-semantic-search.ipynb
+++ b/examples/vector_databases/elasticsearch/elasticsearch-semantic-search.ipynb
@@ -13,7 +13,7 @@
"id": "e0f537af",
"metadata": {},
"source": [
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](openai/openai-cookbook/blob/main/examples/vector_databases/elasticsearch/elasticsearch-semantic-search.ipynb)\n"
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/openai/openai-cookbook/blob/main/examples/vector_databases/elasticsearch/elasticsearch-semantic-search.ipynb)\n"
]
},
{
@@ -779,7 +779,7 @@
"\n",
"Play around with different queries, and if you want to try with your own data, you can experiment with different embedding models.\n",
"\n",
- "ℹ️ Check out our other notebook [Retrieval augmented generation using Elasticsearch and OpenAI](openai/openai-cookbook/blob/main/examples/vector_databases/elasticsearch/elasticsearch-semantic-search.ipynb). That notebook builds on this example to demonstrate how to use Elasticsearch together with the OpenAI [chat completions](https://platform.openai.com/docs/api-reference/chat) API for retrieval augmented generation (RAG)."
+ "ℹ️ Check out our other notebook [Retrieval augmented generation using Elasticsearch and OpenAI](./elasticsearch-retrieval-augmented-generation.ipynb). That notebook builds on this example to demonstrate how to use Elasticsearch together with the OpenAI [chat completions](https://platform.openai.com/docs/api-reference/chat) API for retrieval augmented generation (RAG)."
]
}
],
diff --git a/examples/vector_databases/kusto/Getting_started_with_kusto_and_openai_embeddings.ipynb b/examples/vector_databases/kusto/Getting_started_with_kusto_and_openai_embeddings.ipynb
index e890e349..d6e1f6f9 100644
--- a/examples/vector_databases/kusto/Getting_started_with_kusto_and_openai_embeddings.ipynb
+++ b/examples/vector_databases/kusto/Getting_started_with_kusto_and_openai_embeddings.ipynb
@@ -1 +1 @@
-{"cells":[{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":[]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["# Kusto as a Vector database for AI embeddings"]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["This Notebook provides step by step instuctions on using Azure Data Explorer (Kusto) as a vector database with OpenAI embeddings. "]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["This notebook presents an end-to-end process of:\n","\n","1. Using precomputed embeddings created by OpenAI API.\n","2. Storing the embeddings in Kusto.\n","3. Converting raw text query to an embedding with OpenAI API.\n","4. Using Kusto to perform cosine similarity search in the stored embeddings\n"]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["### Prerequisites"]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["For the purposes of this exercise we need to prepare a couple of things:\n","\n","1. Azure Data Explorer(Kusto) server instance. https://azure.microsoft.com/en-us/products/data-explorer\n","3. Azure OpenAI credentials or OpenAI API key."]},{"cell_type":"code","execution_count":2,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:24:58.8253972Z","execution_start_time":"2023-05-10T09:24:58.8250545Z","livy_statement_state":"available","parent_msg_id":"affb2f05-b242-4152-99b2-f30e3f854c21","queued_time":"2023-05-10T09:24:43.3953963Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":-1},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, -1, Finished, Available)"]},"metadata":{},"output_type":"display_data"},{"data":{},"execution_count":2,"metadata":{},"output_type":"execute_result"},{"name":"stdout","output_type":"stream","text":["Collecting wget\n"," Downloading wget-3.2.zip (10 kB)\n"," Preparing metadata (setup.py) ... \u001b[?25ldone\n","\u001b[?25hBuilding wheels for collected packages: wget\n"," Building wheel for wget (setup.py) ... \u001b[?25l-\b \bdone\n","\u001b[?25h Created wheel for wget: filename=wget-3.2-py3-none-any.whl size=9657 sha256=10fd8aa1d20fd49c36389dc888acc721d0578c5a0635fc9fc5dc642c0f49522e\n"," Stored in directory: /home/trusted-service-user/.cache/pip/wheels/8b/f1/7f/5c94f0a7a505ca1c81cd1d9208ae2064675d97582078e6c769\n","Successfully built wget\n","Installing collected packages: wget\n","Successfully installed wget-3.2\n","\n","\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.0\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m23.1.2\u001b[0m\n","\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49m/nfs4/pyenv-27214bb4-edfd-4fdd-b888-8a99075a1416/bin/python -m pip install --upgrade pip\u001b[0m\n","Note: you may need to restart the kernel to use updated packages.\n"]},{"data":{},"execution_count":2,"metadata":{},"output_type":"execute_result"},{"name":"stdout","output_type":"stream","text":["Warning: PySpark kernel has been restarted to use updated packages.\n","\n"]}],"source":["%pip install wget"]},{"cell_type":"code","execution_count":3,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:25:13.0187836Z","execution_start_time":"2023-05-10T09:25:13.0184873Z","livy_statement_state":"available","parent_msg_id":"d4c4cf5b-21c4-4804-9db2-1f18a6be7733","queued_time":"2023-05-10T09:24:43.5454914Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":-1},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, -1, Finished, Available)"]},"metadata":{},"output_type":"display_data"},{"data":{},"execution_count":3,"metadata":{},"output_type":"execute_result"},{"name":"stdout","output_type":"stream","text":["Collecting openai\n"," Downloading openai-0.27.6-py3-none-any.whl (71 kB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m71.9/71.9 kB\u001b[0m \u001b[31m1.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m00:01\u001b[0m\n","\u001b[?25hRequirement already satisfied: tqdm in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from openai) (4.65.0)\n","Requirement already satisfied: requests>=2.20 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from openai) (2.28.2)\n","Requirement already satisfied: aiohttp in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from openai) (3.8.4)\n","Requirement already satisfied: urllib3<1.27,>=1.21.1 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from requests>=2.20->openai) (1.26.14)\n","Requirement already satisfied: certifi>=2017.4.17 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from requests>=2.20->openai) (2022.12.7)\n","Requirement already satisfied: idna<4,>=2.5 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from requests>=2.20->openai) (3.4)\n","Requirement already satisfied: charset-normalizer<4,>=2 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from requests>=2.20->openai) (2.1.1)\n","Requirement already satisfied: attrs>=17.3.0 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from aiohttp->openai) (22.2.0)\n","Requirement already satisfied: frozenlist>=1.1.1 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from aiohttp->openai) (1.3.3)\n","Requirement already satisfied: multidict<7.0,>=4.5 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from aiohttp->openai) (6.0.4)\n","Requirement already satisfied: yarl<2.0,>=1.0 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from aiohttp->openai) (1.8.2)\n","Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from aiohttp->openai) (4.0.2)\n","Requirement already satisfied: aiosignal>=1.1.2 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from aiohttp->openai) (1.3.1)\n","Installing collected packages: openai\n","Successfully installed openai-0.27.6\n","\n","\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.0\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m23.1.2\u001b[0m\n","\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49m/nfs4/pyenv-27214bb4-edfd-4fdd-b888-8a99075a1416/bin/python -m pip install --upgrade pip\u001b[0m\n","Note: you may need to restart the kernel to use updated packages.\n"]},{"data":{},"execution_count":3,"metadata":{},"output_type":"execute_result"},{"name":"stdout","output_type":"stream","text":["Warning: PySpark kernel has been restarted to use updated packages.\n","\n"]}],"source":["%pip install openai"]},{"cell_type":"code","execution_count":17,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:40:42.8774236Z","execution_start_time":"2023-05-10T09:40:42.8771662Z","livy_statement_state":"available","parent_msg_id":"7a7dfea4-d420-4b03-a2c6-82c65dfe177e","queued_time":"2023-05-10T09:40:30.9990512Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":-1},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, -1, Finished, Available)"]},"metadata":{},"output_type":"display_data"},{"data":{},"execution_count":17,"metadata":{},"output_type":"execute_result"},{"name":"stdout","output_type":"stream","text":["Requirement already satisfied: azure-kusto-data in /nfs4/pyenv-27214bb4-edfd-4fdd-b888-8a99075a1416/lib/python3.10/site-packages (4.1.4)\n","Requirement already satisfied: msal<2,>=1.9.0 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from azure-kusto-data) (1.21.0)\n","Requirement already satisfied: python-dateutil>=2.8.0 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from azure-kusto-data) (2.8.2)\n","Requirement already satisfied: azure-core<2,>=1.11.0 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from azure-kusto-data) (1.26.4)\n","Requirement already satisfied: requests>=2.13.0 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from azure-kusto-data) (2.28.2)\n","Requirement already satisfied: ijson~=3.1 in /nfs4/pyenv-27214bb4-edfd-4fdd-b888-8a99075a1416/lib/python3.10/site-packages (from azure-kusto-data) (3.2.0.post0)\n","Requirement already satisfied: azure-identity<2,>=1.5.0 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from azure-kusto-data) (1.12.0)\n","Requirement already satisfied: six>=1.11.0 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from azure-core<2,>=1.11.0->azure-kusto-data) (1.16.0)\n","Requirement already satisfied: typing-extensions>=4.3.0 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from azure-core<2,>=1.11.0->azure-kusto-data) (4.5.0)\n","Requirement already satisfied: cryptography>=2.5 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from azure-identity<2,>=1.5.0->azure-kusto-data) (40.0.1)\n","Requirement already satisfied: msal-extensions<2.0.0,>=0.3.0 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from azure-identity<2,>=1.5.0->azure-kusto-data) (1.0.0)\n","Requirement already satisfied: PyJWT[crypto]<3,>=1.0.0 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from msal<2,>=1.9.0->azure-kusto-data) (2.6.0)\n","Requirement already satisfied: urllib3<1.27,>=1.21.1 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from requests>=2.13.0->azure-kusto-data) (1.26.14)\n","Requirement already satisfied: charset-normalizer<4,>=2 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from requests>=2.13.0->azure-kusto-data) (2.1.1)\n","Requirement already satisfied: idna<4,>=2.5 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from requests>=2.13.0->azure-kusto-data) (3.4)\n","Requirement already satisfied: certifi>=2017.4.17 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from requests>=2.13.0->azure-kusto-data) (2022.12.7)\n","Requirement already satisfied: cffi>=1.12 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from cryptography>=2.5->azure-identity<2,>=1.5.0->azure-kusto-data) (1.15.1)\n","Requirement already satisfied: portalocker<3,>=1.0 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from msal-extensions<2.0.0,>=0.3.0->azure-identity<2,>=1.5.0->azure-kusto-data) (2.7.0)\n","Requirement already satisfied: pycparser in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from cffi>=1.12->cryptography>=2.5->azure-identity<2,>=1.5.0->azure-kusto-data) (2.21)\n","\n","\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.0\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m23.1.2\u001b[0m\n","\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49m/nfs4/pyenv-27214bb4-edfd-4fdd-b888-8a99075a1416/bin/python -m pip install --upgrade pip\u001b[0m\n","Note: you may need to restart the kernel to use updated packages.\n"]},{"data":{},"execution_count":17,"metadata":{},"output_type":"execute_result"},{"name":"stdout","output_type":"stream","text":["Warning: PySpark kernel has been restarted to use updated packages.\n","\n"]}],"source":["%pip install azure-kusto-data"]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["### Download precomputed Embeddings\n","\n"]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["In this section we are going to load prepared embedding data, so you don't have to recompute the embeddings of Wikipedia articles with your own credits.\n"]},{"cell_type":"code","execution_count":5,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:25:28.6496025Z","execution_start_time":"2023-05-10T09:25:23.4822208Z","livy_statement_state":"available","parent_msg_id":"2d10f66b-3875-426b-abdf-b88b2d64d7ec","queued_time":"2023-05-10T09:24:44.1318823Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":17},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 17, Finished, Available)"]},"metadata":{},"output_type":"display_data"},{"data":{"text/plain":["'vector_database_wikipedia_articles_embedded.zip'"]},"execution_count":7,"metadata":{},"output_type":"execute_result"}],"source":["import wget\n","\n","embeddings_url = \"https://cdn.openai.com/API/examples/data/vector_database_wikipedia_articles_embedded.zip\"\n","\n","# The file is ~700 MB so this will take some time\n","wget.download(embeddings_url)"]},{"cell_type":"code","execution_count":6,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:25:50.6601867Z","execution_start_time":"2023-05-10T09:25:28.9912827Z","livy_statement_state":"available","parent_msg_id":"093e0086-0bc4-4fb8-b656-3484f31b675e","queued_time":"2023-05-10T09:24:44.6002568Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":18},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 18, Finished, Available)"]},"metadata":{},"output_type":"display_data"}],"source":["\n","import zipfile\n","\n","with zipfile.ZipFile(\"vector_database_wikipedia_articles_embedded.zip\",\"r\") as zip_ref:\n"," zip_ref.extractall(\"/lakehouse/default/Files/data\")"]},{"cell_type":"code","execution_count":7,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:31:38.5924721Z","execution_start_time":"2023-05-10T09:25:50.9770732Z","livy_statement_state":"available","parent_msg_id":"fab21836-4966-4068-8725-8fac982ca969","queued_time":"2023-05-10T09:24:44.8734372Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":19},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 19, Finished, Available)"]},"metadata":{},"output_type":"display_data"},{"data":{"text/html":["<div>\n","<style scoped>\n"," .dataframe tbody tr th:only-of-type {\n"," vertical-align: middle;\n"," }\n","\n"," .dataframe tbody tr th {\n"," vertical-align: top;\n"," }\n","\n"," .dataframe thead th {\n"," text-align: right;\n"," }\n","</style>\n","<table border=\"1\" class=\"dataframe\">\n"," <thead>\n"," <tr style=\"text-align: right;\">\n"," <th></th>\n"," <th>id</th>\n"," <th>url</th>\n"," <th>title</th>\n"," <th>text</th>\n"," <th>title_vector</th>\n"," <th>content_vector</th>\n"," <th>vector_id</th>\n"," </tr>\n"," </thead>\n"," <tbody>\n"," <tr>\n"," <th>0</th>\n"," <td>1</td>\n"," <td>https://simple.wikipedia.org/wiki/April</td>\n"," <td>April</td>\n"," <td>April is the fourth month of the year in the J...</td>\n"," <td>[0.001009464613161981, -0.020700545981526375, ...</td>\n"," <td>[-0.011253940872848034, -0.013491976074874401,...</td>\n"," <td>0</td>\n"," </tr>\n"," <tr>\n"," <th>1</th>\n"," <td>2</td>\n"," <td>https://simple.wikipedia.org/wiki/August</td>\n"," <td>August</td>\n"," <td>August (Aug.) is the eighth month of the year ...</td>\n"," <td>[0.0009286514250561595, 0.000820168002974242, ...</td>\n"," <td>[0.0003609954728744924, 0.007262262050062418, ...</td>\n"," <td>1</td>\n"," </tr>\n"," <tr>\n"," <th>2</th>\n"," <td>6</td>\n"," <td>https://simple.wikipedia.org/wiki/Art</td>\n"," <td>Art</td>\n"," <td>Art is a creative activity that expresses imag...</td>\n"," <td>[0.003393713850528002, 0.0061537534929811954, ...</td>\n"," <td>[-0.004959689453244209, 0.015772193670272827, ...</td>\n"," <td>2</td>\n"," </tr>\n"," <tr>\n"," <th>3</th>\n"," <td>8</td>\n"," <td>https://simple.wikipedia.org/wiki/A</td>\n"," <td>A</td>\n"," <td>A or a is the first letter of the English alph...</td>\n"," <td>[0.0153952119871974, -0.013759135268628597, 0....</td>\n"," <td>[0.024894846603274345, -0.022186409682035446, ...</td>\n"," <td>3</td>\n"," </tr>\n"," <tr>\n"," <th>4</th>\n"," <td>9</td>\n"," <td>https://simple.wikipedia.org/wiki/Air</td>\n"," <td>Air</td>\n"," <td>Air refers to the Earth's atmosphere. Air is a...</td>\n"," <td>[0.02224554680287838, -0.02044147066771984, -0...</td>\n"," <td>[0.021524671465158463, 0.018522677943110466, -...</td>\n"," <td>4</td>\n"," </tr>\n"," </tbody>\n","</table>\n","</div>"],"text/plain":[" id url title \\\n","0 1 https://simple.wikipedia.org/wiki/April April \n","1 2 https://simple.wikipedia.org/wiki/August August \n","2 6 https://simple.wikipedia.org/wiki/Art Art \n","3 8 https://simple.wikipedia.org/wiki/A A \n","4 9 https://simple.wikipedia.org/wiki/Air Air \n","\n"," text \\\n","0 April is the fourth month of the year in the J... \n","1 August (Aug.) is the eighth month of the year ... \n","2 Art is a creative activity that expresses imag... \n","3 A or a is the first letter of the English alph... \n","4 Air refers to the Earth's atmosphere. Air is a... \n","\n"," title_vector \\\n","0 [0.001009464613161981, -0.020700545981526375, ... \n","1 [0.0009286514250561595, 0.000820168002974242, ... \n","2 [0.003393713850528002, 0.0061537534929811954, ... \n","3 [0.0153952119871974, -0.013759135268628597, 0.... \n","4 [0.02224554680287838, -0.02044147066771984, -0... \n","\n"," content_vector vector_id \n","0 [-0.011253940872848034, -0.013491976074874401,... 0 \n","1 [0.0003609954728744924, 0.007262262050062418, ... 1 \n","2 [-0.004959689453244209, 0.015772193670272827, ... 2 \n","3 [0.024894846603274345, -0.022186409682035446, ... 3 \n","4 [0.021524671465158463, 0.018522677943110466, -... 4 "]},"execution_count":11,"metadata":{},"output_type":"execute_result"}],"source":["import pandas as pd\n","\n","from ast import literal_eval\n","\n","article_df = pd.read_csv('/lakehouse/default/Files/data/vector_database_wikipedia_articles_embedded.csv')\n","# Read vectors from strings back into a list\n","article_df[\"title_vector\"] = article_df.title_vector.apply(literal_eval)\n","article_df[\"content_vector\"] = article_df.content_vector.apply(literal_eval)\n","article_df.head()\n"]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["### Store vectors in a Kusto table\n"]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["Create a table & load the vectors in Kusto based on the contents in the dataframe. The spark option CreakeIfNotExists will automatically create a table if it doesn't exist\n"]},{"cell_type":"code","execution_count":20,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:41:07.7982707Z","execution_start_time":"2023-05-10T09:41:07.4379451Z","livy_statement_state":"available","parent_msg_id":"0a5fca1c-3aae-4b95-86c8-e098d0369f95","queued_time":"2023-05-10T09:41:07.1656842Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":37},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 37, Finished, Available)"]},"metadata":{},"output_type":"display_data"}],"source":["# replace with your AAD Tenant ID, Kusto Cluster URI, Kusto DB name and Kusto Table\n","AAD_TENANT_ID = \"\"\n","KUSTO_CLUSTER = \"\"\n","KUSTO_DATABASE = \"Vector\"\n","KUSTO_TABLE = \"Wiki\""]},{"cell_type":"code","execution_count":9,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:31:43.2629717Z","execution_start_time":"2023-05-10T09:31:39.5426716Z","livy_statement_state":"available","parent_msg_id":"ece408d2-5f62-4a31-acfb-530070444031","queued_time":"2023-05-10T09:24:45.2865763Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":21},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 21, Finished, Available)"]},"metadata":{},"output_type":"display_data"}],"source":["\n","kustoOptions = {\"kustoCluster\": KUSTO_CLUSTER, \"kustoDatabase\" :KUSTO_DATABASE, \"kustoTable\" : KUSTO_TABLE }\n","\n","# Replace the auth method based on your desired authentication mechanism - https://github.com/Azure/azure-kusto-spark/blob/master/docs/Authentication.md\n","access_token=mssparkutils.credentials.getToken(kustoOptions[\"kustoCluster\"])"]},{"cell_type":"code","execution_count":10,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:31:48.9063385Z","execution_start_time":"2023-05-10T09:31:43.5930348Z","livy_statement_state":"available","parent_msg_id":"421b9d33-f3ce-4f20-a8d4-5d0958f240c9","queued_time":"2023-05-10T09:24:45.5199822Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":22},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 22, Finished, Available)"]},"metadata":{},"output_type":"display_data"},{"name":"stderr","output_type":"stream","text":["/opt/spark/python/lib/pyspark.zip/pyspark/sql/pandas/conversion.py:604: FutureWarning: iteritems is deprecated and will be removed in a future version. Use .items instead.\n"]}],"source":["#Pandas data frame to spark dataframe\n","sparkDF=spark.createDataFrame(article_df)"]},{"cell_type":"code","execution_count":11,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:34:35.1205454Z","execution_start_time":"2023-05-10T09:31:49.2428848Z","livy_statement_state":"available","parent_msg_id":"7e182f67-e09f-4aa4-9fca-d67b13f01f19","queued_time":"2023-05-10T09:24:45.7895854Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[{"completionTime":"2023-05-10T09:32:55.544GMT","dataRead":0,"dataWritten":0,"description":"Job group for statement 23:\n# Write data to a Kusto table\nsparkDF.write. format(\"com.microsoft.kusto.spark.synapse.datasource\"). option(\"kustoCluster\",kustoOptions[\"kustoCluster\"]). option(\"kustoDatabase\",kustoOptions[\"kustoDatabase\"]). option(\"kustoTable\", kustoOptions[\"kustoTable\"]). option(\"accessToken\", access_token). option(\"tableCreateOptions\", \"CreateIfNotExist\").mode(\"Append\"). save()\n","jobGroup":"23","jobId":7,"killedTasksSummary":{},"name":"foreachPartition at KustoWriter.scala:116","numActiveStages":0,"numActiveTasks":0,"numCompletedIndices":8,"numCompletedStages":1,"numCompletedTasks":8,"numFailedStages":0,"numFailedTasks":0,"numKilledTasks":0,"numSkippedStages":0,"numSkippedTasks":0,"numTasks":8,"rowCount":0,"stageIds":[10],"status":"SUCCEEDED","submissionTime":"2023-05-10T09:32:00.547GMT"}],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":1,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":23},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 23, Finished, Available)"]},"metadata":{},"output_type":"display_data"}],"source":["# Write data to a Kusto table\n","sparkDF.write. \\\n","format(\"com.microsoft.kusto.spark.synapse.datasource\"). \\\n","option(\"kustoCluster\",kustoOptions[\"kustoCluster\"]). \\\n","option(\"kustoDatabase\",kustoOptions[\"kustoDatabase\"]). \\\n","option(\"kustoTable\", kustoOptions[\"kustoTable\"]). \\\n","option(\"accessToken\", access_token). \\\n","option(\"tableCreateOptions\", \"CreateIfNotExist\").\\\n","mode(\"Append\"). \\\n","save()\n"]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["### Prepare your OpenAI API key\n","# "]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["The OpenAI API key is used for vectorization of the documents and queries. You can follow the instructions to create and retrieve your Azure OpenAI key and endpoint. https://learn.microsoft.com/en-us/azure/cognitive-services/openai/tutorials/embeddings\n","\n","\n","Please make sure to use the `text-embedding-3-small` model. Since the precomputed embeddings were created with `text-embedding-3-small` model we also have to use it during search.\n"]},{"cell_type":"code","execution_count":26,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:41:51.4743874Z","execution_start_time":"2023-05-10T09:41:51.1273995Z","livy_statement_state":"available","parent_msg_id":"53239dc7-36b8-4cbc-a4db-ce263729cd4f","queued_time":"2023-05-10T09:41:50.8249073Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":43},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 43, Finished, Available)"]},"metadata":{},"output_type":"display_data"}],"source":["import openai"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["#### If using Azure Open AI"]},{"cell_type":"code","execution_count":27,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:41:53.0029722Z","execution_start_time":"2023-05-10T09:41:52.6610261Z","livy_statement_state":"available","parent_msg_id":"9546736c-bebc-411d-a50a-6cf69eb5e70d","queued_time":"2023-05-10T09:41:52.3687239Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":44},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 44, Finished, Available)"]},"metadata":{},"output_type":"display_data"}],"source":["openai.api_version = '2022-12-01'\n","openai.api_base = '' # Please add your endpoint here\n","openai.api_type = 'azure'\n","openai.api_key = '' # Please add your api key here\n","\n","def embed(query):\n"," # Creates embedding vector from user query\n"," embedded_query = openai.Embedding.create(\n"," input=query,\n"," deployment_id=\"embed\", #replace with your deployment id\n"," chunk_size=1\n"," )[\"data\"][0][\"embedding\"]\n"," return embedded_query"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["#### If using Open AI"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["Only run this cell if you plan to use Open AI for embedding"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["openai.api_key = \"\"\n","\n","\n","def embed(query):\n"," # Creates embedding vector from user query\n"," embedded_query = openai.Embedding.create(\n"," input=query,\n"," model=\"text-embedding-3-small\",\n"," )[\"data\"][0][\"embedding\"]\n"," return embedded_query"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["### Generate embedding for the search term"]},{"cell_type":"code","execution_count":28,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:41:56.2227563Z","execution_start_time":"2023-05-10T09:41:55.1887813Z","livy_statement_state":"available","parent_msg_id":"1001b7dc-2b09-421e-aca4-e7a2b17c7d0e","queued_time":"2023-05-10T09:41:54.8728344Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":45},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 45, Finished, Available)"]},"metadata":{},"output_type":"display_data"}],"source":["\n","searchedEmbedding = embed(\"places where you worship\")\n","#print(searchedEmbedding)"]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["#### Semantic search in Kusto "]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["We will search the Kusto table for the closest vectors.\n","\n","We will be using the series-cosine-similarity-fl UDF for similarity search. \n","\n","Please create the function in your database before proceeding -\n","https://learn.microsoft.com/en-us/azure/data-explorer/kusto/functions-library/series-cosine-similarity-fl?tabs=query-defined"]},{"cell_type":"code","execution_count":18,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:40:52.3506224Z","execution_start_time":"2023-05-10T09:40:51.397278Z","livy_statement_state":"available","parent_msg_id":"5c692f91-d611-4f22-a2f3-e008bb8d89d8","queued_time":"2023-05-10T09:40:46.211323Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":35},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 35, Finished, Available)"]},"metadata":{},"output_type":"display_data"}],"source":["from azure.kusto.data import KustoClient, KustoConnectionStringBuilder\n","from azure.kusto.data.exceptions import KustoServiceError\n","from azure.kusto.data.helpers import dataframe_from_result_table\n","import pandas as pd"]},{"cell_type":"code","execution_count":21,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:41:14.0650747Z","execution_start_time":"2023-05-10T09:41:13.6897398Z","livy_statement_state":"available","parent_msg_id":"2e004b80-df5e-4873-8dc4-dc9b0fcdfd1b","queued_time":"2023-05-10T09:41:13.4128259Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":38},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 38, Finished, Available)"]},"metadata":{},"output_type":"display_data"}],"source":["KCSB = KustoConnectionStringBuilder.with_aad_device_authentication(\n"," KUSTO_CLUSTER)\n","KCSB.authority_id = AAD_TENANT_ID"]},{"cell_type":"code","execution_count":22,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:41:17.1788945Z","execution_start_time":"2023-05-10T09:41:16.7709048Z","livy_statement_state":"available","parent_msg_id":"7b74117d-03a9-4963-9fbf-83dcf5eb33a8","queued_time":"2023-05-10T09:41:16.4790182Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":39},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 39, Finished, Available)"]},"metadata":{},"output_type":"display_data"}],"source":["KUSTO_CLIENT = KustoClient(KCSB)"]},{"cell_type":"code","execution_count":31,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:45:56.5295656Z","execution_start_time":"2023-05-10T09:45:54.8312637Z","livy_statement_state":"available","parent_msg_id":"848897fc-69b2-4108-8cb7-844d8dd473d7","queued_time":"2023-05-10T09:45:54.458869Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":48},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 48, Finished, Available)"]},"metadata":{},"output_type":"display_data"}],"source":["KUSTO_QUERY = \"Wiki | extend similarity = series_cosine_similarity_fl(dynamic(\"+str(searchedEmbedding)+\"), content_vector,1,1) | top 10 by similarity desc \"\n","\n","RESPONSE = KUSTO_CLIENT.execute(KUSTO_DATABASE, KUSTO_QUERY)"]},{"cell_type":"code","execution_count":32,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:46:02.8573664Z","execution_start_time":"2023-05-10T09:46:02.496154Z","livy_statement_state":"available","parent_msg_id":"36d4dd76-ca76-4ce0-aa35-5cd8d7c26b6f","queued_time":"2023-05-10T09:46:02.2249009Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":49},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 49, Finished, Available)"]},"metadata":{},"output_type":"display_data"},{"data":{"text/html":["<div>\n","<style scoped>\n"," .dataframe tbody tr th:only-of-type {\n"," vertical-align: middle;\n"," }\n","\n"," .dataframe tbody tr th {\n"," vertical-align: top;\n"," }\n","\n"," .dataframe thead th {\n"," text-align: right;\n"," }\n","</style>\n","<table border=\"1\" class=\"dataframe\">\n"," <thead>\n"," <tr style=\"text-align: right;\">\n"," <th></th>\n"," <th>id</th>\n"," <th>url</th>\n"," <th>title</th>\n"," <th>text</th>\n"," <th>title_vector</th>\n"," <th>content_vector</th>\n"," <th>vector_id</th>\n"," <th>similarity</th>\n"," </tr>\n"," </thead>\n"," <tbody>\n"," <tr>\n"," <th>0</th>\n"," <td>852</td>\n"," <td>https://simple.wikipedia.org/wiki/Temple</td>\n"," <td>Temple</td>\n"," <td>A temple is a building where people go to prac...</td>\n"," <td>[-0.021837441250681877, -0.007722342386841774,...</td>\n"," <td>[-0.0019541378132998943, 0.007151313126087189,...</td>\n"," <td>413</td>\n"," <td>0.834495</td>\n"," </tr>\n"," <tr>\n"," <th>1</th>\n"," <td>78094</td>\n"," <td>https://simple.wikipedia.org/wiki/Christian%20...</td>\n"," <td>Christian worship</td>\n"," <td>In Christianity, worship has been thought as b...</td>\n"," <td>[0.0017675267299637198, -0.008890199474990368,...</td>\n"," <td>[0.020530683919787407, 0.0024345638230443, -0....</td>\n"," <td>20320</td>\n"," <td>0.832132</td>\n"," </tr>\n"," <tr>\n"," <th>2</th>\n"," <td>59154</td>\n"," <td>https://simple.wikipedia.org/wiki/Service%20of...</td>\n"," <td>Service of worship</td>\n"," <td>A service of worship is a religious meeting wh...</td>\n"," <td>[-0.007969820871949196, 0.0004240311391185969,...</td>\n"," <td>[0.003784010885283351, -0.0030924836173653603,...</td>\n"," <td>15519</td>\n"," <td>0.831633</td>\n"," </tr>\n"," <tr>\n"," <th>3</th>\n"," <td>51910</td>\n"," <td>https://simple.wikipedia.org/wiki/Worship</td>\n"," <td>Worship</td>\n"," <td>Worship is a word often used in religion. It ...</td>\n"," <td>[0.0036036288365721703, -0.01276545226573944, ...</td>\n"," <td>[0.007925753481686115, -0.0110504487529397, 0....</td>\n"," <td>14010</td>\n"," <td>0.828185</td>\n"," </tr>\n"," <tr>\n"," <th>4</th>\n"," <td>29576</td>\n"," <td>https://simple.wikipedia.org/wiki/Altar</td>\n"," <td>Altar</td>\n"," <td>An altar is a place, often a table, where a re...</td>\n"," <td>[0.007887467741966248, -0.02706138789653778, -...</td>\n"," <td>[0.023901859298348427, -0.031175222247838977, ...</td>\n"," <td>8708</td>\n"," <td>0.824124</td>\n"," </tr>\n"," <tr>\n"," <th>5</th>\n"," <td>92507</td>\n"," <td>https://simple.wikipedia.org/wiki/Shrine</td>\n"," <td>Shrine</td>\n"," <td>A shrine is a holy or sacred place with someth...</td>\n"," <td>[-0.011601685546338558, 0.006366696208715439, ...</td>\n"," <td>[0.016423320397734642, -0.0015560361789539456,...</td>\n"," <td>23945</td>\n"," <td>0.823863</td>\n"," </tr>\n"," <tr>\n"," <th>6</th>\n"," <td>815</td>\n"," <td>https://simple.wikipedia.org/wiki/Synagogue</td>\n"," <td>Synagogue</td>\n"," <td>A synagogue is a place where Jews meet to wors...</td>\n"," <td>[-0.017317570745944977, 0.0022673190105706453,...</td>\n"," <td>[-0.004515442531555891, 0.003739549545571208, ...</td>\n"," <td>398</td>\n"," <td>0.819942</td>\n"," </tr>\n"," <tr>\n"," <th>7</th>\n"," <td>68080</td>\n"," <td>https://simple.wikipedia.org/wiki/Shinto%20shrine</td>\n"," <td>Shinto shrine</td>\n"," <td>A Shinto shrine is a sacred place or site wher...</td>\n"," <td>[0.0035740730818361044, 0.0028098472394049168,...</td>\n"," <td>[0.011014971882104874, 0.00042272370774298906,...</td>\n"," <td>18106</td>\n"," <td>0.818475</td>\n"," </tr>\n"," <tr>\n"," <th>8</th>\n"," <td>57790</td>\n"," <td>https://simple.wikipedia.org/wiki/Chapel</td>\n"," <td>Chapel</td>\n"," <td>A chapel is a place for Christian worship. The...</td>\n"," <td>[-0.01371884811669588, 0.0031672674231231213, ...</td>\n"," <td>[0.002526090247556567, 0.02482965588569641, 0....</td>\n"," <td>15260</td>\n"," <td>0.817608</td>\n"," </tr>\n"," <tr>\n"," <th>9</th>\n"," <td>142</td>\n"," <td>https://simple.wikipedia.org/wiki/Church%20%28...</td>\n"," <td>Church (building)</td>\n"," <td>A church is a building that was constructed to...</td>\n"," <td>[0.0021336888894438744, 0.0029748091474175453,...</td>\n"," <td>[0.016109377145767212, 0.022908871993422508, 0...</td>\n"," <td>74</td>\n"," <td>0.812636</td>\n"," </tr>\n"," </tbody>\n","</table>\n","</div>"],"text/plain":[" id url \\\n","0 852 https://simple.wikipedia.org/wiki/Temple \n","1 78094 https://simple.wikipedia.org/wiki/Christian%20... \n","2 59154 https://simple.wikipedia.org/wiki/Service%20of... \n","3 51910 https://simple.wikipedia.org/wiki/Worship \n","4 29576 https://simple.wikipedia.org/wiki/Altar \n","5 92507 https://simple.wikipedia.org/wiki/Shrine \n","6 815 https://simple.wikipedia.org/wiki/Synagogue \n","7 68080 https://simple.wikipedia.org/wiki/Shinto%20shrine \n","8 57790 https://simple.wikipedia.org/wiki/Chapel \n","9 142 https://simple.wikipedia.org/wiki/Church%20%28... \n","\n"," title text \\\n","0 Temple A temple is a building where people go to prac... \n","1 Christian worship In Christianity, worship has been thought as b... \n","2 Service of worship A service of worship is a religious meeting wh... \n","3 Worship Worship is a word often used in religion. It ... \n","4 Altar An altar is a place, often a table, where a re... \n","5 Shrine A shrine is a holy or sacred place with someth... \n","6 Synagogue A synagogue is a place where Jews meet to wors... \n","7 Shinto shrine A Shinto shrine is a sacred place or site wher... \n","8 Chapel A chapel is a place for Christian worship. The... \n","9 Church (building) A church is a building that was constructed to... \n","\n"," title_vector \\\n","0 [-0.021837441250681877, -0.007722342386841774,... \n","1 [0.0017675267299637198, -0.008890199474990368,... \n","2 [-0.007969820871949196, 0.0004240311391185969,... \n","3 [0.0036036288365721703, -0.01276545226573944, ... \n","4 [0.007887467741966248, -0.02706138789653778, -... \n","5 [-0.011601685546338558, 0.006366696208715439, ... \n","6 [-0.017317570745944977, 0.0022673190105706453,... \n","7 [0.0035740730818361044, 0.0028098472394049168,... \n","8 [-0.01371884811669588, 0.0031672674231231213, ... \n","9 [0.0021336888894438744, 0.0029748091474175453,... \n","\n"," content_vector vector_id similarity \n","0 [-0.0019541378132998943, 0.007151313126087189,... 413 0.834495 \n","1 [0.020530683919787407, 0.0024345638230443, -0.... 20320 0.832132 \n","2 [0.003784010885283351, -0.0030924836173653603,... 15519 0.831633 \n","3 [0.007925753481686115, -0.0110504487529397, 0.... 14010 0.828185 \n","4 [0.023901859298348427, -0.031175222247838977, ... 8708 0.824124 \n","5 [0.016423320397734642, -0.0015560361789539456,... 23945 0.823863 \n","6 [-0.004515442531555891, 0.003739549545571208, ... 398 0.819942 \n","7 [0.011014971882104874, 0.00042272370774298906,... 18106 0.818475 \n","8 [0.002526090247556567, 0.02482965588569641, 0.... 15260 0.817608 \n","9 [0.016109377145767212, 0.022908871993422508, 0... 74 0.812636 "]},"execution_count":33,"metadata":{},"output_type":"execute_result"}],"source":["df = dataframe_from_result_table(RESPONSE.primary_results[0])\n","df"]},{"cell_type":"code","execution_count":null,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[],"source":["searchedEmbedding = embed(\"unfortunate events in history\")\n"]},{"cell_type":"code","execution_count":35,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:48:43.6147167Z","execution_start_time":"2023-05-10T09:48:41.8371731Z","livy_statement_state":"available","parent_msg_id":"3dd276f3-a68e-44f7-8205-253d772aea18","queued_time":"2023-05-10T09:48:41.4581244Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":52},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 52, Finished, Available)"]},"metadata":{},"output_type":"display_data"},{"data":{"text/html":["<div>\n","<style scoped>\n"," .dataframe tbody tr th:only-of-type {\n"," vertical-align: middle;\n"," }\n","\n"," .dataframe tbody tr th {\n"," vertical-align: top;\n"," }\n","\n"," .dataframe thead th {\n"," text-align: right;\n"," }\n","</style>\n","<table border=\"1\" class=\"dataframe\">\n"," <thead>\n"," <tr style=\"text-align: right;\">\n"," <th></th>\n"," <th>id</th>\n"," <th>url</th>\n"," <th>title</th>\n"," <th>text</th>\n"," <th>title_vector</th>\n"," <th>content_vector</th>\n"," <th>vector_id</th>\n"," <th>similarity</th>\n"," </tr>\n"," </thead>\n"," <tbody>\n"," <tr>\n"," <th>0</th>\n"," <td>848</td>\n"," <td>https://simple.wikipedia.org/wiki/Tragedy</td>\n"," <td>Tragedy</td>\n"," <td>In theatre, a tragedy as defined by Aristotle ...</td>\n"," <td>[-0.019502468407154083, -0.010160734876990318,...</td>\n"," <td>[-0.012951433658599854, -0.018836138769984245,...</td>\n"," <td>410</td>\n"," <td>0.851848</td>\n"," </tr>\n"," <tr>\n"," <th>1</th>\n"," <td>4469</td>\n"," <td>https://simple.wikipedia.org/wiki/The%20Holocaust</td>\n"," <td>The Holocaust</td>\n"," <td>The Holocaust, sometimes called The Shoah (), ...</td>\n"," <td>[-0.030233195051550865, -0.024401605129241943,...</td>\n"," <td>[-0.016398731619119644, -0.013267949223518372,...</td>\n"," <td>1203</td>\n"," <td>0.847222</td>\n"," </tr>\n"," <tr>\n"," <th>2</th>\n"," <td>64216</td>\n"," <td>https://simple.wikipedia.org/wiki/List%20of%20...</td>\n"," <td>List of historical plagues</td>\n"," <td>This list contains famous or well documented o...</td>\n"," <td>[-0.010667890310287476, -0.0003575817099772393...</td>\n"," <td>[-0.010863155126571655, -0.0012196656316518784...</td>\n"," <td>16859</td>\n"," <td>0.844411</td>\n"," </tr>\n"," <tr>\n"," <th>3</th>\n"," <td>4397</td>\n"," <td>https://simple.wikipedia.org/wiki/List%20of%20...</td>\n"," <td>List of disasters</td>\n"," <td>This is a list of disasters, both natural and ...</td>\n"," <td>[-0.02713736332952976, -0.005278210621327162, ...</td>\n"," <td>[-0.023679986596107483, -0.006126823835074902,...</td>\n"," <td>1158</td>\n"," <td>0.843063</td>\n"," </tr>\n"," <tr>\n"," <th>4</th>\n"," <td>23073</td>\n"," <td>https://simple.wikipedia.org/wiki/Disaster</td>\n"," <td>Disaster</td>\n"," <td>A disaster is something very not good that hap...</td>\n"," <td>[-0.018235962837934497, -0.020034968852996823,...</td>\n"," <td>[-0.02504003793001175, 0.007415903266519308, 0...</td>\n"," <td>7251</td>\n"," <td>0.840334</td>\n"," </tr>\n"," <tr>\n"," <th>5</th>\n"," <td>4382</td>\n"," <td>https://simple.wikipedia.org/wiki/List%20of%20...</td>\n"," <td>List of terrorist incidents</td>\n"," <td>The following is a list by date of acts and fa...</td>\n"," <td>[-0.03989032283425331, -0.012808636762201786, ...</td>\n"," <td>[-0.045838188380002975, -0.01682935282588005, ...</td>\n"," <td>1149</td>\n"," <td>0.836162</td>\n"," </tr>\n"," <tr>\n"," <th>6</th>\n"," <td>13528</td>\n"," <td>https://simple.wikipedia.org/wiki/A%20Series%2...</td>\n"," <td>A Series of Unfortunate Events</td>\n"," <td>A Series of Unfortunate Events is a series of ...</td>\n"," <td>[0.0010618815431371331, -0.0267023965716362, -...</td>\n"," <td>[0.002801976166665554, -0.02904471382498741, -...</td>\n"," <td>4347</td>\n"," <td>0.835172</td>\n"," </tr>\n"," <tr>\n"," <th>7</th>\n"," <td>42874</td>\n"," <td>https://simple.wikipedia.org/wiki/History%20of...</td>\n"," <td>History of the world</td>\n"," <td>The history of the world (also called human hi...</td>\n"," <td>[0.0026915925554931164, -0.022206028923392296,...</td>\n"," <td>[0.013645033352077007, -0.005165994167327881, ...</td>\n"," <td>11672</td>\n"," <td>0.830243</td>\n"," </tr>\n"," <tr>\n"," <th>8</th>\n"," <td>4452</td>\n"," <td>https://simple.wikipedia.org/wiki/Accident</td>\n"," <td>Accident</td>\n"," <td>An accident is when something goes wrong when ...</td>\n"," <td>[-0.004075294826179743, -0.0059883203357458115...</td>\n"," <td>[0.00926120299845934, 0.013705797493457794, 0....</td>\n"," <td>1190</td>\n"," <td>0.826898</td>\n"," </tr>\n"," <tr>\n"," <th>9</th>\n"," <td>324</td>\n"," <td>https://simple.wikipedia.org/wiki/History</td>\n"," <td>History</td>\n"," <td>History is the study of past events. People kn...</td>\n"," <td>[0.006603690329939127, -0.011856242083013058, ...</td>\n"," <td>[0.0048830462619662285, 0.0032003086525946856,...</td>\n"," <td>170</td>\n"," <td>0.824645</td>\n"," </tr>\n"," </tbody>\n","</table>\n","</div>"],"text/plain":[" id url \\\n","0 848 https://simple.wikipedia.org/wiki/Tragedy \n","1 4469 https://simple.wikipedia.org/wiki/The%20Holocaust \n","2 64216 https://simple.wikipedia.org/wiki/List%20of%20... \n","3 4397 https://simple.wikipedia.org/wiki/List%20of%20... \n","4 23073 https://simple.wikipedia.org/wiki/Disaster \n","5 4382 https://simple.wikipedia.org/wiki/List%20of%20... \n","6 13528 https://simple.wikipedia.org/wiki/A%20Series%2... \n","7 42874 https://simple.wikipedia.org/wiki/History%20of... \n","8 4452 https://simple.wikipedia.org/wiki/Accident \n","9 324 https://simple.wikipedia.org/wiki/History \n","\n"," title \\\n","0 Tragedy \n","1 The Holocaust \n","2 List of historical plagues \n","3 List of disasters \n","4 Disaster \n","5 List of terrorist incidents \n","6 A Series of Unfortunate Events \n","7 History of the world \n","8 Accident \n","9 History \n","\n"," text \\\n","0 In theatre, a tragedy as defined by Aristotle ... \n","1 The Holocaust, sometimes called The Shoah (), ... \n","2 This list contains famous or well documented o... \n","3 This is a list of disasters, both natural and ... \n","4 A disaster is something very not good that hap... \n","5 The following is a list by date of acts and fa... \n","6 A Series of Unfortunate Events is a series of ... \n","7 The history of the world (also called human hi... \n","8 An accident is when something goes wrong when ... \n","9 History is the study of past events. People kn... \n","\n"," title_vector \\\n","0 [-0.019502468407154083, -0.010160734876990318,... \n","1 [-0.030233195051550865, -0.024401605129241943,... \n","2 [-0.010667890310287476, -0.0003575817099772393... \n","3 [-0.02713736332952976, -0.005278210621327162, ... \n","4 [-0.018235962837934497, -0.020034968852996823,... \n","5 [-0.03989032283425331, -0.012808636762201786, ... \n","6 [0.0010618815431371331, -0.0267023965716362, -... \n","7 [0.0026915925554931164, -0.022206028923392296,... \n","8 [-0.004075294826179743, -0.0059883203357458115... \n","9 [0.006603690329939127, -0.011856242083013058, ... \n","\n"," content_vector vector_id similarity \n","0 [-0.012951433658599854, -0.018836138769984245,... 410 0.851848 \n","1 [-0.016398731619119644, -0.013267949223518372,... 1203 0.847222 \n","2 [-0.010863155126571655, -0.0012196656316518784... 16859 0.844411 \n","3 [-0.023679986596107483, -0.006126823835074902,... 1158 0.843063 \n","4 [-0.02504003793001175, 0.007415903266519308, 0... 7251 0.840334 \n","5 [-0.045838188380002975, -0.01682935282588005, ... 1149 0.836162 \n","6 [0.002801976166665554, -0.02904471382498741, -... 4347 0.835172 \n","7 [0.013645033352077007, -0.005165994167327881, ... 11672 0.830243 \n","8 [0.00926120299845934, 0.013705797493457794, 0.... 1190 0.826898 \n","9 [0.0048830462619662285, 0.0032003086525946856,... 170 0.824645 "]},"execution_count":39,"metadata":{},"output_type":"execute_result"}],"source":["KUSTO_QUERY = \"Wiki | extend similarity = series_cosine_similarity_fl(dynamic(\"+str(searchedEmbedding)+\"), title_vector,1,1) | top 10 by similarity desc \"\n","RESPONSE = KUSTO_CLIENT.execute(KUSTO_DATABASE, KUSTO_QUERY)\n","\n","df = dataframe_from_result_table(RESPONSE.primary_results[0])\n","df"]}],"metadata":{"kernel_info":{"name":"synapse_pyspark"},"kernelspec":{"display_name":"Synapse PySpark","language":"Python","name":"synapse_pyspark"},"language_info":{"name":"python"},"notebook_environment":{},"save_output":true,"spark_compute":{"compute_id":"/trident/default","session_options":{"conf":{},"enableDebugMode":false}},"synapse_widget":{"state":{},"version":"0.1"},"trident":{"lakehouse":{"default_lakehouse":"7a5ec84c-e155-4d5f-a4e6-d49f4628d60b","default_lakehouse_name":"TempLH","default_lakehouse_workspace_id":"14a81bdb-d1c4-4808-9396-b12faab604c3","known_lakehouses":[{"id":"7a5ec84c-e155-4d5f-a4e6-d49f4628d60b"}]}},"widgets":{}},"nbformat":4,"nbformat_minor":0}
+{"cells":[{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":[]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["# Kusto as a Vector database for AI embeddings"]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["This notebook provides step-by-step instructions on using Azure Data Explorer (Kusto) as a vector database with OpenAI embeddings. "]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["This notebook presents an end-to-end process of:\n","\n","1. Using precomputed embeddings created by OpenAI API.\n","2. Storing the embeddings in Kusto.\n","3. Converting raw text query to an embedding with OpenAI API.\n","4. Using Kusto to perform cosine similarity search in the stored embeddings\n"]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["### Prerequisites"]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["For the purposes of this exercise we need to prepare a couple of things:\n","\n","1. Azure Data Explorer(Kusto) server instance. https://azure.microsoft.com/en-us/products/data-explorer\n","3. Azure OpenAI credentials or OpenAI API key."]},{"cell_type":"code","execution_count":2,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:24:58.8253972Z","execution_start_time":"2023-05-10T09:24:58.8250545Z","livy_statement_state":"available","parent_msg_id":"affb2f05-b242-4152-99b2-f30e3f854c21","queued_time":"2023-05-10T09:24:43.3953963Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":-1},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, -1, Finished, Available)"]},"metadata":{},"output_type":"display_data"},{"data":{},"execution_count":2,"metadata":{},"output_type":"execute_result"},{"name":"stdout","output_type":"stream","text":["Collecting wget\n"," Downloading wget-3.2.zip (10 kB)\n"," Preparing metadata (setup.py) ... \u001b[?25ldone\n","\u001b[?25hBuilding wheels for collected packages: wget\n"," Building wheel for wget (setup.py) ... \u001b[?25l-\b \bdone\n","\u001b[?25h Created wheel for wget: filename=wget-3.2-py3-none-any.whl size=9657 sha256=10fd8aa1d20fd49c36389dc888acc721d0578c5a0635fc9fc5dc642c0f49522e\n"," Stored in directory: /home/trusted-service-user/.cache/pip/wheels/8b/f1/7f/5c94f0a7a505ca1c81cd1d9208ae2064675d97582078e6c769\n","Successfully built wget\n","Installing collected packages: wget\n","Successfully installed wget-3.2\n","\n","\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.0\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m23.1.2\u001b[0m\n","\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49m/nfs4/pyenv-27214bb4-edfd-4fdd-b888-8a99075a1416/bin/python -m pip install --upgrade pip\u001b[0m\n","Note: you may need to restart the kernel to use updated packages.\n"]},{"data":{},"execution_count":2,"metadata":{},"output_type":"execute_result"},{"name":"stdout","output_type":"stream","text":["Warning: PySpark kernel has been restarted to use updated packages.\n","\n"]}],"source":["%pip install wget"]},{"cell_type":"code","execution_count":3,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:25:13.0187836Z","execution_start_time":"2023-05-10T09:25:13.0184873Z","livy_statement_state":"available","parent_msg_id":"d4c4cf5b-21c4-4804-9db2-1f18a6be7733","queued_time":"2023-05-10T09:24:43.5454914Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":-1},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, -1, Finished, Available)"]},"metadata":{},"output_type":"display_data"},{"data":{},"execution_count":3,"metadata":{},"output_type":"execute_result"},{"name":"stdout","output_type":"stream","text":["Collecting openai\n"," Downloading openai-0.27.6-py3-none-any.whl (71 kB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m71.9/71.9 kB\u001b[0m \u001b[31m1.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m00:01\u001b[0m\n","\u001b[?25hRequirement already satisfied: tqdm in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from openai) (4.65.0)\n","Requirement already satisfied: requests>=2.20 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from openai) (2.28.2)\n","Requirement already satisfied: aiohttp in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from openai) (3.8.4)\n","Requirement already satisfied: urllib3<1.27,>=1.21.1 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from requests>=2.20->openai) (1.26.14)\n","Requirement already satisfied: certifi>=2017.4.17 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from requests>=2.20->openai) (2022.12.7)\n","Requirement already satisfied: idna<4,>=2.5 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from requests>=2.20->openai) (3.4)\n","Requirement already satisfied: charset-normalizer<4,>=2 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from requests>=2.20->openai) (2.1.1)\n","Requirement already satisfied: attrs>=17.3.0 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from aiohttp->openai) (22.2.0)\n","Requirement already satisfied: frozenlist>=1.1.1 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from aiohttp->openai) (1.3.3)\n","Requirement already satisfied: multidict<7.0,>=4.5 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from aiohttp->openai) (6.0.4)\n","Requirement already satisfied: yarl<2.0,>=1.0 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from aiohttp->openai) (1.8.2)\n","Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from aiohttp->openai) (4.0.2)\n","Requirement already satisfied: aiosignal>=1.1.2 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from aiohttp->openai) (1.3.1)\n","Installing collected packages: openai\n","Successfully installed openai-0.27.6\n","\n","\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.0\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m23.1.2\u001b[0m\n","\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49m/nfs4/pyenv-27214bb4-edfd-4fdd-b888-8a99075a1416/bin/python -m pip install --upgrade pip\u001b[0m\n","Note: you may need to restart the kernel to use updated packages.\n"]},{"data":{},"execution_count":3,"metadata":{},"output_type":"execute_result"},{"name":"stdout","output_type":"stream","text":["Warning: PySpark kernel has been restarted to use updated packages.\n","\n"]}],"source":["%pip install openai"]},{"cell_type":"code","execution_count":17,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:40:42.8774236Z","execution_start_time":"2023-05-10T09:40:42.8771662Z","livy_statement_state":"available","parent_msg_id":"7a7dfea4-d420-4b03-a2c6-82c65dfe177e","queued_time":"2023-05-10T09:40:30.9990512Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":-1},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, -1, Finished, Available)"]},"metadata":{},"output_type":"display_data"},{"data":{},"execution_count":17,"metadata":{},"output_type":"execute_result"},{"name":"stdout","output_type":"stream","text":["Requirement already satisfied: azure-kusto-data in /nfs4/pyenv-27214bb4-edfd-4fdd-b888-8a99075a1416/lib/python3.10/site-packages (4.1.4)\n","Requirement already satisfied: msal<2,>=1.9.0 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from azure-kusto-data) (1.21.0)\n","Requirement already satisfied: python-dateutil>=2.8.0 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from azure-kusto-data) (2.8.2)\n","Requirement already satisfied: azure-core<2,>=1.11.0 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from azure-kusto-data) (1.26.4)\n","Requirement already satisfied: requests>=2.13.0 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from azure-kusto-data) (2.28.2)\n","Requirement already satisfied: ijson~=3.1 in /nfs4/pyenv-27214bb4-edfd-4fdd-b888-8a99075a1416/lib/python3.10/site-packages (from azure-kusto-data) (3.2.0.post0)\n","Requirement already satisfied: azure-identity<2,>=1.5.0 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from azure-kusto-data) (1.12.0)\n","Requirement already satisfied: six>=1.11.0 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from azure-core<2,>=1.11.0->azure-kusto-data) (1.16.0)\n","Requirement already satisfied: typing-extensions>=4.3.0 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from azure-core<2,>=1.11.0->azure-kusto-data) (4.5.0)\n","Requirement already satisfied: cryptography>=2.5 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from azure-identity<2,>=1.5.0->azure-kusto-data) (40.0.1)\n","Requirement already satisfied: msal-extensions<2.0.0,>=0.3.0 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from azure-identity<2,>=1.5.0->azure-kusto-data) (1.0.0)\n","Requirement already satisfied: PyJWT[crypto]<3,>=1.0.0 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from msal<2,>=1.9.0->azure-kusto-data) (2.6.0)\n","Requirement already satisfied: urllib3<1.27,>=1.21.1 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from requests>=2.13.0->azure-kusto-data) (1.26.14)\n","Requirement already satisfied: charset-normalizer<4,>=2 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from requests>=2.13.0->azure-kusto-data) (2.1.1)\n","Requirement already satisfied: idna<4,>=2.5 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from requests>=2.13.0->azure-kusto-data) (3.4)\n","Requirement already satisfied: certifi>=2017.4.17 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from requests>=2.13.0->azure-kusto-data) (2022.12.7)\n","Requirement already satisfied: cffi>=1.12 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from cryptography>=2.5->azure-identity<2,>=1.5.0->azure-kusto-data) (1.15.1)\n","Requirement already satisfied: portalocker<3,>=1.0 in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from msal-extensions<2.0.0,>=0.3.0->azure-identity<2,>=1.5.0->azure-kusto-data) (2.7.0)\n","Requirement already satisfied: pycparser in /home/trusted-service-user/cluster-env/trident_env/lib/python3.10/site-packages (from cffi>=1.12->cryptography>=2.5->azure-identity<2,>=1.5.0->azure-kusto-data) (2.21)\n","\n","\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.0\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m23.1.2\u001b[0m\n","\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49m/nfs4/pyenv-27214bb4-edfd-4fdd-b888-8a99075a1416/bin/python -m pip install --upgrade pip\u001b[0m\n","Note: you may need to restart the kernel to use updated packages.\n"]},{"data":{},"execution_count":17,"metadata":{},"output_type":"execute_result"},{"name":"stdout","output_type":"stream","text":["Warning: PySpark kernel has been restarted to use updated packages.\n","\n"]}],"source":["%pip install azure-kusto-data"]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["### Download precomputed Embeddings\n","\n"]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["In this section we are going to load prepared embedding data, so you don't have to recompute the embeddings of Wikipedia articles with your own credits.\n"]},{"cell_type":"code","execution_count":5,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:25:28.6496025Z","execution_start_time":"2023-05-10T09:25:23.4822208Z","livy_statement_state":"available","parent_msg_id":"2d10f66b-3875-426b-abdf-b88b2d64d7ec","queued_time":"2023-05-10T09:24:44.1318823Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":17},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 17, Finished, Available)"]},"metadata":{},"output_type":"display_data"},{"data":{"text/plain":["'vector_database_wikipedia_articles_embedded.zip'"]},"execution_count":7,"metadata":{},"output_type":"execute_result"}],"source":["import wget\n","\n","embeddings_url = \"https://cdn.openai.com/API/examples/data/vector_database_wikipedia_articles_embedded.zip\"\n","\n","# The file is ~700 MB so this will take some time\n","wget.download(embeddings_url)"]},{"cell_type":"code","execution_count":6,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:25:50.6601867Z","execution_start_time":"2023-05-10T09:25:28.9912827Z","livy_statement_state":"available","parent_msg_id":"093e0086-0bc4-4fb8-b656-3484f31b675e","queued_time":"2023-05-10T09:24:44.6002568Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":18},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 18, Finished, Available)"]},"metadata":{},"output_type":"display_data"}],"source":["\n","import zipfile\n","\n","with zipfile.ZipFile(\"vector_database_wikipedia_articles_embedded.zip\",\"r\") as zip_ref:\n"," zip_ref.extractall(\"/lakehouse/default/Files/data\")"]},{"cell_type":"code","execution_count":7,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:31:38.5924721Z","execution_start_time":"2023-05-10T09:25:50.9770732Z","livy_statement_state":"available","parent_msg_id":"fab21836-4966-4068-8725-8fac982ca969","queued_time":"2023-05-10T09:24:44.8734372Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":19},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 19, Finished, Available)"]},"metadata":{},"output_type":"display_data"},{"data":{"text/html":["<div>\n","<style scoped>\n"," .dataframe tbody tr th:only-of-type {\n"," vertical-align: middle;\n"," }\n","\n"," .dataframe tbody tr th {\n"," vertical-align: top;\n"," }\n","\n"," .dataframe thead th {\n"," text-align: right;\n"," }\n","</style>\n","<table border=\"1\" class=\"dataframe\">\n"," <thead>\n"," <tr style=\"text-align: right;\">\n"," <th></th>\n"," <th>id</th>\n"," <th>url</th>\n"," <th>title</th>\n"," <th>text</th>\n"," <th>title_vector</th>\n"," <th>content_vector</th>\n"," <th>vector_id</th>\n"," </tr>\n"," </thead>\n"," <tbody>\n"," <tr>\n"," <th>0</th>\n"," <td>1</td>\n"," <td>https://simple.wikipedia.org/wiki/April</td>\n"," <td>April</td>\n"," <td>April is the fourth month of the year in the J...</td>\n"," <td>[0.001009464613161981, -0.020700545981526375, ...</td>\n"," <td>[-0.011253940872848034, -0.013491976074874401,...</td>\n"," <td>0</td>\n"," </tr>\n"," <tr>\n"," <th>1</th>\n"," <td>2</td>\n"," <td>https://simple.wikipedia.org/wiki/August</td>\n"," <td>August</td>\n"," <td>August (Aug.) is the eighth month of the year ...</td>\n"," <td>[0.0009286514250561595, 0.000820168002974242, ...</td>\n"," <td>[0.0003609954728744924, 0.007262262050062418, ...</td>\n"," <td>1</td>\n"," </tr>\n"," <tr>\n"," <th>2</th>\n"," <td>6</td>\n"," <td>https://simple.wikipedia.org/wiki/Art</td>\n"," <td>Art</td>\n"," <td>Art is a creative activity that expresses imag...</td>\n"," <td>[0.003393713850528002, 0.0061537534929811954, ...</td>\n"," <td>[-0.004959689453244209, 0.015772193670272827, ...</td>\n"," <td>2</td>\n"," </tr>\n"," <tr>\n"," <th>3</th>\n"," <td>8</td>\n"," <td>https://simple.wikipedia.org/wiki/A</td>\n"," <td>A</td>\n"," <td>A or a is the first letter of the English alph...</td>\n"," <td>[0.0153952119871974, -0.013759135268628597, 0....</td>\n"," <td>[0.024894846603274345, -0.022186409682035446, ...</td>\n"," <td>3</td>\n"," </tr>\n"," <tr>\n"," <th>4</th>\n"," <td>9</td>\n"," <td>https://simple.wikipedia.org/wiki/Air</td>\n"," <td>Air</td>\n"," <td>Air refers to the Earth's atmosphere. Air is a...</td>\n"," <td>[0.02224554680287838, -0.02044147066771984, -0...</td>\n"," <td>[0.021524671465158463, 0.018522677943110466, -...</td>\n"," <td>4</td>\n"," </tr>\n"," </tbody>\n","</table>\n","</div>"],"text/plain":[" id url title \\\n","0 1 https://simple.wikipedia.org/wiki/April April \n","1 2 https://simple.wikipedia.org/wiki/August August \n","2 6 https://simple.wikipedia.org/wiki/Art Art \n","3 8 https://simple.wikipedia.org/wiki/A A \n","4 9 https://simple.wikipedia.org/wiki/Air Air \n","\n"," text \\\n","0 April is the fourth month of the year in the J... \n","1 August (Aug.) is the eighth month of the year ... \n","2 Art is a creative activity that expresses imag... \n","3 A or a is the first letter of the English alph... \n","4 Air refers to the Earth's atmosphere. Air is a... \n","\n"," title_vector \\\n","0 [0.001009464613161981, -0.020700545981526375, ... \n","1 [0.0009286514250561595, 0.000820168002974242, ... \n","2 [0.003393713850528002, 0.0061537534929811954, ... \n","3 [0.0153952119871974, -0.013759135268628597, 0.... \n","4 [0.02224554680287838, -0.02044147066771984, -0... \n","\n"," content_vector vector_id \n","0 [-0.011253940872848034, -0.013491976074874401,... 0 \n","1 [0.0003609954728744924, 0.007262262050062418, ... 1 \n","2 [-0.004959689453244209, 0.015772193670272827, ... 2 \n","3 [0.024894846603274345, -0.022186409682035446, ... 3 \n","4 [0.021524671465158463, 0.018522677943110466, -... 4 "]},"execution_count":11,"metadata":{},"output_type":"execute_result"}],"source":["import pandas as pd\n","\n","from ast import literal_eval\n","\n","article_df = pd.read_csv('/lakehouse/default/Files/data/vector_database_wikipedia_articles_embedded.csv')\n","# Read vectors from strings back into a list\n","article_df[\"title_vector\"] = article_df.title_vector.apply(literal_eval)\n","article_df[\"content_vector\"] = article_df.content_vector.apply(literal_eval)\n","article_df.head()\n"]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["### Store vectors in a Kusto table\n"]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["Create a table & load the vectors in Kusto based on the contents in the dataframe. The spark option CreakeIfNotExists will automatically create a table if it doesn't exist\n"]},{"cell_type":"code","execution_count":20,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:41:07.7982707Z","execution_start_time":"2023-05-10T09:41:07.4379451Z","livy_statement_state":"available","parent_msg_id":"0a5fca1c-3aae-4b95-86c8-e098d0369f95","queued_time":"2023-05-10T09:41:07.1656842Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":37},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 37, Finished, Available)"]},"metadata":{},"output_type":"display_data"}],"source":["# replace with your AAD Tenant ID, Kusto Cluster URI, Kusto DB name and Kusto Table\n","AAD_TENANT_ID = \"\"\n","KUSTO_CLUSTER = \"\"\n","KUSTO_DATABASE = \"Vector\"\n","KUSTO_TABLE = \"Wiki\""]},{"cell_type":"code","execution_count":9,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:31:43.2629717Z","execution_start_time":"2023-05-10T09:31:39.5426716Z","livy_statement_state":"available","parent_msg_id":"ece408d2-5f62-4a31-acfb-530070444031","queued_time":"2023-05-10T09:24:45.2865763Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":21},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 21, Finished, Available)"]},"metadata":{},"output_type":"display_data"}],"source":["\n","kustoOptions = {\"kustoCluster\": KUSTO_CLUSTER, \"kustoDatabase\" :KUSTO_DATABASE, \"kustoTable\" : KUSTO_TABLE }\n","\n","# Replace the auth method based on your desired authentication mechanism - https://github.com/Azure/azure-kusto-spark/blob/master/docs/Authentication.md\n","access_token=mssparkutils.credentials.getToken(kustoOptions[\"kustoCluster\"])"]},{"cell_type":"code","execution_count":10,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:31:48.9063385Z","execution_start_time":"2023-05-10T09:31:43.5930348Z","livy_statement_state":"available","parent_msg_id":"421b9d33-f3ce-4f20-a8d4-5d0958f240c9","queued_time":"2023-05-10T09:24:45.5199822Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":22},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 22, Finished, Available)"]},"metadata":{},"output_type":"display_data"},{"name":"stderr","output_type":"stream","text":["/opt/spark/python/lib/pyspark.zip/pyspark/sql/pandas/conversion.py:604: FutureWarning: iteritems is deprecated and will be removed in a future version. Use .items instead.\n"]}],"source":["#Pandas data frame to spark dataframe\n","sparkDF=spark.createDataFrame(article_df)"]},{"cell_type":"code","execution_count":11,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:34:35.1205454Z","execution_start_time":"2023-05-10T09:31:49.2428848Z","livy_statement_state":"available","parent_msg_id":"7e182f67-e09f-4aa4-9fca-d67b13f01f19","queued_time":"2023-05-10T09:24:45.7895854Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[{"completionTime":"2023-05-10T09:32:55.544GMT","dataRead":0,"dataWritten":0,"description":"Job group for statement 23:\n# Write data to a Kusto table\nsparkDF.write. format(\"com.microsoft.kusto.spark.synapse.datasource\"). option(\"kustoCluster\",kustoOptions[\"kustoCluster\"]). option(\"kustoDatabase\",kustoOptions[\"kustoDatabase\"]). option(\"kustoTable\", kustoOptions[\"kustoTable\"]). option(\"accessToken\", access_token). option(\"tableCreateOptions\", \"CreateIfNotExist\").mode(\"Append\"). save()\n","jobGroup":"23","jobId":7,"killedTasksSummary":{},"name":"foreachPartition at KustoWriter.scala:116","numActiveStages":0,"numActiveTasks":0,"numCompletedIndices":8,"numCompletedStages":1,"numCompletedTasks":8,"numFailedStages":0,"numFailedTasks":0,"numKilledTasks":0,"numSkippedStages":0,"numSkippedTasks":0,"numTasks":8,"rowCount":0,"stageIds":[10],"status":"SUCCEEDED","submissionTime":"2023-05-10T09:32:00.547GMT"}],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":1,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":23},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 23, Finished, Available)"]},"metadata":{},"output_type":"display_data"}],"source":["# Write data to a Kusto table\n","sparkDF.write. \\\n","format(\"com.microsoft.kusto.spark.synapse.datasource\"). \\\n","option(\"kustoCluster\",kustoOptions[\"kustoCluster\"]). \\\n","option(\"kustoDatabase\",kustoOptions[\"kustoDatabase\"]). \\\n","option(\"kustoTable\", kustoOptions[\"kustoTable\"]). \\\n","option(\"accessToken\", access_token). \\\n","option(\"tableCreateOptions\", \"CreateIfNotExist\").\\\n","mode(\"Append\"). \\\n","save()\n"]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["### Prepare your OpenAI API key\n","# "]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["The OpenAI API key is used for vectorization of the documents and queries. You can follow the instructions to create and retrieve your Azure OpenAI key and endpoint. https://learn.microsoft.com/en-us/azure/cognitive-services/openai/tutorials/embeddings\n","\n","\n","Please make sure to use the `text-embedding-3-small` model. Since the precomputed embeddings were created with `text-embedding-3-small` model we also have to use it during search.\n"]},{"cell_type":"code","execution_count":26,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:41:51.4743874Z","execution_start_time":"2023-05-10T09:41:51.1273995Z","livy_statement_state":"available","parent_msg_id":"53239dc7-36b8-4cbc-a4db-ce263729cd4f","queued_time":"2023-05-10T09:41:50.8249073Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":43},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 43, Finished, Available)"]},"metadata":{},"output_type":"display_data"}],"source":["import openai"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["#### If using Azure Open AI"]},{"cell_type":"code","execution_count":27,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:41:53.0029722Z","execution_start_time":"2023-05-10T09:41:52.6610261Z","livy_statement_state":"available","parent_msg_id":"9546736c-bebc-411d-a50a-6cf69eb5e70d","queued_time":"2023-05-10T09:41:52.3687239Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":44},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 44, Finished, Available)"]},"metadata":{},"output_type":"display_data"}],"source":["openai.api_version = '2022-12-01'\n","openai.api_base = '' # Please add your endpoint here\n","openai.api_type = 'azure'\n","openai.api_key = '' # Please add your api key here\n","\n","def embed(query):\n"," # Creates embedding vector from user query\n"," embedded_query = openai.Embedding.create(\n"," input=query,\n"," deployment_id=\"embed\", #replace with your deployment id\n"," chunk_size=1\n"," )[\"data\"][0][\"embedding\"]\n"," return embedded_query"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["#### If using Open AI"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["Only run this cell if you plan to use Open AI for embedding"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["openai.api_key = \"\"\n","\n","\n","def embed(query):\n"," # Creates embedding vector from user query\n"," embedded_query = openai.Embedding.create(\n"," input=query,\n"," model=\"text-embedding-3-small\",\n"," )[\"data\"][0][\"embedding\"]\n"," return embedded_query"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["### Generate embedding for the search term"]},{"cell_type":"code","execution_count":28,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:41:56.2227563Z","execution_start_time":"2023-05-10T09:41:55.1887813Z","livy_statement_state":"available","parent_msg_id":"1001b7dc-2b09-421e-aca4-e7a2b17c7d0e","queued_time":"2023-05-10T09:41:54.8728344Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":45},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 45, Finished, Available)"]},"metadata":{},"output_type":"display_data"}],"source":["\n","searchedEmbedding = embed(\"places where you worship\")\n","#print(searchedEmbedding)"]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["#### Semantic search in Kusto "]},{"attachments":{},"cell_type":"markdown","metadata":{"nteract":{"transient":{"deleting":false}}},"source":["We will search the Kusto table for the closest vectors.\n","\n","We will be using the series-cosine-similarity-fl UDF for similarity search. \n","\n","Please create the function in your database before proceeding -\n","https://learn.microsoft.com/en-us/azure/data-explorer/kusto/functions-library/series-cosine-similarity-fl?tabs=query-defined"]},{"cell_type":"code","execution_count":18,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:40:52.3506224Z","execution_start_time":"2023-05-10T09:40:51.397278Z","livy_statement_state":"available","parent_msg_id":"5c692f91-d611-4f22-a2f3-e008bb8d89d8","queued_time":"2023-05-10T09:40:46.211323Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":35},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 35, Finished, Available)"]},"metadata":{},"output_type":"display_data"}],"source":["from azure.kusto.data import KustoClient, KustoConnectionStringBuilder\n","from azure.kusto.data.exceptions import KustoServiceError\n","from azure.kusto.data.helpers import dataframe_from_result_table\n","import pandas as pd"]},{"cell_type":"code","execution_count":21,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:41:14.0650747Z","execution_start_time":"2023-05-10T09:41:13.6897398Z","livy_statement_state":"available","parent_msg_id":"2e004b80-df5e-4873-8dc4-dc9b0fcdfd1b","queued_time":"2023-05-10T09:41:13.4128259Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":38},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 38, Finished, Available)"]},"metadata":{},"output_type":"display_data"}],"source":["KCSB = KustoConnectionStringBuilder.with_aad_device_authentication(\n"," KUSTO_CLUSTER)\n","KCSB.authority_id = AAD_TENANT_ID"]},{"cell_type":"code","execution_count":22,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:41:17.1788945Z","execution_start_time":"2023-05-10T09:41:16.7709048Z","livy_statement_state":"available","parent_msg_id":"7b74117d-03a9-4963-9fbf-83dcf5eb33a8","queued_time":"2023-05-10T09:41:16.4790182Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":39},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 39, Finished, Available)"]},"metadata":{},"output_type":"display_data"}],"source":["KUSTO_CLIENT = KustoClient(KCSB)"]},{"cell_type":"code","execution_count":31,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:45:56.5295656Z","execution_start_time":"2023-05-10T09:45:54.8312637Z","livy_statement_state":"available","parent_msg_id":"848897fc-69b2-4108-8cb7-844d8dd473d7","queued_time":"2023-05-10T09:45:54.458869Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":48},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 48, Finished, Available)"]},"metadata":{},"output_type":"display_data"}],"source":["KUSTO_QUERY = \"Wiki | extend similarity = series_cosine_similarity_fl(dynamic(\"+str(searchedEmbedding)+\"), content_vector,1,1) | top 10 by similarity desc \"\n","\n","RESPONSE = KUSTO_CLIENT.execute(KUSTO_DATABASE, KUSTO_QUERY)"]},{"cell_type":"code","execution_count":32,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:46:02.8573664Z","execution_start_time":"2023-05-10T09:46:02.496154Z","livy_statement_state":"available","parent_msg_id":"36d4dd76-ca76-4ce0-aa35-5cd8d7c26b6f","queued_time":"2023-05-10T09:46:02.2249009Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":49},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 49, Finished, Available)"]},"metadata":{},"output_type":"display_data"},{"data":{"text/html":["<div>\n","<style scoped>\n"," .dataframe tbody tr th:only-of-type {\n"," vertical-align: middle;\n"," }\n","\n"," .dataframe tbody tr th {\n"," vertical-align: top;\n"," }\n","\n"," .dataframe thead th {\n"," text-align: right;\n"," }\n","</style>\n","<table border=\"1\" class=\"dataframe\">\n"," <thead>\n"," <tr style=\"text-align: right;\">\n"," <th></th>\n"," <th>id</th>\n"," <th>url</th>\n"," <th>title</th>\n"," <th>text</th>\n"," <th>title_vector</th>\n"," <th>content_vector</th>\n"," <th>vector_id</th>\n"," <th>similarity</th>\n"," </tr>\n"," </thead>\n"," <tbody>\n"," <tr>\n"," <th>0</th>\n"," <td>852</td>\n"," <td>https://simple.wikipedia.org/wiki/Temple</td>\n"," <td>Temple</td>\n"," <td>A temple is a building where people go to prac...</td>\n"," <td>[-0.021837441250681877, -0.007722342386841774,...</td>\n"," <td>[-0.0019541378132998943, 0.007151313126087189,...</td>\n"," <td>413</td>\n"," <td>0.834495</td>\n"," </tr>\n"," <tr>\n"," <th>1</th>\n"," <td>78094</td>\n"," <td>https://simple.wikipedia.org/wiki/Christian%20...</td>\n"," <td>Christian worship</td>\n"," <td>In Christianity, worship has been thought as b...</td>\n"," <td>[0.0017675267299637198, -0.008890199474990368,...</td>\n"," <td>[0.020530683919787407, 0.0024345638230443, -0....</td>\n"," <td>20320</td>\n"," <td>0.832132</td>\n"," </tr>\n"," <tr>\n"," <th>2</th>\n"," <td>59154</td>\n"," <td>https://simple.wikipedia.org/wiki/Service%20of...</td>\n"," <td>Service of worship</td>\n"," <td>A service of worship is a religious meeting wh...</td>\n"," <td>[-0.007969820871949196, 0.0004240311391185969,...</td>\n"," <td>[0.003784010885283351, -0.0030924836173653603,...</td>\n"," <td>15519</td>\n"," <td>0.831633</td>\n"," </tr>\n"," <tr>\n"," <th>3</th>\n"," <td>51910</td>\n"," <td>https://simple.wikipedia.org/wiki/Worship</td>\n"," <td>Worship</td>\n"," <td>Worship is a word often used in religion. It ...</td>\n"," <td>[0.0036036288365721703, -0.01276545226573944, ...</td>\n"," <td>[0.007925753481686115, -0.0110504487529397, 0....</td>\n"," <td>14010</td>\n"," <td>0.828185</td>\n"," </tr>\n"," <tr>\n"," <th>4</th>\n"," <td>29576</td>\n"," <td>https://simple.wikipedia.org/wiki/Altar</td>\n"," <td>Altar</td>\n"," <td>An altar is a place, often a table, where a re...</td>\n"," <td>[0.007887467741966248, -0.02706138789653778, -...</td>\n"," <td>[0.023901859298348427, -0.031175222247838977, ...</td>\n"," <td>8708</td>\n"," <td>0.824124</td>\n"," </tr>\n"," <tr>\n"," <th>5</th>\n"," <td>92507</td>\n"," <td>https://simple.wikipedia.org/wiki/Shrine</td>\n"," <td>Shrine</td>\n"," <td>A shrine is a holy or sacred place with someth...</td>\n"," <td>[-0.011601685546338558, 0.006366696208715439, ...</td>\n"," <td>[0.016423320397734642, -0.0015560361789539456,...</td>\n"," <td>23945</td>\n"," <td>0.823863</td>\n"," </tr>\n"," <tr>\n"," <th>6</th>\n"," <td>815</td>\n"," <td>https://simple.wikipedia.org/wiki/Synagogue</td>\n"," <td>Synagogue</td>\n"," <td>A synagogue is a place where Jews meet to wors...</td>\n"," <td>[-0.017317570745944977, 0.0022673190105706453,...</td>\n"," <td>[-0.004515442531555891, 0.003739549545571208, ...</td>\n"," <td>398</td>\n"," <td>0.819942</td>\n"," </tr>\n"," <tr>\n"," <th>7</th>\n"," <td>68080</td>\n"," <td>https://simple.wikipedia.org/wiki/Shinto%20shrine</td>\n"," <td>Shinto shrine</td>\n"," <td>A Shinto shrine is a sacred place or site wher...</td>\n"," <td>[0.0035740730818361044, 0.0028098472394049168,...</td>\n"," <td>[0.011014971882104874, 0.00042272370774298906,...</td>\n"," <td>18106</td>\n"," <td>0.818475</td>\n"," </tr>\n"," <tr>\n"," <th>8</th>\n"," <td>57790</td>\n"," <td>https://simple.wikipedia.org/wiki/Chapel</td>\n"," <td>Chapel</td>\n"," <td>A chapel is a place for Christian worship. The...</td>\n"," <td>[-0.01371884811669588, 0.0031672674231231213, ...</td>\n"," <td>[0.002526090247556567, 0.02482965588569641, 0....</td>\n"," <td>15260</td>\n"," <td>0.817608</td>\n"," </tr>\n"," <tr>\n"," <th>9</th>\n"," <td>142</td>\n"," <td>https://simple.wikipedia.org/wiki/Church%20%28...</td>\n"," <td>Church (building)</td>\n"," <td>A church is a building that was constructed to...</td>\n"," <td>[0.0021336888894438744, 0.0029748091474175453,...</td>\n"," <td>[0.016109377145767212, 0.022908871993422508, 0...</td>\n"," <td>74</td>\n"," <td>0.812636</td>\n"," </tr>\n"," </tbody>\n","</table>\n","</div>"],"text/plain":[" id url \\\n","0 852 https://simple.wikipedia.org/wiki/Temple \n","1 78094 https://simple.wikipedia.org/wiki/Christian%20... \n","2 59154 https://simple.wikipedia.org/wiki/Service%20of... \n","3 51910 https://simple.wikipedia.org/wiki/Worship \n","4 29576 https://simple.wikipedia.org/wiki/Altar \n","5 92507 https://simple.wikipedia.org/wiki/Shrine \n","6 815 https://simple.wikipedia.org/wiki/Synagogue \n","7 68080 https://simple.wikipedia.org/wiki/Shinto%20shrine \n","8 57790 https://simple.wikipedia.org/wiki/Chapel \n","9 142 https://simple.wikipedia.org/wiki/Church%20%28... \n","\n"," title text \\\n","0 Temple A temple is a building where people go to prac... \n","1 Christian worship In Christianity, worship has been thought as b... \n","2 Service of worship A service of worship is a religious meeting wh... \n","3 Worship Worship is a word often used in religion. It ... \n","4 Altar An altar is a place, often a table, where a re... \n","5 Shrine A shrine is a holy or sacred place with someth... \n","6 Synagogue A synagogue is a place where Jews meet to wors... \n","7 Shinto shrine A Shinto shrine is a sacred place or site wher... \n","8 Chapel A chapel is a place for Christian worship. The... \n","9 Church (building) A church is a building that was constructed to... \n","\n"," title_vector \\\n","0 [-0.021837441250681877, -0.007722342386841774,... \n","1 [0.0017675267299637198, -0.008890199474990368,... \n","2 [-0.007969820871949196, 0.0004240311391185969,... \n","3 [0.0036036288365721703, -0.01276545226573944, ... \n","4 [0.007887467741966248, -0.02706138789653778, -... \n","5 [-0.011601685546338558, 0.006366696208715439, ... \n","6 [-0.017317570745944977, 0.0022673190105706453,... \n","7 [0.0035740730818361044, 0.0028098472394049168,... \n","8 [-0.01371884811669588, 0.0031672674231231213, ... \n","9 [0.0021336888894438744, 0.0029748091474175453,... \n","\n"," content_vector vector_id similarity \n","0 [-0.0019541378132998943, 0.007151313126087189,... 413 0.834495 \n","1 [0.020530683919787407, 0.0024345638230443, -0.... 20320 0.832132 \n","2 [0.003784010885283351, -0.0030924836173653603,... 15519 0.831633 \n","3 [0.007925753481686115, -0.0110504487529397, 0.... 14010 0.828185 \n","4 [0.023901859298348427, -0.031175222247838977, ... 8708 0.824124 \n","5 [0.016423320397734642, -0.0015560361789539456,... 23945 0.823863 \n","6 [-0.004515442531555891, 0.003739549545571208, ... 398 0.819942 \n","7 [0.011014971882104874, 0.00042272370774298906,... 18106 0.818475 \n","8 [0.002526090247556567, 0.02482965588569641, 0.... 15260 0.817608 \n","9 [0.016109377145767212, 0.022908871993422508, 0... 74 0.812636 "]},"execution_count":33,"metadata":{},"output_type":"execute_result"}],"source":["df = dataframe_from_result_table(RESPONSE.primary_results[0])\n","df"]},{"cell_type":"code","execution_count":null,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[],"source":["searchedEmbedding = embed(\"unfortunate events in history\")\n"]},{"cell_type":"code","execution_count":35,"metadata":{"jupyter":{"outputs_hidden":false,"source_hidden":false},"nteract":{"transient":{"deleting":false}}},"outputs":[{"data":{"application/vnd.livy.statement-meta+json":{"execution_finish_time":"2023-05-10T09:48:43.6147167Z","execution_start_time":"2023-05-10T09:48:41.8371731Z","livy_statement_state":"available","parent_msg_id":"3dd276f3-a68e-44f7-8205-253d772aea18","queued_time":"2023-05-10T09:48:41.4581244Z","session_id":"7e5070d2-4560-4fb8-a3a8-6a594acd58ab","session_start_time":null,"spark_jobs":{"jobs":[],"limit":20,"numbers":{"FAILED":0,"RUNNING":0,"SUCCEEDED":0,"UNKNOWN":0},"rule":"ALL_DESC"},"spark_pool":null,"state":"finished","statement_id":52},"text/plain":["StatementMeta(, 7e5070d2-4560-4fb8-a3a8-6a594acd58ab, 52, Finished, Available)"]},"metadata":{},"output_type":"display_data"},{"data":{"text/html":["<div>\n","<style scoped>\n"," .dataframe tbody tr th:only-of-type {\n"," vertical-align: middle;\n"," }\n","\n"," .dataframe tbody tr th {\n"," vertical-align: top;\n"," }\n","\n"," .dataframe thead th {\n"," text-align: right;\n"," }\n","</style>\n","<table border=\"1\" class=\"dataframe\">\n"," <thead>\n"," <tr style=\"text-align: right;\">\n"," <th></th>\n"," <th>id</th>\n"," <th>url</th>\n"," <th>title</th>\n"," <th>text</th>\n"," <th>title_vector</th>\n"," <th>content_vector</th>\n"," <th>vector_id</th>\n"," <th>similarity</th>\n"," </tr>\n"," </thead>\n"," <tbody>\n"," <tr>\n"," <th>0</th>\n"," <td>848</td>\n"," <td>https://simple.wikipedia.org/wiki/Tragedy</td>\n"," <td>Tragedy</td>\n"," <td>In theatre, a tragedy as defined by Aristotle ...</td>\n"," <td>[-0.019502468407154083, -0.010160734876990318,...</td>\n"," <td>[-0.012951433658599854, -0.018836138769984245,...</td>\n"," <td>410</td>\n"," <td>0.851848</td>\n"," </tr>\n"," <tr>\n"," <th>1</th>\n"," <td>4469</td>\n"," <td>https://simple.wikipedia.org/wiki/The%20Holocaust</td>\n"," <td>The Holocaust</td>\n"," <td>The Holocaust, sometimes called The Shoah (), ...</td>\n"," <td>[-0.030233195051550865, -0.024401605129241943,...</td>\n"," <td>[-0.016398731619119644, -0.013267949223518372,...</td>\n"," <td>1203</td>\n"," <td>0.847222</td>\n"," </tr>\n"," <tr>\n"," <th>2</th>\n"," <td>64216</td>\n"," <td>https://simple.wikipedia.org/wiki/List%20of%20...</td>\n"," <td>List of historical plagues</td>\n"," <td>This list contains famous or well documented o...</td>\n"," <td>[-0.010667890310287476, -0.0003575817099772393...</td>\n"," <td>[-0.010863155126571655, -0.0012196656316518784...</td>\n"," <td>16859</td>\n"," <td>0.844411</td>\n"," </tr>\n"," <tr>\n"," <th>3</th>\n"," <td>4397</td>\n"," <td>https://simple.wikipedia.org/wiki/List%20of%20...</td>\n"," <td>List of disasters</td>\n"," <td>This is a list of disasters, both natural and ...</td>\n"," <td>[-0.02713736332952976, -0.005278210621327162, ...</td>\n"," <td>[-0.023679986596107483, -0.006126823835074902,...</td>\n"," <td>1158</td>\n"," <td>0.843063</td>\n"," </tr>\n"," <tr>\n"," <th>4</th>\n"," <td>23073</td>\n"," <td>https://simple.wikipedia.org/wiki/Disaster</td>\n"," <td>Disaster</td>\n"," <td>A disaster is something very not good that hap...</td>\n"," <td>[-0.018235962837934497, -0.020034968852996823,...</td>\n"," <td>[-0.02504003793001175, 0.007415903266519308, 0...</td>\n"," <td>7251</td>\n"," <td>0.840334</td>\n"," </tr>\n"," <tr>\n"," <th>5</th>\n"," <td>4382</td>\n"," <td>https://simple.wikipedia.org/wiki/List%20of%20...</td>\n"," <td>List of terrorist incidents</td>\n"," <td>The following is a list by date of acts and fa...</td>\n"," <td>[-0.03989032283425331, -0.012808636762201786, ...</td>\n"," <td>[-0.045838188380002975, -0.01682935282588005, ...</td>\n"," <td>1149</td>\n"," <td>0.836162</td>\n"," </tr>\n"," <tr>\n"," <th>6</th>\n"," <td>13528</td>\n"," <td>https://simple.wikipedia.org/wiki/A%20Series%2...</td>\n"," <td>A Series of Unfortunate Events</td>\n"," <td>A Series of Unfortunate Events is a series of ...</td>\n"," <td>[0.0010618815431371331, -0.0267023965716362, -...</td>\n"," <td>[0.002801976166665554, -0.02904471382498741, -...</td>\n"," <td>4347</td>\n"," <td>0.835172</td>\n"," </tr>\n"," <tr>\n"," <th>7</th>\n"," <td>42874</td>\n"," <td>https://simple.wikipedia.org/wiki/History%20of...</td>\n"," <td>History of the world</td>\n"," <td>The history of the world (also called human hi...</td>\n"," <td>[0.0026915925554931164, -0.022206028923392296,...</td>\n"," <td>[0.013645033352077007, -0.005165994167327881, ...</td>\n"," <td>11672</td>\n"," <td>0.830243</td>\n"," </tr>\n"," <tr>\n"," <th>8</th>\n"," <td>4452</td>\n"," <td>https://simple.wikipedia.org/wiki/Accident</td>\n"," <td>Accident</td>\n"," <td>An accident is when something goes wrong when ...</td>\n"," <td>[-0.004075294826179743, -0.0059883203357458115...</td>\n"," <td>[0.00926120299845934, 0.013705797493457794, 0....</td>\n"," <td>1190</td>\n"," <td>0.826898</td>\n"," </tr>\n"," <tr>\n"," <th>9</th>\n"," <td>324</td>\n"," <td>https://simple.wikipedia.org/wiki/History</td>\n"," <td>History</td>\n"," <td>History is the study of past events. People kn...</td>\n"," <td>[0.006603690329939127, -0.011856242083013058, ...</td>\n"," <td>[0.0048830462619662285, 0.0032003086525946856,...</td>\n"," <td>170</td>\n"," <td>0.824645</td>\n"," </tr>\n"," </tbody>\n","</table>\n","</div>"],"text/plain":[" id url \\\n","0 848 https://simple.wikipedia.org/wiki/Tragedy \n","1 4469 https://simple.wikipedia.org/wiki/The%20Holocaust \n","2 64216 https://simple.wikipedia.org/wiki/List%20of%20... \n","3 4397 https://simple.wikipedia.org/wiki/List%20of%20... \n","4 23073 https://simple.wikipedia.org/wiki/Disaster \n","5 4382 https://simple.wikipedia.org/wiki/List%20of%20... \n","6 13528 https://simple.wikipedia.org/wiki/A%20Series%2... \n","7 42874 https://simple.wikipedia.org/wiki/History%20of... \n","8 4452 https://simple.wikipedia.org/wiki/Accident \n","9 324 https://simple.wikipedia.org/wiki/History \n","\n"," title \\\n","0 Tragedy \n","1 The Holocaust \n","2 List of historical plagues \n","3 List of disasters \n","4 Disaster \n","5 List of terrorist incidents \n","6 A Series of Unfortunate Events \n","7 History of the world \n","8 Accident \n","9 History \n","\n"," text \\\n","0 In theatre, a tragedy as defined by Aristotle ... \n","1 The Holocaust, sometimes called The Shoah (), ... \n","2 This list contains famous or well documented o... \n","3 This is a list of disasters, both natural and ... \n","4 A disaster is something very not good that hap... \n","5 The following is a list by date of acts and fa... \n","6 A Series of Unfortunate Events is a series of ... \n","7 The history of the world (also called human hi... \n","8 An accident is when something goes wrong when ... \n","9 History is the study of past events. People kn... \n","\n"," title_vector \\\n","0 [-0.019502468407154083, -0.010160734876990318,... \n","1 [-0.030233195051550865, -0.024401605129241943,... \n","2 [-0.010667890310287476, -0.0003575817099772393... \n","3 [-0.02713736332952976, -0.005278210621327162, ... \n","4 [-0.018235962837934497, -0.020034968852996823,... \n","5 [-0.03989032283425331, -0.012808636762201786, ... \n","6 [0.0010618815431371331, -0.0267023965716362, -... \n","7 [0.0026915925554931164, -0.022206028923392296,... \n","8 [-0.004075294826179743, -0.0059883203357458115... \n","9 [0.006603690329939127, -0.011856242083013058, ... \n","\n"," content_vector vector_id similarity \n","0 [-0.012951433658599854, -0.018836138769984245,... 410 0.851848 \n","1 [-0.016398731619119644, -0.013267949223518372,... 1203 0.847222 \n","2 [-0.010863155126571655, -0.0012196656316518784... 16859 0.844411 \n","3 [-0.023679986596107483, -0.006126823835074902,... 1158 0.843063 \n","4 [-0.02504003793001175, 0.007415903266519308, 0... 7251 0.840334 \n","5 [-0.045838188380002975, -0.01682935282588005, ... 1149 0.836162 \n","6 [0.002801976166665554, -0.02904471382498741, -... 4347 0.835172 \n","7 [0.013645033352077007, -0.005165994167327881, ... 11672 0.830243 \n","8 [0.00926120299845934, 0.013705797493457794, 0.... 1190 0.826898 \n","9 [0.0048830462619662285, 0.0032003086525946856,... 170 0.824645 "]},"execution_count":39,"metadata":{},"output_type":"execute_result"}],"source":["KUSTO_QUERY = \"Wiki | extend similarity = series_cosine_similarity_fl(dynamic(\"+str(searchedEmbedding)+\"), title_vector,1,1) | top 10 by similarity desc \"\n","RESPONSE = KUSTO_CLIENT.execute(KUSTO_DATABASE, KUSTO_QUERY)\n","\n","df = dataframe_from_result_table(RESPONSE.primary_results[0])\n","df"]}],"metadata":{"kernel_info":{"name":"synapse_pyspark"},"kernelspec":{"display_name":"Synapse PySpark","language":"Python","name":"synapse_pyspark"},"language_info":{"name":"python"},"notebook_environment":{},"save_output":true,"spark_compute":{"compute_id":"/trident/default","session_options":{"conf":{},"enableDebugMode":false}},"synapse_widget":{"state":{},"version":"0.1"},"trident":{"lakehouse":{"default_lakehouse":"7a5ec84c-e155-4d5f-a4e6-d49f4628d60b","default_lakehouse_name":"TempLH","default_lakehouse_workspace_id":"14a81bdb-d1c4-4808-9396-b12faab604c3","known_lakehouses":[{"id":"7a5ec84c-e155-4d5f-a4e6-d49f4628d60b"}]}},"widgets":{}},"nbformat":4,"nbformat_minor":0}
diff --git a/examples/vector_databases/milvus/Filtered_search_with_Milvus_and_OpenAI.ipynb b/examples/vector_databases/milvus/Filtered_search_with_Milvus_and_OpenAI.ipynb
index e6aadfb3..b098e040 100644
--- a/examples/vector_databases/milvus/Filtered_search_with_Milvus_and_OpenAI.ipynb
+++ b/examples/vector_databases/milvus/Filtered_search_with_Milvus_and_OpenAI.ipynb
@@ -304,7 +304,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "This next step does the actual inserting. We iterate through all the entries and create batches that we insert once we hit our set batch size. After the loop is over we insert the last remaning batch if it exists. "
+ "This next step does the actual inserting. We iterate through all the entries and create batches that we insert once we hit our set batch size. After the loop is over we insert the last remaining batch if it exists. "
]
},
{
diff --git a/examples/vector_databases/milvus/Getting_started_with_Milvus_and_OpenAI.ipynb b/examples/vector_databases/milvus/Getting_started_with_Milvus_and_OpenAI.ipynb
index 9ea14250..a3bd2450 100644
--- a/examples/vector_databases/milvus/Getting_started_with_Milvus_and_OpenAI.ipynb
+++ b/examples/vector_databases/milvus/Getting_started_with_Milvus_and_OpenAI.ipynb
@@ -412,7 +412,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "This next step does the actual inserting. Due to having so many datapoints, if you want to immidiately test it out you can stop the inserting cell block early and move along. Doing this will probably decrease the accuracy of the results due to less datapoints, but it should still be good enough. "
+ "This next step inserts the data. Because there are so many data points, you can stop the insertion cell early if you want to test the workflow immediately. Using fewer data points will probably reduce the accuracy of the results, but it should still be sufficient for a test. "
]
},
{
@@ -487,7 +487,7 @@
"metadata": {},
"source": [
"## Query the Database\n",
- "With our data safely inserted in Milvus, we can now perform a query. The query takes in a string or a list of strings and searches them. The resuts print out your provided description and the results that include the result score, the result title, and the result book description. "
+ "With our data safely inserted in Milvus, we can now perform a query. The query takes in a string or a list of strings and searches them. The output includes your query and each result's score, title, and book description. "
]
},
{
diff --git a/examples/vector_databases/mongodb_atlas/semantic_search_using_mongodb_atlas_vector_search.ipynb b/examples/vector_databases/mongodb_atlas/semantic_search_using_mongodb_atlas_vector_search.ipynb
index fe4f9b22..4869ceb7 100644
--- a/examples/vector_databases/mongodb_atlas/semantic_search_using_mongodb_atlas_vector_search.ipynb
+++ b/examples/vector_databases/mongodb_atlas/semantic_search_using_mongodb_atlas_vector_search.ipynb
@@ -229,7 +229,7 @@
"id": "ShPbxQPaPvHD"
},
"source": [
- "After executing the above, the documents in \"movies\" collection will contain an additional field of \"embedding\", as defined by the `EMBEDDDING_FIELD_NAME` variable, apart from already existing fields like title, plot, genres, cast, directors, etc."
+ "After executing the above, the documents in \"movies\" collection will contain an additional field of \"embedding\", as defined by the `EMBEDDING_FIELD_NAME` variable, apart from already existing fields like title, plot, genres, cast, directors, etc."
]
},
{
@@ -263,7 +263,7 @@
"id": "ymRTaFb1X5Tq"
},
"source": [
- "Now head over to [Atlas UI](cloud.mongodb.com) and create an Atlas Vector Search index using the steps descibed [here](https://www.mongodb.com/docs/atlas/atlas-vector-search/vector-search-tutorial/#create-the-atlas-vector-search-index). The 'dimensions' field with value 1536, corresponds to openAI text-embedding-ada002.\n",
+ "Now head over to [Atlas UI](https://cloud.mongodb.com) and create an Atlas Vector Search index using the steps described [here](https://www.mongodb.com/docs/atlas/atlas-vector-search/vector-search-tutorial/#create-the-atlas-vector-search-index). The 'dimensions' field with value 1536, corresponds to OpenAI text-embedding-ada-002.\n",
"\n",
"Use the definition given below in the JSON editor on the Atlas UI.\n",
"\n",
@@ -289,7 +289,7 @@
"id": "2l5BzUgncjiq"
},
"source": [
- "(Optional) Alternatively, we can use [pymongo driver to create these vector search indexes programatically](https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.create_search_index)\n",
+ "(Optional) Alternatively, we can use [pymongo driver to create these vector search indexes programmatically](https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.create_search_index)\n",
"The python command given in the cell below will create the index (this only works for the most recent version of the Python Driver for MongoDB and MongoDB server version 7.0+ Atlas cluster)."
]
},
diff --git a/examples/vector_databases/neon/neon-postgres-vector-search-pgvector.ipynb b/examples/vector_databases/neon/neon-postgres-vector-search-pgvector.ipynb
index a836a74a..739a7d4a 100644
--- a/examples/vector_databases/neon/neon-postgres-vector-search-pgvector.ipynb
+++ b/examples/vector_databases/neon/neon-postgres-vector-search-pgvector.ipynb
@@ -358,7 +358,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Check the number of records to ensure the data has been been loaded. There should be 25000 records."
+ "Check the number of records to ensure the data has been loaded. There should be 25000 records."
]
},
{
diff --git a/examples/vector_databases/pinecone/Using_Pinecone_for_embeddings_search.ipynb b/examples/vector_databases/pinecone/Using_Pinecone_for_embeddings_search.ipynb
index 86689d0a..a7b54356 100644
--- a/examples/vector_databases/pinecone/Using_Pinecone_for_embeddings_search.ipynb
+++ b/examples/vector_databases/pinecone/Using_Pinecone_for_embeddings_search.ipynb
@@ -344,7 +344,7 @@
"\n",
"The next option we'll look at is **Pinecone**, a managed vector database which offers a cloud-native option.\n",
"\n",
- "Before you proceed with this step you'll need to navigate to [Pinecone](pinecone.io), sign up and then save your API key as an environment variable titled ```PINECONE_API_KEY```.\n",
+ "Before you proceed with this step you'll need to navigate to [Pinecone](https://www.pinecone.io), sign up and then save your API key as an environment variable titled ```PINECONE_API_KEY```.\n",
"\n",
"For section we will:\n",
"- Create an index with multiple namespaces for article titles and content\n",
diff --git a/examples/vector_databases/redis/Using_Redis_for_embeddings_search.ipynb b/examples/vector_databases/redis/Using_Redis_for_embeddings_search.ipynb
index 5e2443e9..f70fce0d 100644
--- a/examples/vector_databases/redis/Using_Redis_for_embeddings_search.ipynb
+++ b/examples/vector_databases/redis/Using_Redis_for_embeddings_search.ipynb
@@ -365,7 +365,7 @@
"source": [
"## Setup\n",
"\n",
- "There are many ways to deploy Redis with RediSearch. The easiest way to get started is to use Docker, but there are are many potential options for deployment. For other deployment options, see the [redis directory](./redis) in this repo.\n",
+ "There are many ways to deploy Redis with RediSearch. The easiest way to get started is to use Docker, but there are many potential options for deployment. For other deployment options, see the [Redis directory](.) in this repo.\n",
"\n",
"For this tutorial, we will use Redis Stack on Docker.\n",
"\n",
diff --git a/examples/vector_databases/typesense/Using_Typesense_for_embeddings_search.ipynb b/examples/vector_databases/typesense/Using_Typesense_for_embeddings_search.ipynb
index 3dfd3d7f..f9ccf469 100644
--- a/examples/vector_databases/typesense/Using_Typesense_for_embeddings_search.ipynb
+++ b/examples/vector_databases/typesense/Using_Typesense_for_embeddings_search.ipynb
@@ -325,7 +325,7 @@
"source": [
"### Setup\n",
"\n",
- "To run Typesense locally, you'll need [Docker](https://www.docker.com/). Following the instructions contained in the Typesense documentation [here](https://typesense.org/docs/guide/install-typesense.html#docker-compose), we created an example docker-compose.yml file in this repo saved at [./typesense/docker-compose.yml](./typesense/docker-compose.yml).\n",
+ "To run Typesense locally, you'll need [Docker](https://www.docker.com/). Following the instructions contained in the Typesense documentation [here](https://typesense.org/docs/guide/install-typesense.html#docker-compose), we created an example docker-compose.yml file in this repo saved at [`docker-compose.yml`](./docker-compose.yml).\n",
"\n",
"After starting Docker, you can start Typesense locally by navigating to the `examples/vector_databases/typesense/` directory and running `docker-compose up -d`.\n",
"\n",
diff --git a/examples/vector_databases/weaviate/Using_Weaviate_for_embeddings_search.ipynb b/examples/vector_databases/weaviate/Using_Weaviate_for_embeddings_search.ipynb
index 035db590..88ec1809 100644
--- a/examples/vector_databases/weaviate/Using_Weaviate_for_embeddings_search.ipynb
+++ b/examples/vector_databases/weaviate/Using_Weaviate_for_embeddings_search.ipynb
@@ -331,7 +331,7 @@
"* for any CRUD operations\n",
"* for semantic search\n",
"\n",
- "Check out the [Getting Started with Weaviate and OpenAI module cookbook](./weaviate/getting-started-with-weaviate-and-openai.ipynb) to learn step by step how to import and vectorize data in one step."
+ "Check out the [Getting Started with Weaviate and OpenAI module cookbook](./getting-started-with-weaviate-and-openai.ipynb) to learn step by step how to import and vectorize data in one step."
]
},
{
@@ -341,7 +341,7 @@
"source": [
"### Setup\n",
"\n",
- "To run Weaviate locally, you'll need [Docker](https://www.docker.com/). Following the instructions contained in the Weaviate documentation [here](https://weaviate.io/developers/weaviate/installation/docker-compose), we created an example docker-compose.yml file in this repo saved at [./weaviate/docker-compose.yml](./weaviate/docker-compose.yml).\n",
+ "To run Weaviate locally, you'll need [Docker](https://www.docker.com/). Following the instructions contained in the Weaviate documentation [here](https://weaviate.io/developers/weaviate/installation/docker-compose), we created an example docker-compose.yml file in this repo saved at [`docker-compose.yml`](./docker-compose.yml).\n",
"\n",
"After starting Docker, you can start Weaviate locally by navigating to the `examples/vector_databases/weaviate/` directory and running `docker-compose up -d`.\n",
"\n",
diff --git a/examples/vector_databases/weaviate/generative-search-with-weaviate-and-openai.ipynb b/examples/vector_databases/weaviate/generative-search-with-weaviate-and-openai.ipynb
index 1c7d7fb8..7865e358 100644
--- a/examples/vector_databases/weaviate/generative-search-with-weaviate-and-openai.ipynb
+++ b/examples/vector_databases/weaviate/generative-search-with-weaviate-and-openai.ipynb
@@ -22,13 +22,13 @@
"source": [
"## Prerequisites\n",
"\n",
- "This cookbook only coveres Generative Search examples, however, it doesn't cover the configuration and data imports.\n",
+ "This cookbook covers only Generative Search examples; it doesn't cover the configuration and data imports.\n",
"\n",
"In order to make the most of this cookbook, please complete the [Getting Started cookbook](./getting-started-with-weaviate-and-openai.ipynb) first, where you will learn the essentials of working with Weaviate and import the demo data.\n",
"\n",
"Checklist:\n",
"* completed [Getting Started cookbook](./getting-started-with-weaviate-and-openai.ipynb),\n",
- "* crated a `Weaviate` instance,\n",
+ "* created a `Weaviate` instance,\n",
"* imported data into your `Weaviate` instance,\n",
"* you have an [OpenAI API key](https://beta.openai.com/account/api-keys)"
]
diff --git a/examples/vector_databases/weaviate/getting-started-with-weaviate-and-openai.ipynb b/examples/vector_databases/weaviate/getting-started-with-weaviate-and-openai.ipynb
index d58c528c..13c817cd 100644
--- a/examples/vector_databases/weaviate/getting-started-with-weaviate-and-openai.ipynb
+++ b/examples/vector_databases/weaviate/getting-started-with-weaviate-and-openai.ipynb
@@ -264,7 +264,7 @@
"2. select OpenAI module\n",
"\n",
"> This is the second and final step, which requires OpenAI specific configuration.\n",
- "> After this step, the rest of instructions wlll only touch on Weaviate, as the OpenAI tasks will be handled automatically.\n",
+ "> After this step, the rest of the instructions will only touch on Weaviate, as the OpenAI tasks will be handled automatically.\n",
"\n",
"\n",
"## What is a schema\n",
diff --git a/examples/vector_databases/weaviate/hybrid-search-with-weaviate-and-openai.ipynb b/examples/vector_databases/weaviate/hybrid-search-with-weaviate-and-openai.ipynb
index 3ab0965d..10942b46 100644
--- a/examples/vector_databases/weaviate/hybrid-search-with-weaviate-and-openai.ipynb
+++ b/examples/vector_databases/weaviate/hybrid-search-with-weaviate-and-openai.ipynb
@@ -264,7 +264,7 @@
"2. select OpenAI module\n",
"\n",
"> This is the second and final step, which requires OpenAI specific configuration.\n",
- "> After this step, the rest of instructions wlll only touch on Weaviate, as the OpenAI tasks will be handled automatically.\n",
+ "> After this step, the rest of the instructions will only touch on Weaviate, as the OpenAI tasks will be handled automatically.\n",
"\n",
"\n",
"## What is a schema\n",
diff --git a/examples/vector_databases/weaviate/question-answering-with-weaviate-and-openai.ipynb b/examples/vector_databases/weaviate/question-answering-with-weaviate-and-openai.ipynb
index 1c6f2b0a..027ceab4 100644
--- a/examples/vector_databases/weaviate/question-answering-with-weaviate-and-openai.ipynb
+++ b/examples/vector_databases/weaviate/question-answering-with-weaviate-and-openai.ipynb
@@ -263,7 +263,7 @@
"2. select OpenAI module\n",
"\n",
"> This is the second and final step, which requires OpenAI specific configuration.\n",
- "> After this step, the rest of instructions wlll only touch on Weaviate, as the OpenAI tasks will be handled automatically.\n",
+ "> After this step, the rest of the instructions will only touch on Weaviate, as the OpenAI tasks will be handled automatically.\n",
"\n",
"\n",
"## What is a schema\n",
diff --git a/examples/vector_databases/zilliz/Filtered_search_with_Zilliz_and_OpenAI.ipynb b/examples/vector_databases/zilliz/Filtered_search_with_Zilliz_and_OpenAI.ipynb
index 32f59be1..395614d3 100644
--- a/examples/vector_databases/zilliz/Filtered_search_with_Zilliz_and_OpenAI.ipynb
+++ b/examples/vector_databases/zilliz/Filtered_search_with_Zilliz_and_OpenAI.ipynb
@@ -187,7 +187,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "This next step does the actual inserting. We iterate through all the entries and create batches that we insert once we hit our set batch size. After the loop is over we insert the last remaning batch if it exists. "
+ "This next step does the actual inserting. We iterate through all the entries and create batches that we insert once we hit our set batch size. After the loop is over we insert the last remaining batch if it exists. "
]
},
{
diff --git a/examples/voice_solutions/voice_translation_into_different_languages_using_GPT-4o.ipynb b/examples/voice_solutions/voice_translation_into_different_languages_using_GPT-4o.ipynb
index 4c375f53..7062bd43 100644
--- a/examples/voice_solutions/voice_translation_into_different_languages_using_GPT-4o.ipynb
+++ b/examples/voice_solutions/voice_translation_into_different_languages_using_GPT-4o.ipynb
@@ -24,7 +24,7 @@
"\n",
"**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. \n",
" \n",
- "**2. Dub** the audio file from source language directly to the target langauge. \n",
+ "**2. Dub** the audio file from source language directly to the target language. \n",
" \n",
"**3. Obtain Translation Benchmarks** using BLEU or ROUGE. \n",
" \n",