Skip to content

Commit d68a124

Browse files
committed
updated image understanding vector stores
1 parent 26b16ae commit d68a124

File tree

1 file changed

+65
-70
lines changed

1 file changed

+65
-70
lines changed

examples/multimodal/image_understanding_with_rag.ipynb

Lines changed: 65 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,11 @@
66
"source": [
77
"# Image Understanding with RAG using OpenAI's Vision & Responses APIs\n",
88
"\n",
9-
"Welcome! This cookbook guides you through working with multimodal data, using OpenAI's Vision & Responses APIs, with image understanding and file search capabilities. It demonstrates how to build a RAG system, powered by GPT 4.1, that can analyse customer experiences, from their feedback which can be both visual and text-based.\n",
9+
"Welcome! This notebook demonstrates how to build a Retrieval-Augmented Generation (RAG) system using OpenAIs Vision and Responses APIs. It focuses on multimodal data, specifically, combining image and text inputs to analyze customer experiences. The system leverages GPT-4.1 and integrates image understanding with file search to provide context-aware responses.\n",
1010
"\n",
11-
"Many datasets are multimodal, often containing both text and image data. A good example of this is in radiology in healthcare, where patient records contain both image scan and written report. In addition, many real-world datasets are noisy and contain missing or incomplete data meaning valuable information can be missed with analysing multiple modalities.\n",
11+
"Multimodal datasets are increasingly common, particularly in domains like healthcare, where records often contain both visual data (e.g. radiology scans) and accompanying text (e.g. clinical notes). Real-world datasets also tend to be noisy, with incomplete or missing information, making it critical to analyze multiple modalities in tandem.\n",
1212
"\n",
13-
"This guide covers a common use case in customer service, which is analysing the experience of customers. This guide will cover synthetic generation for text and image modalities, combining image analysis with file search for more robust, context-aware answers from a RAG system and it also leverages the Evals API to evaluate the performance gain of including image understanding in the RAG system.\n",
13+
"This guide focuses on a customer service use case: evaluating customer feedback that may include screenshots, photos, and written complaints. You’ll learn how to synthetically generate both image and text inputs, use file search for context retrieval, and apply the Evals API to assess how incorporating image understanding impacts overall performance.\n",
1414
"\n",
1515
"---\n",
1616
"\n",
@@ -49,7 +49,7 @@
4949
"metadata": {},
5050
"outputs": [],
5151
"source": [
52-
"%pip install openai evals pandas matplotlib tqdm ipython --upgrade --quiet"
52+
"%pip install openai evals pandas numpy matplotlib tqdm ipython --upgrade --quiet"
5353
]
5454
},
5555
{
@@ -60,9 +60,11 @@
6060
"source": [
6161
"import base64\n",
6262
"from io import BytesIO\n",
63+
"import os\n",
6364
"from pathlib import Path\n",
6465
"\n",
6566
"import matplotlib.pyplot as plt\n",
67+
"import numpy as np\n",
6668
"import pandas as pd\n",
6769
"from openai import OpenAI\n",
6870
"from IPython.display import display, Image\n",
@@ -80,7 +82,7 @@
8082
"source": [
8183
"## Example Generations\n",
8284
"\n",
83-
"Given how expensive it can be generate high-quality training and evaluation data for machine learning tasks, utilising synthetic data can be an effective alternative. The OpenAI Image API can be used to generate synthetic images for this purpose and this cookbook uses the Responses API to generate synthetic text data."
85+
"Generating high-quality training and evaluation data for machine learning tasks can be costly and time-consuming. Synthetic data offers a practical and scalable alternative. In this notebook, the OpenAI Image API is used to generate synthetic images, while the Responses API is employed to create synthetic text, enabling efficient prototyping and experimentation across multimodal tasks."
8486
]
8587
},
8688
{
@@ -147,7 +149,7 @@
147149
"source": [
148150
"## Data Processing\n",
149151
"\n",
150-
"In this instance, we will use a pre-generated synthetic dataset of customer feedback, which includes both short text snippets and images from customer reviews, sometimes combined. You can also generate your own synthetic dataset for this cookbook using the above examples."
152+
"In this example, we’ll work with a pre-generated synthetic dataset of customer feedback that includes short text snippets, images from customer reviews, and occasionally combined multimodal entries. You can also generate your own synthetic dataset using the examples provided above to tailor the data to your specific use case."
151153
]
152154
},
153155
{
@@ -249,7 +251,7 @@
249251
"cell_type": "markdown",
250252
"metadata": {},
251253
"source": [
252-
"This example uses OpenAI's built-in vector store and file search capabilities to build a RAG system that can analyse customer experiences, from their feedback which can be both visual and text-based."
254+
"This example uses OpenAI's built-in vector store and file search capabilities to build a RAG system that can analyse customer experiences, from their feedback which can be both visual and text-based. We create two vector stores for comparisons, one with image understanding and one without."
253255
]
254256
},
255257
{
@@ -291,10 +293,13 @@
291293
"source": [
292294
"# upload files to vector database and set metadata\n",
293295
"\n",
294-
"def upload_files_to_vector_store(vector_store_id, df):\n",
296+
"def upload_files_to_vector_store(vector_store_id, df, column_name=\"full_sentiment\"):\n",
295297
" file_ids = []\n",
296298
" for i, row in tqdm(df.iterrows(), total=len(df), desc=\"Uploading context files\"):\n",
297-
" file_stream = BytesIO(row[\"full_sentiment\"].encode('utf-8'))\n",
299+
" if pd.isna(row[column_name]):\n",
300+
" file_stream = BytesIO('No information available.'.encode('utf-8'))\n",
301+
" else:\n",
302+
" file_stream = BytesIO(row[column_name].encode('utf-8'))\n",
298303
" file_stream.name = f\"context_{row.get('id', i)}_{row.get('month', '')}.txt\"\n",
299304
" \n",
300305
" file = client.vector_stores.files.upload(\n",
@@ -308,9 +313,7 @@
308313
" vector_store_id=vector_store_id,\n",
309314
" file_id=file_ids[i],\n",
310315
" attributes={\"month\": row[\"month\"]}\n",
311-
" )\n",
312-
" import time\n",
313-
" time.sleep(1) # TODO"
316+
" )"
314317
]
315318
},
316319
{
@@ -319,8 +322,17 @@
319322
"metadata": {},
320323
"outputs": [],
321324
"source": [
322-
"upload_files_to_vector_store(text_image_vector_store_id, df)\n",
323-
"upload_files_to_vector_store(text_image_vector_store_id, df) "
325+
"upload_files_to_vector_store(text_image_vector_store_id, df)"
326+
]
327+
},
328+
{
329+
"cell_type": "code",
330+
"execution_count": null,
331+
"metadata": {},
332+
"outputs": [],
333+
"source": [
334+
"\n",
335+
"upload_files_to_vector_store(text_vector_store_id, df, column_name=\"text\") "
324336
]
325337
},
326338
{
@@ -332,14 +344,21 @@
332344
"We can analyse our dataset with natural language queries with the help of File Search. For the text-only dataset, we see that information is missing that could inform our analysis.\n"
333345
]
334346
},
347+
{
348+
"cell_type": "markdown",
349+
"metadata": {},
350+
"source": [
351+
"The only positive review for spaghetti in July has visual feedback and we can see the RAG system with only text based context available is uncertain about positive details. However with image context provided the second RAG system is able to provide a more accurate response."
352+
]
353+
},
335354
{
336355
"cell_type": "code",
337356
"execution_count": null,
338357
"metadata": {},
339358
"outputs": [],
340359
"source": [
341360
"# Query the vector store for spaghetti reviews in July\n",
342-
"query = \"What were the reviews like for the spaghetti?\"\n",
361+
"query = \"What were the reviews like for the spaghetti presentation?\"\n",
343362
"print(f\"🔍 Query: {query}\\n\")\n",
344363
"\n",
345364
"# Execute the search with filtering\n",
@@ -369,7 +388,7 @@
369388
"metadata": {},
370389
"outputs": [],
371390
"source": [
372-
"query = \"What were the reviews like for the spaghetti?\"\n",
391+
"query = \"What were the reviews like for the spaghetti presentation?\"\n",
373392
"print(f\"🔍 Query: {query}\\n\")\n",
374393
"\n",
375394
"response = client.responses.create(\n",
@@ -410,9 +429,9 @@
410429
"}\n",
411430
"\n",
412431
"def display_retrieved_images(\n",
413-
" response: Any,\n",
432+
" response,\n",
414433
" cache_dir: str = \".local_cache\"\n",
415-
") -> Dict[str, str]:\n",
434+
"):\n",
416435
" \"\"\"\n",
417436
" Display images from the retrieved search results.\n",
418437
" \n",
@@ -447,6 +466,13 @@
447466
"print(f\"Displayed {len(displayed)} images\")"
448467
]
449468
},
469+
{
470+
"cell_type": "markdown",
471+
"metadata": {},
472+
"source": [
473+
"Likewise we can test this for negative reviews in June."
474+
]
475+
},
450476
{
451477
"cell_type": "code",
452478
"execution_count": null,
@@ -518,46 +544,6 @@
518544
" for _, row in df.iterrows()]\n",
519545
"\n",
520546
"\n",
521-
"# def create_eval_run(evaluation_data):\n",
522-
"# eval_config = {\n",
523-
"# \"type\": \"completions\",\n",
524-
"# \"model\": \"gpt-4.1\",\n",
525-
"# \"input_messages\": {\n",
526-
"# \"type\": \"template\",\n",
527-
"# \"template\": [\n",
528-
"# {\n",
529-
"# \"type\": \"message\",\n",
530-
"# \"role\": \"user\",\n",
531-
"# \"content\": {\n",
532-
"# \"type\": \"input_text\",\n",
533-
"# \"text\": \"Classify the sentiment of this food delivery review: {{ item.input }}. Categorize the request into one of \\\"positive\\\", \\\"negative\\\" or \\\"unclear\\\". Respond with only one of those words.\"\n",
534-
"# }\n",
535-
"# }\n",
536-
"# ]\n",
537-
"# },\n",
538-
"# \"source\": {\n",
539-
"# \"type\": \"file_content\",\n",
540-
"# \"content\": evaluation_data\n",
541-
"# }\n",
542-
"# }\n",
543-
"\n",
544-
"# # Create and monitor evaluation run\n",
545-
"# run = client.evals.runs.create(\n",
546-
"# eval_id=eval_obj.id,\n",
547-
"# data_source=eval_config\n",
548-
"# )\n",
549-
"\n",
550-
"# print(\"✅ Evaluation run created successfully\")\n",
551-
"# print(f\"Run ID: {run.id}\")\n",
552-
"# return run.id"
553-
]
554-
},
555-
{
556-
"cell_type": "code",
557-
"execution_count": null,
558-
"metadata": {},
559-
"outputs": [],
560-
"source": [
561547
"def prepare_evaluation_data(\n",
562548
" df: pd.DataFrame,\n",
563549
" text_col: str = \"full_sentiment\",\n",
@@ -687,22 +673,16 @@
687673
"execution_count": null,
688674
"metadata": {},
689675
"outputs": [],
690-
"source": []
691-
},
692-
{
693-
"cell_type": "markdown",
694-
"metadata": {},
695676
"source": [
696-
"We can retrieve the results of these evaluation runs and perform some local analysis. In this case, we will compare the performance of the text-only and text+image runs and evaluate how increasing the number of total tokens (through the addition of image context) affects the accuracy of the model. We can also do some basic error analysis by analysing the model input of the failed examples."
677+
"text_only_run_output_items = client.evals.runs.output_items.list(eval_id=eval_id, run_id=text_only_run_id)\n",
678+
"text_image_run_output_items = client.evals.runs.output_items.list(eval_id=eval_id, run_id=text_image_run_id)"
697679
]
698680
},
699681
{
700-
"cell_type": "code",
701-
"execution_count": null,
682+
"cell_type": "markdown",
702683
"metadata": {},
703-
"outputs": [],
704684
"source": [
705-
"text_only_run_output_items = client.runs.output_items(text_only_run)"
685+
"We can retrieve the results of these evaluation runs and perform some local analysis. In this case, we will compare the performance of the text-only and text+image runs and evaluate how increasing the number of total tokens (through the addition of image context) affects the accuracy of the model. We can also do some basic error analysis by analysing the model input of the failed examples."
706686
]
707687
},
708688
{
@@ -790,9 +770,24 @@
790770
"metadata": {},
791771
"outputs": [],
792772
"source": [
793-
"# delete vector store\n",
794-
"client.vector_stores.delete(vector_store)"
773+
"# delete vector stores\n",
774+
"deleted_vector_store = client.vector_stores.delete(\n",
775+
" vector_store_id=text_vector_store_id\n",
776+
")\n",
777+
"print(deleted_vector_store)\n",
778+
"\n",
779+
"deleted_vector_store = client.vector_stores.delete(\n",
780+
" vector_store_id=text_image_vector_store_id\n",
781+
")\n",
782+
"print(deleted_vector_store)"
795783
]
784+
},
785+
{
786+
"cell_type": "code",
787+
"execution_count": null,
788+
"metadata": {},
789+
"outputs": [],
790+
"source": []
796791
}
797792
],
798793
"metadata": {

0 commit comments

Comments
 (0)