# embedding_metadata

key: _node_content
string_value:
{"id_": "482bd064-745a-46eb-b366-72db3b5a3af5", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Clustering_for_transaction_classification.ipynb", "title": "Clustering for Transaction Classification", "tokens": 2826, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "57301cf1-0f1f-4264-8320-817054358a70", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Clustering_for_transaction_classification.ipynb", "title": "Clustering for Transaction Classification", "tokens": 2826, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "37265102bc4e08e16fac5f2ad8c4e8b28f45454e68085fd2f04969754e61d36a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c236c99f-302f-42d6-b274-719030154628", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Clustering_for_transaction_classification.ipynb", "title": "Clustering for Transaction Classification", "tokens": 2826, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "3d6b437d71a0d9faa15860637e70902bc49ed076cdcc030ef27c700c5a09b3a4", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 8669, "end_char_idx": 11677, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
CBRE, Kelvin Hall
    GLASGOW CITY COUNCIL, Kelvin Hall
    University Of Glasgow, Kelvin Hall
    GLASGOW LIFE, Oct 20 to Dec 20 service charge - Kelvin Hall
    Computacenter Uk, Kelvin Hall
    XMA Scotland Ltd, Kelvin Hall
    GLASGOW LIFE, Service Charges Kelvin Hall 01/07/19-30/09/19
    Glasgow Life, Kelvin Hall Service Charges
    Glasgow City Council, Kelvin Hall
    GLASGOW LIFE, Quarterly service charge KH
    ----------------------------------------------------------------------------------------------------
    
    
    Cluster 3 Theme:
    
    The common theme among these transactions is that they all involve payments for facility management fees and services provided by ECG Facilities Service.
    
    
    ECG FACILITIES SERVICE, This payment covers multiple invoices for facility management fees
    ECG FACILITIES SERVICE, Facilities Management Charge
    ECG FACILITIES SERVICE, Inspection and Maintenance of all Library properties
    ECG Facilities Service, Facilities Management Charge
    ECG FACILITIES SERVICE, Maintenance contract - October
    ECG FACILITIES SERVICE, Electrical and mechanical works
    ECG FACILITIES SERVICE, This payment covers multiple invoices for facility management fees
    ECG FACILITIES SERVICE, CB Bolier Replacement (1),USP Batteries,Gutter Works & Cleaning of pigeon fouling
    ECG Facilities Service, Facilities Management Charge
    ECG Facilities Service, Facilities Management Charge
    ----------------------------------------------------------------------------------------------------
    
    
    Cluster 4 Theme:
    
    The common theme among these transactions is that they all involve construction or refurbishment work.
    
    
    M & J Ballantyne Ltd, George IV Bridge Work
    John Graham Construction Ltd, Causewayside Refurbishment
    John Graham Construction Ltd, Causewayside Refurbishment
    John Graham Construction Ltd, Causewayside Refurbishment
    John Graham Construction Ltd, Causewayside Refurbishment
    ARTHUR MCKAY BUILDING SERVICES, Causewayside Work
    John Graham Construction Ltd, Causewayside Refurbishment
    Morris & Spottiswood Ltd, George IV Bridge Work
    ECG FACILITIES SERVICE, Causewayside IT Work
    John Graham Construction Ltd, Causewayside Refurbishment
    ----------------------------------------------------------------------------------------------------
    
    


### Conclusion

We now have five new clusters that we can use to describe our data. Looking at the visualisation some of our clusters have some overlap and we'll need some tuning to get to the right place, but already we can see that GPT-3 has made some effective inferences. In particular, it picked up that items including legal deposits were related to literature archival, which is true but the model was given no clues on. Very cool, and with some tuning we can create a base set of clusters that we can then use with a multiclass classifier to generalise to other transactional datasets we might use.


key: _node_content
string_value:
{"id_": "86979331-1e8d-4c1c-a744-ba4a4c808e1e", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb", "title": "Recommendation using embeddings and nearest neighbor search", "tokens": 4069, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "a11a29ec-ba8e-4016-8225-e739c1266d56", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb", "title": "Recommendation using embeddings and nearest neighbor search", "tokens": 4069, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "55cd2bb30475cecec36500acb7c07fdb436389573ee4b15ac4410bf4ec6f69a0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "25cec6e4-dd63-4e41-ae57-140597879086", "node_type": "1", "metadata": {}, "hash": "340eeb21c91464462dbc4b0af53a55f87d868bb8c1ee4aef6583d55ea0d5ca8c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2695, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Recommendation using embeddings and nearest neighbor search

Recommendations are widespread across the web.

- 'Bought that item? Try these similar items.'
- 'Enjoy that book? Try these similar titles.'
- 'Not the help page you were looking for? Try these similar pages.'

This notebook demonstrates how to use embeddings to find similar items to recommend. In particular, we use [AG's corpus of news articles](http://groups.di.unipi.it/~gulli/AG_corpus_of_news_articles.html) as our dataset.

Our model will answer the question: given an article, what other articles are most similar to it?


```python
import pandas as pd
import pickle

from utils.embeddings_utils import (
    get_embedding,
    distances_from_embeddings,
    tsne_components_from_embeddings,
    chart_from_components,
    indices_of_nearest_neighbors_from_distances,
)

EMBEDDING_MODEL = "text-embedding-3-small"

```

### 2. Load data

Next, let's load the AG news data and see what it looks like.


```python
# load data (full dataset available at http://groups.di.unipi.it/~gulli/AG_corpus_of_news_articles.html)
dataset_path = "data/AG_news_samples.csv"
df = pd.read_csv(dataset_path)

n_examples = 5
df.head(n_examples)

```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>title</th>
      <th>description</th>
      <th>label_int</th>
      <th>label</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>World Briefings</td>
      <td>BRITAIN: BLAIR WARNS OF CLIMATE THREAT Prime M...</td>
      <td>1</td>
      <td>World</td>
    </tr>
    <tr>
      <th>1</th>
      <td>Nvidia Puts a Firewall on a Motherboard (PC Wo...</td>
      <td>PC World - Upcoming chip set will include buil...</td>
      <td>4</td>
      <td>Sci/Tech</td>
    </tr>
    <tr>
      <th>2</th>
      <td>Olympic joy in Greek, Chinese press</td>
      <td>Newspapers in Greece reflect a mixture of exhi...</td>
      <td>2</td>
      <td>Sports</td>
    </tr>
    <tr>
      <th>3</th>
      <td>U2 Can iPod with Pictures</td>
      <td>SAN JOSE, Calif. -- Apple Computer (Quote, Cha...</td>
      <td>4</td>
      <td>Sci/Tech</td>
    </tr>
    <tr>
      <th>4</th>
      <td>The Dream Factory</td>
      <td>Any product, any shape, any size -- manufactur...</td>
      <td>4</td>
      <td>Sci/Tech</td>
    </tr>
  </tbody>
</table>
</div>



Let's take a look at those same examples, but not truncated by ellipses.


key: _node_content
string_value:
{"id_": "25cec6e4-dd63-4e41-ae57-140597879086", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb", "title": "Recommendation using embeddings and nearest neighbor search", "tokens": 4069, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "a11a29ec-ba8e-4016-8225-e739c1266d56", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb", "title": "Recommendation using embeddings and nearest neighbor search", "tokens": 4069, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "55cd2bb30475cecec36500acb7c07fdb436389573ee4b15ac4410bf4ec6f69a0", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "86979331-1e8d-4c1c-a744-ba4a4c808e1e", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb", "title": "Recommendation using embeddings and nearest neighbor search", "tokens": 4069, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "e0d621eed6a9a90d58a90ad6c4d0364c5c6e968fc46abe2d22898b1bcdad2f27", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "74772d3e-ba9b-4c19-b26b-7430d8c2262c", "node_type": "1", "metadata": {}, "hash": "6ea2f9d939c91815b63a9b33bf1dba8402a997e600ee341e878bf185e57138ac", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2623, "end_char_idx": 5791, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Let's take a look at those same examples, but not truncated by ellipses.


```python
# print the title, description, and label of each example
for idx, row in df.head(n_examples).iterrows():
    print("")
    print(f"Title: {row['title']}")
    print(f"Description: {row['description']}")
    print(f"Label: {row['label']}")

```

    
    Title: World Briefings
    Description: BRITAIN: BLAIR WARNS OF CLIMATE THREAT Prime Minister Tony Blair urged the international community to consider global warming a dire threat and agree on a plan of action to curb the  quot;alarming quot; growth of greenhouse gases.
    Label: World
    
    Title: Nvidia Puts a Firewall on a Motherboard (PC World)
    Description: PC World - Upcoming chip set will include built-in security features for your PC.
    Label: Sci/Tech
    
    Title: Olympic joy in Greek, Chinese press
    Description: Newspapers in Greece reflect a mixture of exhilaration that the Athens Olympics proved successful, and relief that they passed off without any major setback.
    Label: Sports
    
    Title: U2 Can iPod with Pictures
    Description: SAN JOSE, Calif. -- Apple Computer (Quote, Chart) unveiled a batch of new iPods, iTunes software and promos designed to keep it atop the heap of digital music players.
    Label: Sci/Tech
    
    Title: The Dream Factory
    Description: Any product, any shape, any size -- manufactured on your desktop! The future is the fabricator. By Bruce Sterling from Wired magazine.
    Label: Sci/Tech


### 3. Build cache to save embeddings

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.

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.


```python
# establish a cache of embeddings to avoid recomputing
# cache is a dict of tuples (text, model) -> embedding, saved as a pickle file

# set path to embedding cache
embedding_cache_path = "data/recommendations_embeddings_cache.pkl"

# load the cache if it exists, and save a copy to disk
try:
    embedding_cache = pd.read_pickle(embedding_cache_path)
except FileNotFoundError:
    embedding_cache = {}
with open(embedding_cache_path, "wb") as embedding_cache_file:
    pickle.dump(embedding_cache, embedding_cache_file)

# define a function to retrieve embeddings from the cache if present, and otherwise request via the API
def embedding_from_string(
    string: str,
    model: str = EMBEDDING_MODEL,
    embedding_cache=embedding_cache
) -> list:
    """Return embedding of given string, using a cache to avoid recomputing."""
    if (string, model) not in embedding_cache.keys():
        embedding_cache[(string, model)] = get_embedding(string, model)
        with open(embedding_cache_path, "wb") as embedding_cache_file:
            pickle.dump(embedding_cache, embedding_cache_file)
    return embedding_cache[(string, model)]

```

Let's check that it works by getting an embedding.


key: _node_content
string_value:
{"id_": "74772d3e-ba9b-4c19-b26b-7430d8c2262c", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb", "title": "Recommendation using embeddings and nearest neighbor search", "tokens": 4069, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "a11a29ec-ba8e-4016-8225-e739c1266d56", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb", "title": "Recommendation using embeddings and nearest neighbor search", "tokens": 4069, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "55cd2bb30475cecec36500acb7c07fdb436389573ee4b15ac4410bf4ec6f69a0", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "25cec6e4-dd63-4e41-ae57-140597879086", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb", "title": "Recommendation using embeddings and nearest neighbor search", "tokens": 4069, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "6cbd5f38c594f914bb3ad2daea87e6c830cb6bd84dd62098e57ccdae8500f8b2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "163fdcb3-4044-4c21-83ee-971481bea36a", "node_type": "1", "metadata": {}, "hash": "93dfaa3c5a302ed6f671e5546ff8e8393aa89676e248cb987df32676cc38c5b3", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 4137, "end_char_idx": 6944, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
### 3. Build cache to save embeddings

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.

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.


```python
# establish a cache of embeddings to avoid recomputing
# cache is a dict of tuples (text, model) -> embedding, saved as a pickle file

# set path to embedding cache
embedding_cache_path = "data/recommendations_embeddings_cache.pkl"

# load the cache if it exists, and save a copy to disk
try:
    embedding_cache = pd.read_pickle(embedding_cache_path)
except FileNotFoundError:
    embedding_cache = {}
with open(embedding_cache_path, "wb") as embedding_cache_file:
    pickle.dump(embedding_cache, embedding_cache_file)

# define a function to retrieve embeddings from the cache if present, and otherwise request via the API
def embedding_from_string(
    string: str,
    model: str = EMBEDDING_MODEL,
    embedding_cache=embedding_cache
) -> list:
    """Return embedding of given string, using a cache to avoid recomputing."""
    if (string, model) not in embedding_cache.keys():
        embedding_cache[(string, model)] = get_embedding(string, model)
        with open(embedding_cache_path, "wb") as embedding_cache_file:
            pickle.dump(embedding_cache, embedding_cache_file)
    return embedding_cache[(string, model)]

```

Let's check that it works by getting an embedding.


```python
# as an example, take the first description from the dataset
example_string = df["description"].values[0]
print(f"\nExample string: {example_string}")

# print the first 10 dimensions of the embedding
example_embedding = embedding_from_string(example_string)
print(f"\nExample embedding: {example_embedding[:10]}...")

```

    
    Example string: BRITAIN: BLAIR WARNS OF CLIMATE THREAT Prime Minister Tony Blair urged the international community to consider global warming a dire threat and agree on a plan of action to curb the  quot;alarming quot; growth of greenhouse gases.
    
    Example embedding: [0.0545826330780983, -0.00428084097802639, 0.04785159230232239, 0.01587914116680622, -0.03640881925821304, 0.0143799539655447, -0.014267769642174244, -0.015175441280007362, -0.002344391541555524, 0.011075624264776707]...


### 4. Recommend similar articles based on embeddings

To find similar articles, let's follow a three-step plan:
1. Get the similarity embeddings of all the article descriptions
2. Calculate the distance between a source title and all other articles
3. Print out the other articles closest to the source title


key: _node_content
string_value:
{"id_": "163fdcb3-4044-4c21-83ee-971481bea36a", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb", "title": "Recommendation using embeddings and nearest neighbor search", "tokens": 4069, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "a11a29ec-ba8e-4016-8225-e739c1266d56", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb", "title": "Recommendation using embeddings and nearest neighbor search", "tokens": 4069, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "55cd2bb30475cecec36500acb7c07fdb436389573ee4b15ac4410bf4ec6f69a0", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "74772d3e-ba9b-4c19-b26b-7430d8c2262c", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb", "title": "Recommendation using embeddings and nearest neighbor search", "tokens": 4069, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "bb4cebbb8595c5de31746231c14307438781f4a35d79bf5356eb9e5e1afe4921", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c6ae37d9-2187-4ac7-9d22-d14d887ef6d0", "node_type": "1", "metadata": {}, "hash": "adebd0568b91744deecc87cc7950398249040d26763055da6d404041665d5248", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5794, "end_char_idx": 8730, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
# as an example, take the first description from the dataset
example_string = df["description"].values[0]
print(f"\nExample string: {example_string}")

# print the first 10 dimensions of the embedding
example_embedding = embedding_from_string(example_string)
print(f"\nExample embedding: {example_embedding[:10]}...")

```

    
    Example string: BRITAIN: BLAIR WARNS OF CLIMATE THREAT Prime Minister Tony Blair urged the international community to consider global warming a dire threat and agree on a plan of action to curb the  quot;alarming quot; growth of greenhouse gases.
    
    Example embedding: [0.0545826330780983, -0.00428084097802639, 0.04785159230232239, 0.01587914116680622, -0.03640881925821304, 0.0143799539655447, -0.014267769642174244, -0.015175441280007362, -0.002344391541555524, 0.011075624264776707]...


### 4. Recommend similar articles based on embeddings

To find similar articles, let's follow a three-step plan:
1. Get the similarity embeddings of all the article descriptions
2. Calculate the distance between a source title and all other articles
3. Print out the other articles closest to the source title


```python
def print_recommendations_from_strings(
    strings: list[str],
    index_of_source_string: int,
    k_nearest_neighbors: int = 1,
    model=EMBEDDING_MODEL,
) -> list[int]:
    """Print out the k nearest neighbors of a given string."""
    # get embeddings for all strings
    embeddings = [embedding_from_string(string, model=model) for string in strings]

    # get the embedding of the source string
    query_embedding = embeddings[index_of_source_string]

    # get distances between the source embedding and other embeddings (function from utils.embeddings_utils.py)
    distances = distances_from_embeddings(query_embedding, embeddings, distance_metric="cosine")
    
    # get indices of nearest neighbors (function from utils.utils.embeddings_utils.py)
    indices_of_nearest_neighbors = indices_of_nearest_neighbors_from_distances(distances)

    # print out source string
    query_string = strings[index_of_source_string]
    print(f"Source string: {query_string}")
    # print out its k nearest neighbors
    k_counter = 0
    for i in indices_of_nearest_neighbors:
        # skip any strings that are identical matches to the starting string
        if query_string == strings[i]:
            continue
        # stop after printing out k articles
        if k_counter >= k_nearest_neighbors:
            break
        k_counter += 1

        # print out the similar strings and their distances
        print(
            f"""
        --- Recommendation #{k_counter} (nearest neighbor {k_counter} of {k_nearest_neighbors}) ---
        String: {strings[i]}
        Distance: {distances[i]:0.3f}"""
        )

    return indices_of_nearest_neighbors

```

### 5. Example recommendations

Let's look for articles similar to first one, which was about Tony Blair.


key: _node_content
string_value:
{"id_": "c6ae37d9-2187-4ac7-9d22-d14d887ef6d0", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb", "title": "Recommendation using embeddings and nearest neighbor search", "tokens": 4069, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "a11a29ec-ba8e-4016-8225-e739c1266d56", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb", "title": "Recommendation using embeddings and nearest neighbor search", "tokens": 4069, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "55cd2bb30475cecec36500acb7c07fdb436389573ee4b15ac4410bf4ec6f69a0", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "163fdcb3-4044-4c21-83ee-971481bea36a", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb", "title": "Recommendation using embeddings and nearest neighbor search", "tokens": 4069, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "23e9ea2ff0840965017dbf1ff5e7e7eabc54e8dfe5db27c7e94caaabc39bc248", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9cee76dd-99d8-4dc5-b7ee-3f8e2d819276", "node_type": "1", "metadata": {}, "hash": "dc83a0888dce9918dfd7a98133cc7c8577e1c489b8156b831a841579c2a7bb55", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 6947, "end_char_idx": 10753, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
def print_recommendations_from_strings(
    strings: list[str],
    index_of_source_string: int,
    k_nearest_neighbors: int = 1,
    model=EMBEDDING_MODEL,
) -> list[int]:
    """Print out the k nearest neighbors of a given string."""
    # get embeddings for all strings
    embeddings = [embedding_from_string(string, model=model) for string in strings]

    # get the embedding of the source string
    query_embedding = embeddings[index_of_source_string]

    # get distances between the source embedding and other embeddings (function from utils.embeddings_utils.py)
    distances = distances_from_embeddings(query_embedding, embeddings, distance_metric="cosine")
    
    # get indices of nearest neighbors (function from utils.utils.embeddings_utils.py)
    indices_of_nearest_neighbors = indices_of_nearest_neighbors_from_distances(distances)

    # print out source string
    query_string = strings[index_of_source_string]
    print(f"Source string: {query_string}")
    # print out its k nearest neighbors
    k_counter = 0
    for i in indices_of_nearest_neighbors:
        # skip any strings that are identical matches to the starting string
        if query_string == strings[i]:
            continue
        # stop after printing out k articles
        if k_counter >= k_nearest_neighbors:
            break
        k_counter += 1

        # print out the similar strings and their distances
        print(
            f"""
        --- Recommendation #{k_counter} (nearest neighbor {k_counter} of {k_nearest_neighbors}) ---
        String: {strings[i]}
        Distance: {distances[i]:0.3f}"""
        )

    return indices_of_nearest_neighbors

```

### 5. Example recommendations

Let's look for articles similar to first one, which was about Tony Blair.


```python
article_descriptions = df["description"].tolist()

tony_blair_articles = print_recommendations_from_strings(
    strings=article_descriptions,  # let's base similarity off of the article description
    index_of_source_string=0,  # articles similar to the first one about Tony Blair
    k_nearest_neighbors=5,  # 5 most similar articles
)

```

    Source string: BRITAIN: BLAIR WARNS OF CLIMATE THREAT Prime Minister Tony Blair urged the international community to consider global warming a dire threat and agree on a plan of action to curb the  quot;alarming quot; growth of greenhouse gases.
    
            --- Recommendation #1 (nearest neighbor 1 of 5) ---
            String: The anguish of hostage Kenneth Bigley in Iraq hangs over Prime Minister Tony Blair today as he faces the twin test of a local election and a debate by his Labour Party about the divisive war.
            Distance: 0.514
    
            --- Recommendation #2 (nearest neighbor 2 of 5) ---
            String: THE re-election of British Prime Minister Tony Blair would be seen as an endorsement of the military action in Iraq, Prime Minister John Howard said today.
            Distance: 0.516
    
            --- Recommendation #3 (nearest neighbor 3 of 5) ---
            String: Israel is prepared to back a Middle East conference convened by Tony Blair early next year despite having expressed fears that the British plans were over-ambitious and designed 
            Distance: 0.546
    
            --- Recommendation #4 (nearest neighbor 4 of 5) ---
            String: Allowing dozens of casinos to be built in the UK would bring investment and thousands of jobs, Tony Blair says.
            Distance: 0.568
    
            --- Recommendation #5 (nearest neighbor 5 of 5) ---
            String: AFP - A battle group of British troops rolled out of southern Iraq on a US-requested mission to deadlier areas near Baghdad, in a major political gamble for British Prime Minister Tony Blair.
            Distance: 0.579


key: _node_content
string_value:
{"id_": "9cee76dd-99d8-4dc5-b7ee-3f8e2d819276", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb", "title": "Recommendation using embeddings and nearest neighbor search", "tokens": 4069, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "a11a29ec-ba8e-4016-8225-e739c1266d56", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb", "title": "Recommendation using embeddings and nearest neighbor search", "tokens": 4069, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "55cd2bb30475cecec36500acb7c07fdb436389573ee4b15ac4410bf4ec6f69a0", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c6ae37d9-2187-4ac7-9d22-d14d887ef6d0", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb", "title": "Recommendation using embeddings and nearest neighbor search", "tokens": 4069, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "4729a63334c932ef754aa784202741c9ebeca4458ccf9acff1132b802f4f2155", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2c183bba-b975-4615-b90d-94335ea0692b", "node_type": "1", "metadata": {}, "hash": "5ae63dacc5a5799dadefeafa29674962fc3d2513b7ca63ef44b5dab942449d77", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 10756, "end_char_idx": 14090, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Pretty good! 4 of the 5 recommendations explicitly mention Tony Blair and the fifth is an article from London about climate change, topics that might be often associated with Tony Blair.

Let's see how our recommender does on the second example article about NVIDIA's new chipset with more security.


```python
chipset_security_articles = print_recommendations_from_strings(
    strings=article_descriptions,  # let's base similarity off of the article description
    index_of_source_string=1,  # let's look at articles similar to the second one about a more secure chipset
    k_nearest_neighbors=5,  # let's look at the 5 most similar articles
)

```

    Source string: PC World - Upcoming chip set will include built-in security features for your PC.
    
            --- Recommendation #1 (nearest neighbor 1 of 5) ---
            String: PC World - Updated antivirus software for businesses adds intrusion prevention features.
            Distance: 0.422
    
            --- Recommendation #2 (nearest neighbor 2 of 5) ---
            String: PC World - Symantec, McAfee hope raising virus-definition fees will move users to\  suites.
            Distance: 0.518
    
            --- Recommendation #3 (nearest neighbor 3 of 5) ---
            String: originally offered on notebook PCs -- to its Opteron 32- and 64-bit x86 processors for server applications. The technology will help servers to run 
            Distance: 0.522
    
            --- Recommendation #4 (nearest neighbor 4 of 5) ---
            String: PC World - Send your video throughout your house--wirelessly--with new gateways and media adapters.
            Distance: 0.532
    
            --- Recommendation #5 (nearest neighbor 5 of 5) ---
            String: Chips that help a computer's main microprocessors perform specific types of math problems are becoming a big business once again.\
            Distance: 0.532


From the printed distances, you can see that the #1 recommendation is much closer than all the others (0.11 vs 0.14+). And the #1 recommendation looks very similar to the starting article - it's another article from PC World about increasing computer security. Pretty good! 

## Appendix: Using embeddings in more sophisticated recommenders

A more sophisticated way to build a recommender system is to train a machine learning model that takes in tens or hundreds of signals, such as item popularity or user click data. Even in this system, embeddings can be a very useful signal into the recommender, especially for items that are being 'cold started' with no user data yet (e.g., a brand new product added to the catalog without any clicks yet).

## Appendix: Using embeddings to visualize similar articles

To get a sense of what our nearest neighbor recommender is doing, let's visualize the article embeddings. Although we can't plot the 2048 dimensions of each embedding vector, we can use techniques like [t-SNE](https://en.wikipedia.org/wiki/T-distributed_stochastic_neighbor_embedding) or [PCA](https://en.wikipedia.org/wiki/Principal_component_analysis) to compress the embeddings down into 2 or 3 dimensions, which we can chart.

Before visualizing the nearest neighbors, let's visualize all of the article descriptions using t-SNE. Note that t-SNE is not deterministic, meaning that results may vary from run to run.


key: _node_content
string_value:
{"id_": "2c183bba-b975-4615-b90d-94335ea0692b", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb", "title": "Recommendation using embeddings and nearest neighbor search", "tokens": 4069, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "a11a29ec-ba8e-4016-8225-e739c1266d56", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb", "title": "Recommendation using embeddings and nearest neighbor search", "tokens": 4069, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "55cd2bb30475cecec36500acb7c07fdb436389573ee4b15ac4410bf4ec6f69a0", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9cee76dd-99d8-4dc5-b7ee-3f8e2d819276", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb", "title": "Recommendation using embeddings and nearest neighbor search", "tokens": 4069, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "c6073f63e68d28f6cb6cad8f7545dcde8bfd4e4f13c62d4d7c29c3d415b946d2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "00954d1c-d815-4566-bc29-e5c19dbeb527", "node_type": "1", "metadata": {}, "hash": "3f7b3e4e5ab6636347da9cdd6aad327875db456a937af007f180a4965e750e6b", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 12661, "end_char_idx": 15965, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
From the printed distances, you can see that the #1 recommendation is much closer than all the others (0.11 vs 0.14+). And the #1 recommendation looks very similar to the starting article - it's another article from PC World about increasing computer security. Pretty good! 

## Appendix: Using embeddings in more sophisticated recommenders

A more sophisticated way to build a recommender system is to train a machine learning model that takes in tens or hundreds of signals, such as item popularity or user click data. Even in this system, embeddings can be a very useful signal into the recommender, especially for items that are being 'cold started' with no user data yet (e.g., a brand new product added to the catalog without any clicks yet).

## Appendix: Using embeddings to visualize similar articles

To get a sense of what our nearest neighbor recommender is doing, let's visualize the article embeddings. Although we can't plot the 2048 dimensions of each embedding vector, we can use techniques like [t-SNE](https://en.wikipedia.org/wiki/T-distributed_stochastic_neighbor_embedding) or [PCA](https://en.wikipedia.org/wiki/Principal_component_analysis) to compress the embeddings down into 2 or 3 dimensions, which we can chart.

Before visualizing the nearest neighbors, let's visualize all of the article descriptions using t-SNE. Note that t-SNE is not deterministic, meaning that results may vary from run to run.


```python
# get embeddings for all article descriptions
embeddings = [embedding_from_string(string) for string in article_descriptions]
# compress the 2048-dimensional embeddings into 2 dimensions using t-SNE
tsne_components = tsne_components_from_embeddings(embeddings)
# get the article labels for coloring the chart
labels = df["label"].tolist()

chart_from_components(
    components=tsne_components,
    labels=labels,
    strings=article_descriptions,
    width=600,
    height=500,
    title="t-SNE components of article descriptions",
)

```



As you can see in the chart above, even the highly compressed embeddings do a good job of clustering article descriptions by category. And it's worth emphasizing: this clustering is done with no knowledge of the labels themselves!

Also, if you look closely at the most egregious outliers, they are often due to mislabeling rather than poor embedding. For example, the majority of the blue World points in the green Sports cluster appear to be Sports stories.

Next, let's recolor the points by whether they are a source article, its nearest neighbors, or other.


```python
# create labels for the recommended articles
def nearest_neighbor_labels(
    list_of_indices: list[int],
    k_nearest_neighbors: int = 5
) -> list[str]:
    """Return a list of labels to color the k nearest neighbors."""
    labels = ["Other" for _ in list_of_indices]
    source_index = list_of_indices[0]
    labels[source_index] = "Source"
    for i in range(k_nearest_neighbors):
        nearest_neighbor_index = list_of_indices[i + 1]
        labels[nearest_neighbor_index] = f"Nearest neighbor (top {k_nearest_neighbors})"
    return labels


tony_blair_labels = nearest_neighbor_labels(tony_blair_articles, k_nearest_neighbors=5)
chipset_security_labels = nearest_neighbor_labels(chipset_security_articles, k_nearest_neighbors=5
)

```


key: _node_content
string_value:
{"id_": "00954d1c-d815-4566-bc29-e5c19dbeb527", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb", "title": "Recommendation using embeddings and nearest neighbor search", "tokens": 4069, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "a11a29ec-ba8e-4016-8225-e739c1266d56", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb", "title": "Recommendation using embeddings and nearest neighbor search", "tokens": 4069, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "55cd2bb30475cecec36500acb7c07fdb436389573ee4b15ac4410bf4ec6f69a0", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2c183bba-b975-4615-b90d-94335ea0692b", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb", "title": "Recommendation using embeddings and nearest neighbor search", "tokens": 4069, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "eb3400634536737d2d72d10570a4675f4b3b1f5ef459f89724dda40bf5c66191", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 14646, "end_char_idx": 17660, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
As you can see in the chart above, even the highly compressed embeddings do a good job of clustering article descriptions by category. And it's worth emphasizing: this clustering is done with no knowledge of the labels themselves!

Also, if you look closely at the most egregious outliers, they are often due to mislabeling rather than poor embedding. For example, the majority of the blue World points in the green Sports cluster appear to be Sports stories.

Next, let's recolor the points by whether they are a source article, its nearest neighbors, or other.


```python
# create labels for the recommended articles
def nearest_neighbor_labels(
    list_of_indices: list[int],
    k_nearest_neighbors: int = 5
) -> list[str]:
    """Return a list of labels to color the k nearest neighbors."""
    labels = ["Other" for _ in list_of_indices]
    source_index = list_of_indices[0]
    labels[source_index] = "Source"
    for i in range(k_nearest_neighbors):
        nearest_neighbor_index = list_of_indices[i + 1]
        labels[nearest_neighbor_index] = f"Nearest neighbor (top {k_nearest_neighbors})"
    return labels


tony_blair_labels = nearest_neighbor_labels(tony_blair_articles, k_nearest_neighbors=5)
chipset_security_labels = nearest_neighbor_labels(chipset_security_articles, k_nearest_neighbors=5
)

```


```python
# a 2D chart of nearest neighbors of the Tony Blair article
chart_from_components(
    components=tsne_components,
    labels=tony_blair_labels,
    strings=article_descriptions,
    width=600,
    height=500,
    title="Nearest neighbors of the Tony Blair article",
    category_orders={"label": ["Other", "Nearest neighbor (top 5)", "Source"]},
)

```



Looking at the 2D chart above, we can see that the articles about Tony Blair are somewhat close together inside of the World news cluster. Interestingly, although the 5 nearest neighbors (red) were closest in high dimensional space, they are not the closest points in this compressed 2D space. Compressing the embeddings down to 2 dimensions discards much of their information, and the nearest neighbors in the 2D space don't seem to be as relevant as those in the full embedding space.


```python
# a 2D chart of nearest neighbors of the chipset security article
chart_from_components(
    components=tsne_components,
    labels=chipset_security_labels,
    strings=article_descriptions,
    width=600,
    height=500,
    title="Nearest neighbors of the chipset security article",
    category_orders={"label": ["Other", "Nearest neighbor (top 5)", "Source"]},
)

```



For the chipset security example, the 4 closest nearest neighbors in the full embedding space remain nearest neighbors in this compressed 2D visualization. The fifth is displayed as more distant, despite being closer in the full embedding space.

Should you want to, you can also make an interactive 3D plot of the embeddings with the function `chart_from_components_3D`. (Doing so will require recomputing the t-SNE components with `n_components=3`.)


key: _node_content
string_value:
{"id_": "d6defee1-92af-4ce9-bd92-f7cefdc2952d", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "f4791e24-686a-4906-9f86-a8cd385120cc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "143d1ff00605bdcd7deef3627aa3385ba87f078aaedf31eeaddec44418405200", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8ddea7a9-df48-4ad4-822c-6d73800e8eac", "node_type": "1", "metadata": {}, "hash": "7aef4d97ee1085af22b4d2c5c83f2b689499e355d2c921dabae5b0d073008310", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2980, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Batch processing with the Batch API

The new Batch API allows to **create async batch jobs for a lower price and with higher rate limits**.

Batches will be completed within 24h, but may be processed sooner depending on global usage. 

Ideal use cases for the Batch API include:

- Tagging, captioning, or enriching content on a marketplace or blog
- Categorizing and suggesting answers for support tickets
- Performing sentiment analysis on large datasets of customer feedback
- Generating summaries or translations for collections of documents or articles

and much more!

This cookbook will walk you through how to use the Batch API with a couple of practical examples.

We will start with an example to categorize movies using `gpt-4o-mini`, and then cover how we can use the vision capabilities of this model to caption images.

Please note that multiple models are available through the Batch API, and that you can use the same parameters in your Batch API calls as with the Chat Completions endpoint.

## Setup


```python
# Make sure you have the latest version of the SDK available to use the Batch API
%pip install openai --upgrade
```


```python
import json
from openai import OpenAI
import pandas as pd
from IPython.display import Image, display
```


```python
# Initializing OpenAI client - see https://platform.openai.com/docs/quickstart?context=python
client = OpenAI()
```

## First example: Categorizing movies

In this example, we will use `gpt-4o-mini` to extract movie categories from a description of the movie. We will also extract a 1-sentence summary from this description. 

We will use [JSON mode](https://platform.openai.com/docs/guides/text-generation/json-mode) to extract categories as an array of strings and the 1-sentence summary in a structured format. 

For each movie, we want to get a result that looks like this:

```
{
    categories: ['category1', 'category2', 'category3'],
    summary: '1-sentence summary'
}
```

### Loading data

We will use the IMDB top 1000 movies dataset for this example. 


```python
dataset_path = "data/imdb_top_1000.csv"

df = pd.read_csv(dataset_path)
df.head()
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Poster_Link</th>
      <th>Series_Title</th>
      <th>Released_Year</th>
      <th>Certificate</th>
      <th>Runtime</th>
      <th>Genre</th>
      <th>IMDB_Rating</th>
      <th>Overview</th>
      <th>Meta_score</th>
      <th>Director</th>
      <th>Star1</th>
      <th>Star2</th>
      <th>Star3</th>
      <th>Star4</th>
      <th>No_of_Votes</th>
      <th>Gross</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>https://m.media-amazon.com/images/M/MV5BMDFkYT.


key: _node_content
string_value:
{"id_": "8ddea7a9-df48-4ad4-822c-6d73800e8eac", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "f4791e24-686a-4906-9f86-a8cd385120cc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "143d1ff00605bdcd7deef3627aa3385ba87f078aaedf31eeaddec44418405200", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d6defee1-92af-4ce9-bd92-f7cefdc2952d", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "3ad46c590848f35506e841ab451020df9a38fa420b8546ee51a6e4de3ba1ec5e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "76f84a3b-e6fb-4f3a-8b4f-e4024d0c3b22", "node_type": "1", "metadata": {}, "hash": "689b2a2a194a3de3116d4131edc23f66ea218263747391e5c55977f8a69c39a1", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": null, "end_char_idx": null, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
dataset_path = "data/imdb_top_1000.csv"

df = pd.read_csv(dataset_path)
df.head()
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Poster_Link</th>
      <th>Series_Title</th>
      <th>Released_Year</th>
      <th>Certificate</th>
      <th>Runtime</th>
      <th>Genre</th>
      <th>IMDB_Rating</th>
      <th>Overview</th>
      <th>Meta_score</th>
      <th>Director</th>
      <th>Star1</th>
      <th>Star2</th>
      <th>Star3</th>
      <th>Star4</th>
      <th>No_of_Votes</th>
      <th>Gross</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>https://m.media-amazon.com/images/M/MV5BMDFkYT.</td>
      <td>The Shawshank Redemption</td>
      <td>1994</td>
      <td>A</td>
      <td>142 min</td>
      <td>Drama</td>
      <td>9.3</td>
      <td>Two imprisoned men bond over a number of years.</td>
      <td>80.0</td>
      <td>Frank Darabont</td>
      <td>Tim Robbins</td>
      <td>Morgan Freeman</td>
      <td>Bob Gunton</td>
      <td>William Sadler</td>
      <td>2343110</td>
      <td>28,341,469</td>
    </tr>
    <tr>
      <th>1</th>
      <td>https://m.media-amazon.com/images/M/MV5BM2MyNj.</td>
      <td>The Godfather</td>
      <td>1972</td>
      <td>A</td>
      <td>175 min</td>
      <td>Crime, Drama</td>
      <td>9.2</td>
      <td>An organized crime dynasty's aging patriarch t.</td>
      <td>100.0</td>
      <td>Francis Ford Coppola</td>
      <td>Marlon Brando</td>
      <td>Al Pacino</td>
      <td>James Caan</td>
      <td>Diane Keaton</td>
      <td>1620367</td>
      <td>134,966,411</td>
    </tr>
    <tr>
      <th>2</th>
      <td>https://m.media-amazon.com/images/M/MV5BMTMxNT.</td>
      <td>The Dark Knight</td>
      <td>2008</td>
      <td>UA</td>
      <td>152 min</td>
      <td>Action, Crime, Drama</td>
      <td>9.


key: _node_content
string_value:
{"id_": "76f84a3b-e6fb-4f3a-8b4f-e4024d0c3b22", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "f4791e24-686a-4906-9f86-a8cd385120cc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "143d1ff00605bdcd7deef3627aa3385ba87f078aaedf31eeaddec44418405200", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8ddea7a9-df48-4ad4-822c-6d73800e8eac", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "93612a8b53b795d4d529390d7d357ba6f30b4db0c758d49f7898312de3cbb386", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "195476db-00cb-4b9f-864a-ff6d330c9071", "node_type": "1", "metadata": {}, "hash": "f259f4997073520d4389520c48dff2e1198b59bf56544c5eca6f3cb36f8b4a01", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": null, "end_char_idx": null, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
3</td>
      <td>Two imprisoned men bond over a number of years.</td>
      <td>80.0</td>
      <td>Frank Darabont</td>
      <td>Tim Robbins</td>
      <td>Morgan Freeman</td>
      <td>Bob Gunton</td>
      <td>William Sadler</td>
      <td>2343110</td>
      <td>28,341,469</td>
    </tr>
    <tr>
      <th>1</th>
      <td>https://m.media-amazon.com/images/M/MV5BM2MyNj.</td>
      <td>The Godfather</td>
      <td>1972</td>
      <td>A</td>
      <td>175 min</td>
      <td>Crime, Drama</td>
      <td>9.2</td>
      <td>An organized crime dynasty's aging patriarch t.</td>
      <td>100.0</td>
      <td>Francis Ford Coppola</td>
      <td>Marlon Brando</td>
      <td>Al Pacino</td>
      <td>James Caan</td>
      <td>Diane Keaton</td>
      <td>1620367</td>
      <td>134,966,411</td>
    </tr>
    <tr>
      <th>2</th>
      <td>https://m.media-amazon.com/images/M/MV5BMTMxNT.</td>
      <td>The Dark Knight</td>
      <td>2008</td>
      <td>UA</td>
      <td>152 min</td>
      <td>Action, Crime, Drama</td>
      <td>9.0</td>
      <td>When the menace known as the Joker wreaks havo.</td>
      <td>84.0</td>
      <td>Christopher Nolan</td>
      <td>Christian Bale</td>
      <td>Heath Ledger</td>
      <td>Aaron Eckhart</td>
      <td>Michael Caine</td>
      <td>2303232</td>
      <td>534,858,444</td>
    </tr>
    <tr>
      <th>3</th>
      <td>https://m.media-amazon.com/images/M/MV5BMWMwMG.</td>
      <td>The Godfather: Part II</td>
      <td>1974</td>
      <td>A</td>
      <td>202 min</td>
      <td>Crime, Drama</td>
      <td>9.0</td>
      <td>The early life and career of Vito Corleone in .</td>
      <td>90.0</td>
      <td>Francis Ford Coppola</td>
      <td>Al Pacino</td>
      <td>Robert De Niro</td>
      <td>Robert Duvall</td>
      <td>Diane Keaton</td>
      <td>1129952</td>
      <td>57,300,000</td>
    </tr>
    <tr>
      <th>4</th>
      <td>https://m.media-amazon.com/images/M/MV5BMWU4N2.


key: _node_content
string_value:
{"id_": "195476db-00cb-4b9f-864a-ff6d330c9071", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "f4791e24-686a-4906-9f86-a8cd385120cc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "143d1ff00605bdcd7deef3627aa3385ba87f078aaedf31eeaddec44418405200", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "76f84a3b-e6fb-4f3a-8b4f-e4024d0c3b22", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "67f81eb3c98d4d7b1722ade5ddb9343da32099083f40675c5e47663b358326d5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ec2b95d4-e4aa-44f9-b1f9-1e2bef239de2", "node_type": "1", "metadata": {}, "hash": "94a0ffa62c368205975badcc8ca6e43bb899b2f158bc51103f09605af1cb3055", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": null, "end_char_idx": null, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Crime, Drama</td>
      <td>9.0</td>
      <td>When the menace known as the Joker wreaks havo.</td>
      <td>84.0</td>
      <td>Christopher Nolan</td>
      <td>Christian Bale</td>
      <td>Heath Ledger</td>
      <td>Aaron Eckhart</td>
      <td>Michael Caine</td>
      <td>2303232</td>
      <td>534,858,444</td>
    </tr>
    <tr>
      <th>3</th>
      <td>https://m.media-amazon.com/images/M/MV5BMWMwMG.</td>
      <td>The Godfather: Part II</td>
      <td>1974</td>
      <td>A</td>
      <td>202 min</td>
      <td>Crime, Drama</td>
      <td>9.0</td>
      <td>The early life and career of Vito Corleone in .</td>
      <td>90.0</td>
      <td>Francis Ford Coppola</td>
      <td>Al Pacino</td>
      <td>Robert De Niro</td>
      <td>Robert Duvall</td>
      <td>Diane Keaton</td>
      <td>1129952</td>
      <td>57,300,000</td>
    </tr>
    <tr>
      <th>4</th>
      <td>https://m.media-amazon.com/images/M/MV5BMWU4N2.</td>
      <td>12 Angry Men</td>
      <td>1957</td>
      <td>U</td>
      <td>96 min</td>
      <td>Crime, Drama</td>
      <td>9.0</td>
      <td>A jury holdout attempts to prevent a miscarria.</td>
      <td>96.0</td>
      <td>Sidney Lumet</td>
      <td>Henry Fonda</td>
      <td>Lee J. Cobb</td>
      <td>Martin Balsam</td>
      <td>John Fiedler</td>
      <td>689845</td>
      <td>4,360,000</td>
    </tr>
  </tbody>
</table>
</div>



### Processing step 

Here, we will prepare our requests by first trying them out with the Chat Completions endpoint.

Once we're happy with the results, we can move on to creating the batch file.


key: _node_content
string_value:
{"id_": "ec2b95d4-e4aa-44f9-b1f9-1e2bef239de2", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "f4791e24-686a-4906-9f86-a8cd385120cc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "143d1ff00605bdcd7deef3627aa3385ba87f078aaedf31eeaddec44418405200", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "195476db-00cb-4b9f-864a-ff6d330c9071", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "779b7b0d969b3379627720c319487c4d120f6f8d99563a35e0b698c4bb2a6f31", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "74a5fd50-19b4-4204-bc27-dc75c0a38dff", "node_type": "1", "metadata": {}, "hash": "f96941a5b3fe0d45439335fbdb86ead39c347aac94ea6f6b4600d14282f4bbbd", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": null, "end_char_idx": null, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Drama</td>
      <td>9.0</td>
      <td>The early life and career of Vito Corleone in .</td>
      <td>90.0</td>
      <td>Francis Ford Coppola</td>
      <td>Al Pacino</td>
      <td>Robert De Niro</td>
      <td>Robert Duvall</td>
      <td>Diane Keaton</td>
      <td>1129952</td>
      <td>57,300,000</td>
    </tr>
    <tr>
      <th>4</th>
      <td>https://m.media-amazon.com/images/M/MV5BMWU4N2.</td>
      <td>12 Angry Men</td>
      <td>1957</td>
      <td>U</td>
      <td>96 min</td>
      <td>Crime, Drama</td>
      <td>9.0</td>
      <td>A jury holdout attempts to prevent a miscarria.</td>
      <td>96.0</td>
      <td>Sidney Lumet</td>
      <td>Henry Fonda</td>
      <td>Lee J. Cobb</td>
      <td>Martin Balsam</td>
      <td>John Fiedler</td>
      <td>689845</td>
      <td>4,360,000</td>
    </tr>
  </tbody>
</table>
</div>



### Processing step 

Here, we will prepare our requests by first trying them out with the Chat Completions endpoint.

Once we're happy with the results, we can move on to creating the batch file.


```python
categorize_system_prompt = '''
Your goal is to extract movie categories from movie descriptions, as well as a 1-sentence summary for these movies.
You will be provided with a movie description, and you will output a json object containing the following information:

{
    categories: string[] // Array of categories based on the movie description,
    summary: string // 1-sentence summary of the movie based on the movie description
}

Categories refer to the genre or type of the movie, like "action", "romance", "comedy", etc. Keep category names simple and use only lower case letters.
Movies can have several categories, but try to keep it under 3-4. Only mention the categories that are the most obvious based on the description.
'''

def get_categories(description):
    response = client.chat.completions.create(
    model="gpt-4o-mini",
    temperature=0.1,
    # This is to enable JSON mode, making sure responses are valid json objects
    response_format={ 
        "type": "json_object"
    },
    messages=[
        {
            "role": "system",
            "content": categorize_system_prompt
        },
        {
            "role": "user",
            "content": description
        }
    ],
    )

    return response.choices[0].message.content
```


key: _node_content
string_value:
{"id_": "74a5fd50-19b4-4204-bc27-dc75c0a38dff", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "f4791e24-686a-4906-9f86-a8cd385120cc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "143d1ff00605bdcd7deef3627aa3385ba87f078aaedf31eeaddec44418405200", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ec2b95d4-e4aa-44f9-b1f9-1e2bef239de2", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "094f667d8f65695997d456e8a43eed7fb26cfba9749054cc26f27b563ddfe95a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "25857daa-6c7f-46ee-b753-8cee72c41092", "node_type": "1", "metadata": {}, "hash": "633333c077213fbdb89f5b31c4a45d1df185c13f4caa95b06b2657c73d801c0e", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5374, "end_char_idx": 9454, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Cobb</td>
      <td>Martin Balsam</td>
      <td>John Fiedler</td>
      <td>689845</td>
      <td>4,360,000</td>
    </tr>
  </tbody>
</table>
</div>



### Processing step 

Here, we will prepare our requests by first trying them out with the Chat Completions endpoint.

Once we're happy with the results, we can move on to creating the batch file.


```python
categorize_system_prompt = '''
Your goal is to extract movie categories from movie descriptions, as well as a 1-sentence summary for these movies.
You will be provided with a movie description, and you will output a json object containing the following information:

{
    categories: string[] // Array of categories based on the movie description,
    summary: string // 1-sentence summary of the movie based on the movie description
}

Categories refer to the genre or type of the movie, like "action", "romance", "comedy", etc. Keep category names simple and use only lower case letters.
Movies can have several categories, but try to keep it under 3-4. Only mention the categories that are the most obvious based on the description.
'''

def get_categories(description):
    response = client.chat.completions.create(
    model="gpt-4o-mini",
    temperature=0.1,
    # This is to enable JSON mode, making sure responses are valid json objects
    response_format={ 
        "type": "json_object"
    },
    messages=[
        {
            "role": "system",
            "content": categorize_system_prompt
        },
        {
            "role": "user",
            "content": description
        }
    ],
    )

    return response.choices[0].message.content
```


```python
# Testing on a few examples
for _, row in df[:5].iterrows():
    description = row['Overview']
    title = row['Series_Title']
    result = get_categories(description)
    print(f"TITLE: {title}\nOVERVIEW: {description}\n\nRESULT: {result}")
    print("\n\n----------------------------\n\n")
```

    TITLE: The Shawshank Redemption
    OVERVIEW: Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.
    
    RESULT: {
        "categories": ["drama"],
        "summary": "Two imprisoned men develop a deep bond over the years, ultimately finding redemption through their shared acts of kindness."
    }
    
    
    ----------------------------
    
    
    TITLE: The Godfather
    OVERVIEW: An organized crime dynasty's aging patriarch transfers control of his clandestine empire to his reluctant son.
    
    RESULT: {
        "categories": ["crime", "drama"],
        "summary": "An aging crime lord hands over his empire to his hesitant son."
    }
    
    
    ----------------------------
    
    
    TITLE: The Dark Knight
    OVERVIEW: When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, Batman must accept one of the greatest psychological and physical tests of his ability to fight injustice.
    
    RESULT: {
        "categories": ["action", "thriller", "superhero"],
        "summary": "Batman faces a formidable challenge as the Joker unleashes chaos on Gotham City."
    }
    
    
    ----------------------------
    
    
    TITLE: The Godfather: Part II
    OVERVIEW: The early life and career of Vito Corleone in 1920s New York City is portrayed, while his son, Michael, expands and tightens his grip on the family crime syndicate.
    
    RESULT: {
        "categories": ["crime", "drama"],
        "summary": "The film depicts the early life of Vito Corleone and the rise of his son Michael within the family crime syndicate in 1920s New York City."
    }
    
    
    ----------------------------
    
    
    TITLE: 12 Angry Men
    OVERVIEW: A jury holdout attempts to prevent a miscarriage of justice by forcing his colleagues to reconsider the evidence.
    
    RESULT: {
        "categories": ["drama", "thriller"],
        "summary": "A jury holdout fights to ensure justice is served by challenging his fellow jurors to reevaluate the evidence."
    }
    
    
    ----------------------------


key: _node_content
string_value:
{"id_": "25857daa-6c7f-46ee-b753-8cee72c41092", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "f4791e24-686a-4906-9f86-a8cd385120cc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "143d1ff00605bdcd7deef3627aa3385ba87f078aaedf31eeaddec44418405200", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "74a5fd50-19b4-4204-bc27-dc75c0a38dff", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "e02d0678b5099b4a88665889fc17f00768af064ffc26bf2fb13c4c619656a1bf", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3ff5280b-1c86-4861-9204-a0990953ee6d", "node_type": "1", "metadata": {}, "hash": "a2fe4493b4a43c501e5810832b0db465a72d3f0b885aaa55c9196431605d2f96", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 9467, "end_char_idx": 12528, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
### Creating the batch file

The batch file, in the `jsonl` format, should contain one line (json object) per request.
Each request is defined as such:

```
{
    "custom_id": <REQUEST_ID>,
    "method": "POST",
    "url": "/v1/chat/completions",
    "body": {
        "model": <MODEL>,
        "messages": <MESSAGES>,
        // other parameters
    }
}
```

Note: the request ID should be unique per batch. This is what you can use to match results to the initial input files, as requests will not be returned in the same order.


```python
# Creating an array of json tasks

tasks = []

for index, row in df.iterrows():
    
    description = row['Overview']
    
    task = {
        "custom_id": f"task-{index}",
        "method": "POST",
        "url": "/v1/chat/completions",
        "body": {
            # This is what you would have in your Chat Completions API call
            "model": "gpt-4o-mini",
            "temperature": 0.1,
            "response_format": { 
                "type": "json_object"
            },
            "messages": [
                {
                    "role": "system",
                    "content": categorize_system_prompt
                },
                {
                    "role": "user",
                    "content": description
                }
            ],
        }
    }
    
    tasks.append(task)
```


```python
# Creating the file

file_name = "data/batch_tasks_movies.jsonl"

with open(file_name, 'w') as file:
    for obj in tasks:
        file.write(json.dumps(obj) + '\n')
```

### Uploading the file


```python
batch_file = client.files.create(
  file=open(file_name, "rb"),
  purpose="batch"
)
```


```python
print(batch_file)
```

    FileObject(id='file-lx16f1KyIxQ2UHVvkG3HLfNR', bytes=1127310, created_at=1721144107, filename='batch_tasks_movies.jsonl', object='file', purpose='batch', status='processed', status_details=None)


### Creating the batch job


```python
batch_job = client.batches.create(
  input_file_id=batch_file.id,
  endpoint="/v1/chat/completions",
  completion_window="24h"
)
```

### Checking batch status

Note: this can take up to 24h, but it will usually be completed faster.

You can continue checking until the status is 'completed'.


```python
batch_job = client.batches.retrieve(batch_job.id)
print(batch_job)
```

### Retrieving results


```python
result_file_id = batch_job.output_file_id
result = client.files.content(result_file_id).content
```


```python
result_file_name = "data/batch_job_results_movies.jsonl"

with open(result_file_name, 'wb') as file:
    file.write(result)
```


```python
# Loading data from saved file
results = []
with open(result_file_name, 'r') as file:
    for line in file:
        # Parsing the JSON string into a dict and appending to the list of results
        json_object = json.loads(line.strip())
        results.append(json_object)
```

### Reading results
Reminder: the results are not in the same order as in the input file.
Make sure to check the custom_id to match the results against the input requests


key: _node_content
string_value:
{"id_": "3ff5280b-1c86-4861-9204-a0990953ee6d", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "f4791e24-686a-4906-9f86-a8cd385120cc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "143d1ff00605bdcd7deef3627aa3385ba87f078aaedf31eeaddec44418405200", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "25857daa-6c7f-46ee-b753-8cee72c41092", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "44ee84b2051b3540b0f58368cbcc0c618941858a45855d666826688f30788e94", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "726e55e0-e764-4736-94ca-2f00120dad49", "node_type": "1", "metadata": {}, "hash": "4e270a15ea8473161d5a615f377d02b89829eabf735198e50e13dcf7c346e3ea", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 11042, "end_char_idx": 15336, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
batch_file = client.files.create(
  file=open(file_name, "rb"),
  purpose="batch"
)
```


```python
print(batch_file)
```

    FileObject(id='file-lx16f1KyIxQ2UHVvkG3HLfNR', bytes=1127310, created_at=1721144107, filename='batch_tasks_movies.jsonl', object='file', purpose='batch', status='processed', status_details=None)


### Creating the batch job


```python
batch_job = client.batches.create(
  input_file_id=batch_file.id,
  endpoint="/v1/chat/completions",
  completion_window="24h"
)
```

### Checking batch status

Note: this can take up to 24h, but it will usually be completed faster.

You can continue checking until the status is 'completed'.


```python
batch_job = client.batches.retrieve(batch_job.id)
print(batch_job)
```

### Retrieving results


```python
result_file_id = batch_job.output_file_id
result = client.files.content(result_file_id).content
```


```python
result_file_name = "data/batch_job_results_movies.jsonl"

with open(result_file_name, 'wb') as file:
    file.write(result)
```


```python
# Loading data from saved file
results = []
with open(result_file_name, 'r') as file:
    for line in file:
        # Parsing the JSON string into a dict and appending to the list of results
        json_object = json.loads(line.strip())
        results.append(json_object)
```

### Reading results
Reminder: the results are not in the same order as in the input file.
Make sure to check the custom_id to match the results against the input requests


```python
# Reading only the first results
for res in results[:5]:
    task_id = res['custom_id']
    # Getting index from task id
    index = task_id.split('-')[-1]
    result = res['response']['body']['choices'][0]['message']['content']
    movie = df.iloc[int(index)]
    description = movie['Overview']
    title = movie['Series_Title']
    print(f"TITLE: {title}\nOVERVIEW: {description}\n\nRESULT: {result}")
    print("\n\n----------------------------\n\n")
```

    TITLE: American Psycho
    OVERVIEW: A wealthy New York City investment banking executive, Patrick Bateman, hides his alternate psychopathic ego from his co-workers and friends as he delves deeper into his violent, hedonistic fantasies.
    
    RESULT: {
        "categories": ["thriller", "psychological", "drama"],
        "summary": "A wealthy investment banker in New York City conceals his psychopathic alter ego while indulging in violent and hedonistic fantasies."
    }
    
    
    ----------------------------
    
    
    TITLE: Lethal Weapon
    OVERVIEW: Two newly paired cops who are complete opposites must put aside their differences in order to catch a gang of drug smugglers.
    
    RESULT: {
        "categories": ["action", "comedy", "crime"],
        "summary": "An action-packed comedy about two mismatched cops teaming up to take down a drug smuggling gang."
    }
    
    
    ----------------------------
    
    
    TITLE: A Star Is Born
    OVERVIEW: A musician helps a young singer find fame as age and alcoholism send his own career into a downward spiral.
    
    RESULT: {
        "categories": ["drama", "music"],
        "summary": "A musician's career spirals downward as he helps a young singer find fame amidst struggles with age and alcoholism."
    }
    
    
    ----------------------------
    
    
    TITLE: From Here to Eternity
    OVERVIEW: In Hawaii in 1941, a private is cruelly punished for not boxing on his unit's team, while his captain's wife and second-in-command are falling in love.
    
    RESULT: {
        "categories": ["drama", "romance", "war"],
        "summary": "A drama set in Hawaii in 1941, where a private faces punishment for not boxing on his unit's team, amidst a forbidden love affair between his captain's wife and second-in-command."
    }
    
    
    ----------------------------
    
    
    TITLE: The Jungle Book
    OVERVIEW: Bagheera the Panther and Baloo the Bear have a difficult time trying to convince a boy to leave the jungle for human civilization.
    
    RESULT: {
        "categories": ["adventure", "animation", "family"],
        "summary": "An adventure-filled animated movie about a panther and a bear trying to persuade a boy to leave the jungle for human civilization."
    }
    
    
    ----------------------------


key: _node_content
string_value:
{"id_": "726e55e0-e764-4736-94ca-2f00120dad49", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "f4791e24-686a-4906-9f86-a8cd385120cc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "143d1ff00605bdcd7deef3627aa3385ba87f078aaedf31eeaddec44418405200", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3ff5280b-1c86-4861-9204-a0990953ee6d", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "bafdc87816167a854883273cfda9a8cd7cc28ebdff9d9b1550debcf37bba5d4f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8d6809bf-087b-43e0-b07f-299c668cc03a", "node_type": "1", "metadata": {}, "hash": "651b3786a1b7ade798e00d0e4b80bf10ccd031c916f77197c7abca78eef3abcf", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": null, "end_char_idx": null, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
## Second example: Captioning images

In this example, we will use `gpt-4-turbo` to caption images of furniture items. 

We will use the vision capabilities of the model to analyze the images and generate the captions.

### Loading data

We will use the Amazon furniture dataset for this example.


```python
dataset_path = "data/amazon_furniture_dataset.csv"
df = pd.read_csv(dataset_path)
df.head()
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>asin</th>
      <th>url</th>
      <th>title</th>
      <th>brand</th>
      <th>price</th>
      <th>availability</th>
      <th>categories</th>
      <th>primary_image</th>
      <th>images</th>
      <th>upc</th>
      <th>.</th>
      <th>color</th>
      <th>material</th>
      <th>style</th>
      <th>important_information</th>
      <th>product_overview</th>
      <th>about_item</th>
      <th>description</th>
      <th>specifications</th>
      <th>uniq_id</th>
      <th>scraped_at</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>B0CJHKVG6P</td>
      <td>https://www.amazon.com/dp/B0CJHKVG6P</td>
      <td>GOYMFK 1pc Free Standing Shoe Rack, Multi-laye.</td>
      <td>GOYMFK</td>
      <td>$24.99</td>
      <td>Only 13 left in stock - order soon.</td>
      <td>['Home &amp; Kitchen', 'Storage &amp; Organization', '.</td>
      <td>https://m.media-amazon.com/images/I/416WaLx10j.</td>
      <td>['https://m.media-amazon.com/images/I/416WaLx1.</td>
      <td>NaN</td>
      <td>.</td>
      <td>White</td>
      <td>Metal</td>
      <td>Modern</td>
      <td>[]</td>
      <td>[{'Brand': ' GOYMFK '}, {'Color': ' White '}, .</td>
      <td>['Multiple layers: Provides ample storage spac.</td>
      <td>multiple shoes, coats, hats, and other items E.</td>
      <td>['Brand: GOYMFK', 'Color: White', 'Material: M.</td>
      <td>02593e81-5c09-5069-8516-b0b29f439ded</td>
      <td>2024-02-02 15:15:08</td>
    </tr>
    <tr>
      <th>1</th>
      <td>B0B66QHB23</td>
      <td>https://www.amazon.


key: _node_content
string_value:
{"id_": "8d6809bf-087b-43e0-b07f-299c668cc03a", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "f4791e24-686a-4906-9f86-a8cd385120cc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "143d1ff00605bdcd7deef3627aa3385ba87f078aaedf31eeaddec44418405200", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "726e55e0-e764-4736-94ca-2f00120dad49", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "5815e78c7401298e8961fbfe5343dd286fb90206557379945065e9cbf8e77200", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "22b83829-e898-4170-8001-1b14be6c7ed9", "node_type": "1", "metadata": {}, "hash": "32541f55b39005325508c1a46cefefec5003a576f76ac0112e25eaf1913526f8", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": null, "end_char_idx": null, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
amazon.com/dp/B0CJHKVG6P</td>
      <td>GOYMFK 1pc Free Standing Shoe Rack, Multi-laye.</td>
      <td>GOYMFK</td>
      <td>$24.99</td>
      <td>Only 13 left in stock - order soon.</td>
      <td>['Home &amp; Kitchen', 'Storage &amp; Organization', '.</td>
      <td>https://m.media-amazon.com/images/I/416WaLx10j.</td>
      <td>['https://m.media-amazon.com/images/I/416WaLx1.</td>
      <td>NaN</td>
      <td>.</td>
      <td>White</td>
      <td>Metal</td>
      <td>Modern</td>
      <td>[]</td>
      <td>[{'Brand': ' GOYMFK '}, {'Color': ' White '}, .</td>
      <td>['Multiple layers: Provides ample storage spac.</td>
      <td>multiple shoes, coats, hats, and other items E.</td>
      <td>['Brand: GOYMFK', 'Color: White', 'Material: M.</td>
      <td>02593e81-5c09-5069-8516-b0b29f439ded</td>
      <td>2024-02-02 15:15:08</td>
    </tr>
    <tr>
      <th>1</th>
      <td>B0B66QHB23</td>
      <td>https://www.amazon.com/dp/B0B66QHB23</td>
      <td>subrtex Leather ding Room, Dining Chairs Set o.</td>
      <td>subrtex</td>
      <td>NaN</td>
      <td>NaN</td>
      <td>['Home &amp; Kitchen', 'Furniture', 'Dining Room F.</td>
      <td>https://m.media-amazon.com/images/I/31SejUEWY7.</td>
      <td>['https://m.media-amazon.com/images/I/31SejUEW.</td>
      <td>NaN</td>
      <td>.</td>
      <td>Black</td>
      <td>Sponge</td>
      <td>Black Rubber Wood</td>
      <td>[]</td>
      <td>NaN</td>
      <td>['【Easy Assembly】: Set of 2 dining room chairs.</td>
      <td>subrtex Dining chairs Set of 2</td>
      <td>['Brand: subrtex', 'Color: Black', 'Product Di.</td>
      <td>5938d217-b8c5-5d3e-b1cf-e28e340f292e</td>
      <td>2024-02-02 15:15:09</td>
    </tr>
    <tr>
      <th>2</th>
      <td>B0BXRTWLYK</td>
      <td>https://www.amazon.com/dp/B0BXRTWLYK</td>
      <td>Plant Repotting Mat MUYETOL Waterproof Transpl.</td>
      <td>MUYETOL</td>
      <td>$5.98</td>
      <td>In Stock</td>
      <td>['Patio, Lawn &amp; Garden',


key: _node_content
string_value:
{"id_": "22b83829-e898-4170-8001-1b14be6c7ed9", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "f4791e24-686a-4906-9f86-a8cd385120cc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "143d1ff00605bdcd7deef3627aa3385ba87f078aaedf31eeaddec44418405200", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8d6809bf-087b-43e0-b07f-299c668cc03a", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "662d2eaecc33b687b9349be68d712d36cf666c35bb683b8a00d8b16e97122b5f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "782b66de-1a7c-47c3-a6a4-c321e0508945", "node_type": "1", "metadata": {}, "hash": "2010cf8beb9c6c716d57871f07e9746ea93a07e7b34a22fc6c69cf34b6e13718", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": null, "end_char_idx": null, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Dining Chairs Set o.</td>
      <td>subrtex</td>
      <td>NaN</td>
      <td>NaN</td>
      <td>['Home &amp; Kitchen', 'Furniture', 'Dining Room F.</td>
      <td>https://m.media-amazon.com/images/I/31SejUEWY7.</td>
      <td>['https://m.media-amazon.com/images/I/31SejUEW.</td>
      <td>NaN</td>
      <td>.</td>
      <td>Black</td>
      <td>Sponge</td>
      <td>Black Rubber Wood</td>
      <td>[]</td>
      <td>NaN</td>
      <td>['【Easy Assembly】: Set of 2 dining room chairs.</td>
      <td>subrtex Dining chairs Set of 2</td>
      <td>['Brand: subrtex', 'Color: Black', 'Product Di.</td>
      <td>5938d217-b8c5-5d3e-b1cf-e28e340f292e</td>
      <td>2024-02-02 15:15:09</td>
    </tr>
    <tr>
      <th>2</th>
      <td>B0BXRTWLYK</td>
      <td>https://www.amazon.com/dp/B0BXRTWLYK</td>
      <td>Plant Repotting Mat MUYETOL Waterproof Transpl.</td>
      <td>MUYETOL</td>
      <td>$5.98</td>
      <td>In Stock</td>
      <td>['Patio, Lawn &amp; Garden', 'Outdoor Décor', 'Doo.</td>
      <td>https://m.media-amazon.com/images/I/41RgefVq70.</td>
      <td>['https://m.media-amazon.com/images/I/41RgefVq.</td>
      <td>NaN</td>
      <td>.</td>
      <td>Green</td>
      <td>Polyethylene</td>
      <td>Modern</td>
      <td>[]</td>
      <td>[{'Brand': ' MUYETOL '}, {'Size': ' 26.8*26.8 .</td>
      <td>['PLANT REPOTTING MAT SIZE: 26.8" x 26.8", squ.</td>
      <td>NaN</td>
      <td>['Brand: MUYETOL', 'Size: 26.8*26.8', 'Item We.</td>
      <td>b2ede786-3f51-5a45-9a5b-bcf856958cd8</td>
      <td>2024-02-02 15:15:09</td>
    </tr>
    <tr>
      <th>3</th>
      <td>B0C1MRB2M8</td>
      <td>https://www.amazon.com/dp/B0C1MRB2M8</td>
      <td>Pickleball Doormat, Welcome Doormat Absorbent .</td>
      <td>VEWETOL</td>
      <td>$13.99</td>
      <td>Only 10 left in stock - order soon.</td>
      <td>['Patio, Lawn &amp; Garden',


key: _node_content
string_value:
{"id_": "782b66de-1a7c-47c3-a6a4-c321e0508945", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "f4791e24-686a-4906-9f86-a8cd385120cc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "143d1ff00605bdcd7deef3627aa3385ba87f078aaedf31eeaddec44418405200", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "22b83829-e898-4170-8001-1b14be6c7ed9", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "400e705cc2455242999aa2464caa50a1a69029f691d0dda60e2502afa66f17c5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d8b9aaab-1f41-485e-9a92-1c8a84eea54e", "node_type": "1", "metadata": {}, "hash": "be19546fc0ff96c8598a033ae3a07a08c5989dcdc1075edfc342e19bcd9ebfa0", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": null, "end_char_idx": null, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Lawn &amp; Garden', 'Outdoor Décor', 'Doo.</td>
      <td>https://m.media-amazon.com/images/I/41RgefVq70.</td>
      <td>['https://m.media-amazon.com/images/I/41RgefVq.</td>
      <td>NaN</td>
      <td>.</td>
      <td>Green</td>
      <td>Polyethylene</td>
      <td>Modern</td>
      <td>[]</td>
      <td>[{'Brand': ' MUYETOL '}, {'Size': ' 26.8*26.8 .</td>
      <td>['PLANT REPOTTING MAT SIZE: 26.8" x 26.8", squ.</td>
      <td>NaN</td>
      <td>['Brand: MUYETOL', 'Size: 26.8*26.8', 'Item We.</td>
      <td>b2ede786-3f51-5a45-9a5b-bcf856958cd8</td>
      <td>2024-02-02 15:15:09</td>
    </tr>
    <tr>
      <th>3</th>
      <td>B0C1MRB2M8</td>
      <td>https://www.amazon.com/dp/B0C1MRB2M8</td>
      <td>Pickleball Doormat, Welcome Doormat Absorbent .</td>
      <td>VEWETOL</td>
      <td>$13.99</td>
      <td>Only 10 left in stock - order soon.</td>
      <td>['Patio, Lawn &amp; Garden', 'Outdoor Décor', 'Doo.</td>
      <td>https://m.media-amazon.com/images/I/61vz1Igler.</td>
      <td>['https://m.media-amazon.com/images/I/61vz1Igl.</td>
      <td>NaN</td>
      <td>.</td>
      <td>A5589</td>
      <td>Rubber</td>
      <td>Modern</td>
      <td>[]</td>
      <td>[{'Brand': ' VEWETOL '}, {'Size': ' 16*24INCH .</td>
      <td>['Specifications: 16x24 Inch ', " High-Quality.</td>
      <td>The decorative doormat features a subtle textu.</td>
      <td>['Brand: VEWETOL', 'Size: 16*24INCH', 'Materia.</td>
      <td>8fd9377b-cfa6-5f10-835c-6b8eca2816b5</td>
      <td>2024-02-02 15:15:10</td>
    </tr>
    <tr>
      <th>4</th>
      <td>B0CG1N9QRC</td>
      <td>https://www.amazon.com/dp/B0CG1N9QRC</td>
      <td>JOIN IRON Foldable TV Trays for Eating Set of .</td>
      <td>JOIN IRON Store</td>
      <td>$89.99</td>
      <td>Usually ships within 5 to 6 weeks</td>
      <td>['Home &amp; Kitchen', 'Furniture',


key: _node_content
string_value:
{"id_": "d8b9aaab-1f41-485e-9a92-1c8a84eea54e", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "f4791e24-686a-4906-9f86-a8cd385120cc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "143d1ff00605bdcd7deef3627aa3385ba87f078aaedf31eeaddec44418405200", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "782b66de-1a7c-47c3-a6a4-c321e0508945", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "ca1609fe11f4f0d6412ead3867c8100b3ce7096a62589e38e1b4597b8e35254d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "186bf09f-e92d-43e2-a8e5-a0d8930dc636", "node_type": "1", "metadata": {}, "hash": "615a265bfc3235a916b751393dac9a9e41297b986abe183d367e966f55189c0f", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": null, "end_char_idx": null, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Lawn &amp; Garden', 'Outdoor Décor', 'Doo.</td>
      <td>https://m.media-amazon.com/images/I/61vz1Igler.</td>
      <td>['https://m.media-amazon.com/images/I/61vz1Igl.</td>
      <td>NaN</td>
      <td>.</td>
      <td>A5589</td>
      <td>Rubber</td>
      <td>Modern</td>
      <td>[]</td>
      <td>[{'Brand': ' VEWETOL '}, {'Size': ' 16*24INCH .</td>
      <td>['Specifications: 16x24 Inch ', " High-Quality.</td>
      <td>The decorative doormat features a subtle textu.</td>
      <td>['Brand: VEWETOL', 'Size: 16*24INCH', 'Materia.</td>
      <td>8fd9377b-cfa6-5f10-835c-6b8eca2816b5</td>
      <td>2024-02-02 15:15:10</td>
    </tr>
    <tr>
      <th>4</th>
      <td>B0CG1N9QRC</td>
      <td>https://www.amazon.com/dp/B0CG1N9QRC</td>
      <td>JOIN IRON Foldable TV Trays for Eating Set of .</td>
      <td>JOIN IRON Store</td>
      <td>$89.99</td>
      <td>Usually ships within 5 to 6 weeks</td>
      <td>['Home &amp; Kitchen', 'Furniture', 'Game &amp; Recrea.</td>
      <td>https://m.media-amazon.com/images/I/41p4d4VJnN.</td>
      <td>['https://m.media-amazon.com/images/I/41p4d4VJ.</td>
      <td>NaN</td>
      <td>.</td>
      <td>Grey Set of 4</td>
      <td>Iron</td>
      <td>X Classic Style</td>
      <td>[]</td>
      <td>NaN</td>
      <td>['Includes 4 Folding Tv Tray Tables And one Co.</td>
      <td>Set of Four Folding Trays With Matching Storag.</td>
      <td>['Brand: JOIN IRON', 'Shape: Rectangular', 'In.</td>
      <td>bdc9aa30-9439-50dc-8e89-213ea211d66a</td>
      <td>2024-02-02 15:15:11</td>
    </tr>
  </tbody>
</table>
<p>5 rows × 25 columns</p>
</div>



### Processing step 

Again, we will first prepare our requests with the Chat Completions endpoint, and create the batch file afterwards.


key: _node_content
string_value:
{"id_": "186bf09f-e92d-43e2-a8e5-a0d8930dc636", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "f4791e24-686a-4906-9f86-a8cd385120cc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "143d1ff00605bdcd7deef3627aa3385ba87f078aaedf31eeaddec44418405200", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d8b9aaab-1f41-485e-9a92-1c8a84eea54e", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "a1af3533aca468ea12200188dd3c9658e4c6ccad792d7cdb2bd592edbeeaabb5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6d10137b-4008-4fe4-98c7-015d265348a5", "node_type": "1", "metadata": {}, "hash": "030b165c81347300de68349b06097328256cf66a7cbdb15c01d23bca776b36c2", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": null, "end_char_idx": null, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
amazon.com/dp/B0CG1N9QRC</td>
      <td>JOIN IRON Foldable TV Trays for Eating Set of .</td>
      <td>JOIN IRON Store</td>
      <td>$89.99</td>
      <td>Usually ships within 5 to 6 weeks</td>
      <td>['Home &amp; Kitchen', 'Furniture', 'Game &amp; Recrea.</td>
      <td>https://m.media-amazon.com/images/I/41p4d4VJnN.</td>
      <td>['https://m.media-amazon.com/images/I/41p4d4VJ.</td>
      <td>NaN</td>
      <td>.</td>
      <td>Grey Set of 4</td>
      <td>Iron</td>
      <td>X Classic Style</td>
      <td>[]</td>
      <td>NaN</td>
      <td>['Includes 4 Folding Tv Tray Tables And one Co.</td>
      <td>Set of Four Folding Trays With Matching Storag.</td>
      <td>['Brand: JOIN IRON', 'Shape: Rectangular', 'In.</td>
      <td>bdc9aa30-9439-50dc-8e89-213ea211d66a</td>
      <td>2024-02-02 15:15:11</td>
    </tr>
  </tbody>
</table>
<p>5 rows × 25 columns</p>
</div>



### Processing step 

Again, we will first prepare our requests with the Chat Completions endpoint, and create the batch file afterwards.


```python
caption_system_prompt = '''
Your goal is to generate short, descriptive captions for images of items.
You will be provided with an item image and the name of that item and you will output a caption that captures the most important information about the item.
If there are multiple items depicted, refer to the name provided to understand which item you should describe.
Your generated caption should be short (1 sentence), and include only the most important information about the item.
The most important information could be: the type of item, the style (if mentioned), the material or color if especially relevant and/or any distinctive features.
Keep it short and to the point.
'''

def get_caption(img_url, title):
    response = client.chat.completions.create(
    model="gpt-4o-mini",
    temperature=0.2,
    max_tokens=300,
    messages=[
        {
            "role": "system",
            "content": caption_system_prompt
        },
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": title
                },
                # The content type should be "image_url" to use gpt-4-turbo's vision capabilities
                {
                    "type": "image_url",
                    "image_url": {
                        "url": img_url
                    }
                },
            ],
        }
    ]
    )

    return response.choices[0].message.content
```


```python
# Testing on a few images
for _, row in df[:5].iterrows():
    img_url = row['primary_image']
    caption = get_caption(img_url, row['title'])
    img = Image(url=img_url)
    display(img)
    print(f"CAPTION: {caption}\n\n")
```


<img src="https://m.media-amazon.com/images/I/416WaLx10jL._SS522_.jpg"/>


key: _node_content
string_value:
{"id_": "6d10137b-4008-4fe4-98c7-015d265348a5", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "f4791e24-686a-4906-9f86-a8cd385120cc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "143d1ff00605bdcd7deef3627aa3385ba87f078aaedf31eeaddec44418405200", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "186bf09f-e92d-43e2-a8e5-a0d8930dc636", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "4bd34e0b0aef9de2c62a87d3ebe0194bfbb16f46e20f656886337cb243aa6426", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "874489fa-8135-4807-8d06-965e01fe6e85", "node_type": "1", "metadata": {}, "hash": "837786bc8cfa394a6cf33ab1f94d8d6ea39824bd18a099d2fefcc6c2db85fa34", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 21366, "end_char_idx": 24465, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
caption_system_prompt = '''
Your goal is to generate short, descriptive captions for images of items.
You will be provided with an item image and the name of that item and you will output a caption that captures the most important information about the item.
If there are multiple items depicted, refer to the name provided to understand which item you should describe.
Your generated caption should be short (1 sentence), and include only the most important information about the item.
The most important information could be: the type of item, the style (if mentioned), the material or color if especially relevant and/or any distinctive features.
Keep it short and to the point.
'''

def get_caption(img_url, title):
    response = client.chat.completions.create(
    model="gpt-4o-mini",
    temperature=0.2,
    max_tokens=300,
    messages=[
        {
            "role": "system",
            "content": caption_system_prompt
        },
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": title
                },
                # The content type should be "image_url" to use gpt-4-turbo's vision capabilities
                {
                    "type": "image_url",
                    "image_url": {
                        "url": img_url
                    }
                },
            ],
        }
    ]
    )

    return response.choices[0].message.content
```


```python
# Testing on a few images
for _, row in df[:5].iterrows():
    img_url = row['primary_image']
    caption = get_caption(img_url, row['title'])
    img = Image(url=img_url)
    display(img)
    print(f"CAPTION: {caption}\n\n")
```


<img src="https://m.media-amazon.com/images/I/416WaLx10jL._SS522_.jpg"/>


    CAPTION: A stylish white free-standing shoe rack featuring multiple layers and eight double hooks, perfect for organizing shoes and accessories in living rooms, bathrooms, or hallways.
    
    



<img src="https://m.media-amazon.com/images/I/31SejUEWY7L._SS522_.jpg"/>


    CAPTION: Set of 2 black leather dining chairs featuring a sleek design with vertical stitching and sturdy wooden legs.
    
    



<img src="https://m.media-amazon.com/images/I/41RgefVq70L._SS522_.jpg"/>


    CAPTION: The MUYETOL Plant Repotting Mat is a waterproof, portable, and foldable gardening work mat measuring 26.8" x 26.8", designed for easy soil changing and indoor transplanting.
    
    



<img src="https://m.media-amazon.com/images/I/61vz1IglerL._SS522_.jpg"/>


    CAPTION: Absorbent non-slip doormat featuring the phrase "It's a good day to play PICKLEBALL" with paddle graphics, measuring 16x24 inches.
    
    



<img src="https://m.media-amazon.com/images/I/41p4d4VJnNL._SS522_.jpg"/>


    CAPTION: Set of 4 foldable TV trays in grey, featuring a compact design with a stand for easy storage, perfect for small spaces.
    
    


### Creating the batch job

As with the first example, we will create an array of json tasks to generate a `jsonl` file and use it to create the batch job.


key: _node_content
string_value:
{"id_": "874489fa-8135-4807-8d06-965e01fe6e85", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "f4791e24-686a-4906-9f86-a8cd385120cc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "143d1ff00605bdcd7deef3627aa3385ba87f078aaedf31eeaddec44418405200", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6d10137b-4008-4fe4-98c7-015d265348a5", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "00a574d2ee59edfc7ab326a44ccb868eb11ad846f58ca1ba2bd3bea87250806b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4acce874-c7f5-4762-bc81-988dc4bd1044", "node_type": "1", "metadata": {}, "hash": "761b184f443df00c375eb8b7b1974b0018950cc81bc5628cead3e0dfaf5791b8", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 23095, "end_char_idx": 26126, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
<img src="https://m.media-amazon.com/images/I/416WaLx10jL._SS522_.jpg"/>


    CAPTION: A stylish white free-standing shoe rack featuring multiple layers and eight double hooks, perfect for organizing shoes and accessories in living rooms, bathrooms, or hallways.
    
    



<img src="https://m.media-amazon.com/images/I/31SejUEWY7L._SS522_.jpg"/>


    CAPTION: Set of 2 black leather dining chairs featuring a sleek design with vertical stitching and sturdy wooden legs.
    
    



<img src="https://m.media-amazon.com/images/I/41RgefVq70L._SS522_.jpg"/>


    CAPTION: The MUYETOL Plant Repotting Mat is a waterproof, portable, and foldable gardening work mat measuring 26.8" x 26.8", designed for easy soil changing and indoor transplanting.
    
    



<img src="https://m.media-amazon.com/images/I/61vz1IglerL._SS522_.jpg"/>


    CAPTION: Absorbent non-slip doormat featuring the phrase "It's a good day to play PICKLEBALL" with paddle graphics, measuring 16x24 inches.
    
    



<img src="https://m.media-amazon.com/images/I/41p4d4VJnNL._SS522_.jpg"/>


    CAPTION: Set of 4 foldable TV trays in grey, featuring a compact design with a stand for easy storage, perfect for small spaces.
    
    


### Creating the batch job

As with the first example, we will create an array of json tasks to generate a `jsonl` file and use it to create the batch job.


```python
# Creating an array of json tasks

tasks = []

for index, row in df.iterrows():
    
    title = row['title']
    img_url = row['primary_image']
    
    task = {
        "custom_id": f"task-{index}",
        "method": "POST",
        "url": "/v1/chat/completions",
        "body": {
            # This is what you would have in your Chat Completions API call
            "model": "gpt-4o-mini",
            "temperature": 0.2,
            "max_tokens": 300,
            "messages": [
                {
                    "role": "system",
                    "content": caption_system_prompt
                },
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "text",
                            "text": title
                        },
                        {
                            "type": "image_url",
                            "image_url": {
                                "url": img_url
                            }
                        },
                    ],
                }
            ]            
        }
    }
    
    tasks.append(task)
```


```python
# Creating the file

file_name = "data/batch_tasks_furniture.jsonl"

with open(file_name, 'w') as file:
    for obj in tasks:
        file.write(json.dumps(obj) + '\n')
```


```python
# Uploading the file 

batch_file = client.files.create(
  file=open(file_name, "rb"),
  purpose="batch"
)
```


```python
# Creating the job

batch_job = client.batches.create(
  input_file_id=batch_file.id,
  endpoint="/v1/chat/completions",
  completion_window="24h"
)
```


key: _node_content
string_value:
{"id_": "4acce874-c7f5-4762-bc81-988dc4bd1044", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "f4791e24-686a-4906-9f86-a8cd385120cc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "143d1ff00605bdcd7deef3627aa3385ba87f078aaedf31eeaddec44418405200", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "874489fa-8135-4807-8d06-965e01fe6e85", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "778956c968dc9640fb2a56e00b92f83208e73c727fdc03c371f7a3c57642f961", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4eef0af1-af76-486e-93be-2dd9fbb6366c", "node_type": "1", "metadata": {}, "hash": "a100e67df780647c9af24d383f5263c9c1e1b5e5badb10e391815715ba829630", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 24310, "end_char_idx": 27662, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
### Creating the batch job

As with the first example, we will create an array of json tasks to generate a `jsonl` file and use it to create the batch job.


```python
# Creating an array of json tasks

tasks = []

for index, row in df.iterrows():
    
    title = row['title']
    img_url = row['primary_image']
    
    task = {
        "custom_id": f"task-{index}",
        "method": "POST",
        "url": "/v1/chat/completions",
        "body": {
            # This is what you would have in your Chat Completions API call
            "model": "gpt-4o-mini",
            "temperature": 0.2,
            "max_tokens": 300,
            "messages": [
                {
                    "role": "system",
                    "content": caption_system_prompt
                },
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "text",
                            "text": title
                        },
                        {
                            "type": "image_url",
                            "image_url": {
                                "url": img_url
                            }
                        },
                    ],
                }
            ]            
        }
    }
    
    tasks.append(task)
```


```python
# Creating the file

file_name = "data/batch_tasks_furniture.jsonl"

with open(file_name, 'w') as file:
    for obj in tasks:
        file.write(json.dumps(obj) + '\n')
```


```python
# Uploading the file 

batch_file = client.files.create(
  file=open(file_name, "rb"),
  purpose="batch"
)
```


```python
# Creating the job

batch_job = client.batches.create(
  input_file_id=batch_file.id,
  endpoint="/v1/chat/completions",
  completion_window="24h"
)
```


```python
batch_job = client.batches.retrieve(batch_job.id)
print(batch_job)
```

### Getting results

As with the first example, we can retrieve results once the batch job is done.

Reminder: the results are not in the same order as in the input file.
Make sure to check the custom_id to match the results against the input requests


```python
# Retrieving result file

result_file_id = batch_job.output_file_id
result = client.files.content(result_file_id).content
```


```python
result_file_name = "data/batch_job_results_furniture.jsonl"

with open(result_file_name, 'wb') as file:
    file.write(result)
```


```python
# Loading data from saved file

results = []
with open(result_file_name, 'r') as file:
    for line in file:
        # Parsing the JSON string into a dict and appending to the list of results
        json_object = json.loads(line.strip())
        results.append(json_object)
```


```python
# Reading only the first results
for res in results[:5]:
    task_id = res['custom_id']
    # Getting index from task id
    index = task_id.split('-')[-1]
    result = res['response']['body']['choices'][0]['message']['content']
    item = df.iloc[int(index)]
    img_url = item['primary_image']
    img = Image(url=img_url)
    display(img)
    print(f"CAPTION: {result}\n\n")
```


<img src="https://m.media-amazon.com/images/I/31FOa-k+EtL._SS522_.jpg"/>


    CAPTION: Brushed brass pedestal towel rack with a sleek, modern design, featuring multiple bars for hanging towels, measuring 25.75 x 14.44 x 32 inches.


key: _node_content
string_value:
{"id_": "4eef0af1-af76-486e-93be-2dd9fbb6366c", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "f4791e24-686a-4906-9f86-a8cd385120cc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "143d1ff00605bdcd7deef3627aa3385ba87f078aaedf31eeaddec44418405200", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4acce874-c7f5-4762-bc81-988dc4bd1044", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/batch_processing.ipynb", "title": "Batch processing with the Batch API", "tokens": 7938, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "773ea5f929976523f1ea28cf0829ad39965175ae43e4b49d09bbb889067a42be", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 26129, "end_char_idx": 29099, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
batch_job = client.batches.retrieve(batch_job.id)
print(batch_job)
```

### Getting results

As with the first example, we can retrieve results once the batch job is done.

Reminder: the results are not in the same order as in the input file.
Make sure to check the custom_id to match the results against the input requests


```python
# Retrieving result file

result_file_id = batch_job.output_file_id
result = client.files.content(result_file_id).content
```


```python
result_file_name = "data/batch_job_results_furniture.jsonl"

with open(result_file_name, 'wb') as file:
    file.write(result)
```


```python
# Loading data from saved file

results = []
with open(result_file_name, 'r') as file:
    for line in file:
        # Parsing the JSON string into a dict and appending to the list of results
        json_object = json.loads(line.strip())
        results.append(json_object)
```


```python
# Reading only the first results
for res in results[:5]:
    task_id = res['custom_id']
    # Getting index from task id
    index = task_id.split('-')[-1]
    result = res['response']['body']['choices'][0]['message']['content']
    item = df.iloc[int(index)]
    img_url = item['primary_image']
    img = Image(url=img_url)
    display(img)
    print(f"CAPTION: {result}\n\n")
```


<img src="https://m.media-amazon.com/images/I/31FOa-k+EtL._SS522_.jpg"/>


    CAPTION: Brushed brass pedestal towel rack with a sleek, modern design, featuring multiple bars for hanging towels, measuring 25.75 x 14.44 x 32 inches.
    
    



<img src="https://m.media-amazon.com/images/I/41z8YktAkGL._SS522_.jpg"/>


    CAPTION: Black round end table featuring a tempered glass top and a metal frame, with a lower shelf for additional storage.
    
    



<img src="https://m.media-amazon.com/images/I/511N0PuE9EL._SS522_.jpg"/>


    CAPTION: Black collapsible and height-adjustable telescoping stool, portable and designed for makeup artists and hairstylists, shown in various stages of folding for easy transport.
    
    



<img src="https://m.media-amazon.com/images/I/31dCSKQ14YL._SS522_.jpg"/>


    CAPTION: Ergonomic pink gaming chair featuring breathable fabric, adjustable height, lumbar support, a footrest, and a swivel recliner function.
    
    



<img src="https://m.media-amazon.com/images/I/51OPfpn9ovL._SS522_.jpg"/>


    CAPTION: A set of two Glitzhome adjustable bar stools featuring a mid-century modern design with swivel seats, PU leather upholstery, and wooden backrests.
    
    


## Wrapping up

In this cookbook, we have seen two examples of how to use the new Batch API, but keep in mind that the Batch API works the same way as the Chat Completions endpoint, supporting the same parameters and most of the recent models (gpt-4o, gpt-4o-mini, gpt-4-turbo, gpt-3.5-turbo...).

By using this API, you can significantly reduce costs, so we recommend switching every workload that can happen async to a batch job with this new API.


key: _node_content
string_value:
{"id_": "5e14eb7b-fe58-4785-a810-05da6efe034b", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "b1fca908-a8b2-46f1-99df-22a9fb835fd9", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "6ab5424c1e34d9cad6deae7e35f5475d8dddeffb23386433668a5e5e5e3c8509", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6a77629e-36e2-4ef9-b488-bb2224716e04", "node_type": "1", "metadata": {}, "hash": "c86dc584f102d4902d6a08323d7227955fd5a4ca1e0f7068c7f3bb4511714465", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2543, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# How to fine-tune chat models

Fine-tuning improves the model by training on many more examples than can fit in a prompt, letting you achieve better results on a wide number of tasks. This notebook provides a step-by-step guide for our new GPT-4o mini fine-tuning. We'll perform entity extraction using the [RecipeNLG dataset](https://github.com/Glorf/recipenlg), which provides various recipes and a list of extracted generic ingredients for each. This is a common dataset for named entity recognition (NER) tasks.

Note: **GPT-4o mini fine-tuning is available to developers in our [Tier 4 and 5 usage tiers](https://platform.openai.com/docs/guides/rate-limits/usage-tiers).** You can start fine-tuning GPT-4o mini by visiting your fine-tuning dashboard, clicking "create", and selecting “gpt-4o-mini-2024-07-18” from the base model drop-down.

We will go through the following steps:

1. **Setup:** Loading our dataset and filtering down to one domain to fine-tune on.
2. **Data preparation:** Preparing your data for fine-tuning by creating training and validation examples, and uploading them to the `Files` endpoint.
3. **Fine-tuning:** Creating your fine-tuned model.
4. **Inference:** Using your fine-tuned model for inference on new inputs.

By the end of this you should be able to train, evaluate and deploy a fine-tuned `gpt-4o-mini-2024-07-18` model.

For more information on fine-tuning, you can refer to our [documentation guide](https://platform.openai.com/docs/guides/fine-tuning) or [API reference](https://platform.openai.com/docs/api-reference/fine-tuning).


## Setup



```python
# make sure to use the latest version of the openai python package
!pip install --upgrade --quiet openai
```


```python
import json
import openai
import os
import pandas as pd
from pprint import pprint

client = openai.OpenAI(
    api_key=os.environ.get("OPENAI_API_KEY"),
    organization="<org id>",
    project="<project id>",
)
```

Fine-tuning works best when focused on a particular domain. It's important to make sure your dataset is both focused enough for the model to learn, but general enough that unseen examples won't be missed. Having this in mind, we have extracted a subset from the RecipesNLG dataset to only contain documents from [cookbooks.com](https://cookbooks.com/).



```python
# Read in the dataset we'll use for this task.
# This will be the RecipesNLG dataset, which we've cleaned to only contain documents from www.cookbooks.com
recipe_df = pd.read_csv("data/cookbook_recipes_nlg_10k.csv")

recipe_df.head()
```


key: _node_content
string_value:
{"id_": "6a77629e-36e2-4ef9-b488-bb2224716e04", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "b1fca908-a8b2-46f1-99df-22a9fb835fd9", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "6ab5424c1e34d9cad6deae7e35f5475d8dddeffb23386433668a5e5e5e3c8509", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5e14eb7b-fe58-4785-a810-05da6efe034b", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "91daa5a3fa0c5171155a487f411779829464e62a21cce4200449ac9f47210e82", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9faac27e-b77d-4b8e-be63-1c0d1cf99426", "node_type": "1", "metadata": {}, "hash": "5b4f1097917b2acb5c1a0ed444aec0aff4ab79093f31dc26597914d91042ff98", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1580, "end_char_idx": 3945, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
## Setup



```python
# make sure to use the latest version of the openai python package
!pip install --upgrade --quiet openai
```


```python
import json
import openai
import os
import pandas as pd
from pprint import pprint

client = openai.OpenAI(
    api_key=os.environ.get("OPENAI_API_KEY"),
    organization="<org id>",
    project="<project id>",
)
```

Fine-tuning works best when focused on a particular domain. It's important to make sure your dataset is both focused enough for the model to learn, but general enough that unseen examples won't be missed. Having this in mind, we have extracted a subset from the RecipesNLG dataset to only contain documents from [cookbooks.com](https://cookbooks.com/).



```python
# Read in the dataset we'll use for this task.
# This will be the RecipesNLG dataset, which we've cleaned to only contain documents from www.cookbooks.com
recipe_df = pd.read_csv("data/cookbook_recipes_nlg_10k.csv")

recipe_df.head()
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>title</th>
      <th>ingredients</th>
      <th>directions</th>
      <th>link</th>
      <th>source</th>
      <th>NER</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>No-Bake Nut Cookies</td>
      <td>["1 c. firmly packed brown sugar", "1/2 c. eva...</td>
      <td>["In a heavy 2-quart saucepan, mix brown sugar...</td>
      <td>www.cookbooks.com/Recipe-Details.aspx?id=44874</td>
      <td>www.cookbooks.com</td>
      <td>["brown sugar", "milk", "vanilla", "nuts", "bu...</td>
    </tr>
    <tr>
      <th>1</th>
      <td>Jewell Ball'S Chicken</td>
      <td>["1 small jar chipped beef, cut up", "4 boned ...</td>
      <td>["Place chipped beef on bottom of baking dish....</td>
      <td>www.cookbooks.com/Recipe-Details.aspx?id=699419</td>
      <td>www.cookbooks.com</td>
      <td>["beef", "chicken breasts", "cream of mushroom...</td>
    </tr>
    <tr>
      <th>2</th>
      <td>Creamy Corn</td>
      <td>["2 (16 oz.) pkg. frozen corn", "1 (8 oz.) pkg...</td>
      <td>["In a slow cooker, combine all ingredients.


key: _node_content
string_value:
{"id_": "9faac27e-b77d-4b8e-be63-1c0d1cf99426", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "b1fca908-a8b2-46f1-99df-22a9fb835fd9", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "6ab5424c1e34d9cad6deae7e35f5475d8dddeffb23386433668a5e5e5e3c8509", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6a77629e-36e2-4ef9-b488-bb2224716e04", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "0ef395b625150d129b410bf4e24ce35e3faaa49c578dbd86c48a379267f5be56", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e25032fd-7ebc-4303-9beb-28f94c3f023e", "node_type": "1", "metadata": {}, "hash": "c26544e0cd9487c7a5bb348b6b38075ee50a7452b7f7d59f430aaf4ae091db57", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3849, "end_char_idx": 6484, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
pkg. frozen corn", "1 (8 oz.) pkg...</td>
      <td>["In a slow cooker, combine all ingredients. C...</td>
      <td>www.cookbooks.com/Recipe-Details.aspx?id=10570</td>
      <td>www.cookbooks.com</td>
      <td>["frozen corn", "cream cheese", "butter", "gar...</td>
    </tr>
    <tr>
      <th>3</th>
      <td>Chicken Funny</td>
      <td>["1 large whole chicken", "2 (10 1/2 oz.) cans...</td>
      <td>["Boil and debone chicken.", "Put bite size pi...</td>
      <td>www.cookbooks.com/Recipe-Details.aspx?id=897570</td>
      <td>www.cookbooks.com</td>
      <td>["chicken", "chicken gravy", "cream of mushroo...</td>
    </tr>
    <tr>
      <th>4</th>
      <td>Reeses Cups(Candy)</td>
      <td>["1 c. peanut butter", "3/4 c. graham cracker ...</td>
      <td>["Combine first four ingredients and press in ...</td>
      <td>www.cookbooks.com/Recipe-Details.aspx?id=659239</td>
      <td>www.cookbooks.com</td>
      <td>["peanut butter", "graham cracker crumbs", "bu...</td>
    </tr>
  </tbody>
</table>
</div>



## Data preparation

We'll begin by preparing our data. When fine-tuning with the `ChatCompletion` format, each training example is a simple list of `messages`. For example, an entry could look like:

```
[{'role': 'system',
  'content': 'You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided.'},

 {'role': 'user',
  'content': 'Title: No-Bake Nut Cookies\n\nIngredients: ["1 c. firmly packed brown sugar", "1/2 c. evaporated milk", "1/2 tsp. vanilla", "1/2 c. broken nuts (pecans)", "2 Tbsp. butter or margarine", "3 1/2 c. bite size shredded rice biscuits"]\n\nGeneric ingredients: '},

 {'role': 'assistant',
  'content': '["brown sugar", "milk", "vanilla", "nuts", "butter", "bite size shredded rice biscuits"]'}]
```

During the training process this conversation will be split, with the final entry being the `completion` that the model will produce, and the remainder of the `messages` acting as the prompt. Consider this when building your training examples - if your model will act on multi-turn conversations, then please provide representative examples so it doesn't perform poorly when the conversation starts to expand.

Please note that currently there is a 4096 token limit for each training example. Anything longer than this will be truncated at 4096 tokens.



```python
system_message = "You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided."


def create_user_message(row):
    return f"Title: {row['title']}\n\nIngredients: {row['ingredients']}\n\nGeneric ingredients: "


key: _node_content
string_value:
{"id_": "e25032fd-7ebc-4303-9beb-28f94c3f023e", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "b1fca908-a8b2-46f1-99df-22a9fb835fd9", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "6ab5424c1e34d9cad6deae7e35f5475d8dddeffb23386433668a5e5e5e3c8509", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9faac27e-b77d-4b8e-be63-1c0d1cf99426", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "366e6add21fbcdf4c037a2db0e18db1af4ce9b1d35126c7e971841dd55cd2a8f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b1f51520-949f-48b5-9027-282efbc7bf0b", "node_type": "1", "metadata": {}, "hash": "b551c0abfdfe8eea9f7758ed3a21185e68cabd23e0a597a482293d5b9e77cdbf", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 4873, "end_char_idx": 8126, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
## Data preparation

We'll begin by preparing our data. When fine-tuning with the `ChatCompletion` format, each training example is a simple list of `messages`. For example, an entry could look like:

```
[{'role': 'system',
  'content': 'You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided.'},

 {'role': 'user',
  'content': 'Title: No-Bake Nut Cookies\n\nIngredients: ["1 c. firmly packed brown sugar", "1/2 c. evaporated milk", "1/2 tsp. vanilla", "1/2 c. broken nuts (pecans)", "2 Tbsp. butter or margarine", "3 1/2 c. bite size shredded rice biscuits"]\n\nGeneric ingredients: '},

 {'role': 'assistant',
  'content': '["brown sugar", "milk", "vanilla", "nuts", "butter", "bite size shredded rice biscuits"]'}]
```

During the training process this conversation will be split, with the final entry being the `completion` that the model will produce, and the remainder of the `messages` acting as the prompt. Consider this when building your training examples - if your model will act on multi-turn conversations, then please provide representative examples so it doesn't perform poorly when the conversation starts to expand.

Please note that currently there is a 4096 token limit for each training example. Anything longer than this will be truncated at 4096 tokens.



```python
system_message = "You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided."


def create_user_message(row):
    return f"Title: {row['title']}\n\nIngredients: {row['ingredients']}\n\nGeneric ingredients: "


def prepare_example_conversation(row):
    return {
        "messages": [
            {"role": "system", "content": system_message},
            {"role": "user", "content": create_user_message(row)},
            {"role": "assistant", "content": row["NER"]},
        ]
    }


pprint(prepare_example_conversation(recipe_df.iloc[0]))
```

    {'messages': [{'content': 'You are a helpful recipe assistant. You are to '
                              'extract the generic ingredients from each of the '
                              'recipes provided.',
                   'role': 'system'},
                  {'content': 'Title: No-Bake Nut Cookies\n'
                              '\n'
                              'Ingredients: ["1 c. firmly packed brown sugar", '
                              '"1/2 c. evaporated milk", "1/2 tsp. vanilla", "1/2 '
                              'c. broken nuts (pecans)", "2 Tbsp. butter or '
                              'margarine", "3 1/2 c. bite size shredded rice '
                              'biscuits"]\n'
                              '\n'
                              'Generic ingredients: ',
                   'role': 'user'},
                  {'content': '["brown sugar", "milk", "vanilla", "nuts", '
                              '"butter", "bite size shredded rice biscuits"]',
                   'role': 'assistant'}]}


Let's now do this for a subset of the dataset to use as our training data. You can begin with even 30-50 well-pruned examples. You should see performance continue to scale linearly as you increase the size of the training set, but your jobs will also take longer.


key: _node_content
string_value:
{"id_": "b1f51520-949f-48b5-9027-282efbc7bf0b", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "b1fca908-a8b2-46f1-99df-22a9fb835fd9", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "6ab5424c1e34d9cad6deae7e35f5475d8dddeffb23386433668a5e5e5e3c8509", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e25032fd-7ebc-4303-9beb-28f94c3f023e", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "588683e3ea9c46ff7a2e090526512010be2675f0deb29d5345080d0704b52b6f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9baa4133-d830-4e0f-9972-1e1e66c359e0", "node_type": "1", "metadata": {}, "hash": "7a946e6404cb2b1151ac8dfb76b3aaa9b42894ff2c51842a89da0767d4960775", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 6357, "end_char_idx": 9193, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
def create_user_message(row):
    return f"Title: {row['title']}\n\nIngredients: {row['ingredients']}\n\nGeneric ingredients: "


def prepare_example_conversation(row):
    return {
        "messages": [
            {"role": "system", "content": system_message},
            {"role": "user", "content": create_user_message(row)},
            {"role": "assistant", "content": row["NER"]},
        ]
    }


pprint(prepare_example_conversation(recipe_df.iloc[0]))
```

    {'messages': [{'content': 'You are a helpful recipe assistant. You are to '
                              'extract the generic ingredients from each of the '
                              'recipes provided.',
                   'role': 'system'},
                  {'content': 'Title: No-Bake Nut Cookies\n'
                              '\n'
                              'Ingredients: ["1 c. firmly packed brown sugar", '
                              '"1/2 c. evaporated milk", "1/2 tsp. vanilla", "1/2 '
                              'c. broken nuts (pecans)", "2 Tbsp. butter or '
                              'margarine", "3 1/2 c. bite size shredded rice '
                              'biscuits"]\n'
                              '\n'
                              'Generic ingredients: ',
                   'role': 'user'},
                  {'content': '["brown sugar", "milk", "vanilla", "nuts", '
                              '"butter", "bite size shredded rice biscuits"]',
                   'role': 'assistant'}]}


Let's now do this for a subset of the dataset to use as our training data. You can begin with even 30-50 well-pruned examples. You should see performance continue to scale linearly as you increase the size of the training set, but your jobs will also take longer.



```python
# use the first 100 rows of the dataset for training
training_df = recipe_df.loc[0:100]

# apply the prepare_example_conversation function to each row of the training_df
training_data = training_df.apply(prepare_example_conversation, axis=1).tolist()

for example in training_data[:5]:
    print(example)
```

    {'messages': [{'role': 'system', 'content': 'You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided.'}, {'role': 'user', 'content': 'Title: No-Bake Nut Cookies\n\nIngredients: ["1 c. firmly packed brown sugar", "1/2 c. evaporated milk", "1/2 tsp. vanilla", "1/2 c. broken nuts (pecans)", "2 Tbsp. butter or margarine", "3 1/2 c. bite size shredded rice biscuits"]\n\nGeneric ingredients: '}, {'role': 'assistant', 'content': '["brown sugar", "milk", "vanilla", "nuts", "butter", "bite size shredded rice biscuits"]'}]}
    {'messages': [{'role': 'system', 'content': 'You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided.


key: _node_content
string_value:
{"id_": "9baa4133-d830-4e0f-9972-1e1e66c359e0", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "b1fca908-a8b2-46f1-99df-22a9fb835fd9", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "6ab5424c1e34d9cad6deae7e35f5475d8dddeffb23386433668a5e5e5e3c8509", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b1f51520-949f-48b5-9027-282efbc7bf0b", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "1e7d76a3571d814b8bdcfe48053ae119e9d5f3f7f3d8bddca0cc5b14037440f0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "cf709b02-b333-495c-8a2e-b90bdc5ddcdc", "node_type": "1", "metadata": {}, "hash": "a462f0eb5e784154e2b3d3b340a7d1170956ee99421fa0b7e530f49021b1dad0", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 7863, "end_char_idx": 10436, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Let's now do this for a subset of the dataset to use as our training data. You can begin with even 30-50 well-pruned examples. You should see performance continue to scale linearly as you increase the size of the training set, but your jobs will also take longer.



```python
# use the first 100 rows of the dataset for training
training_df = recipe_df.loc[0:100]

# apply the prepare_example_conversation function to each row of the training_df
training_data = training_df.apply(prepare_example_conversation, axis=1).tolist()

for example in training_data[:5]:
    print(example)
```

    {'messages': [{'role': 'system', 'content': 'You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided.'}, {'role': 'user', 'content': 'Title: No-Bake Nut Cookies\n\nIngredients: ["1 c. firmly packed brown sugar", "1/2 c. evaporated milk", "1/2 tsp. vanilla", "1/2 c. broken nuts (pecans)", "2 Tbsp. butter or margarine", "3 1/2 c. bite size shredded rice biscuits"]\n\nGeneric ingredients: '}, {'role': 'assistant', 'content': '["brown sugar", "milk", "vanilla", "nuts", "butter", "bite size shredded rice biscuits"]'}]}
    {'messages': [{'role': 'system', 'content': 'You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided.'}, {'role': 'user', 'content': 'Title: Jewell Ball\'S Chicken\n\nIngredients: ["1 small jar chipped beef, cut up", "4 boned chicken breasts", "1 can cream of mushroom soup", "1 carton sour cream"]\n\nGeneric ingredients: '}, {'role': 'assistant', 'content': '["beef", "chicken breasts", "cream of mushroom soup", "sour cream"]'}]}
    {'messages': [{'role': 'system', 'content': 'You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided.'}, {'role': 'user', 'content': 'Title: Creamy Corn\n\nIngredients: ["2 (16 oz.) pkg. frozen corn", "1 (8 oz.) pkg. cream cheese, cubed", "1/3 c. butter, cubed", "1/2 tsp. garlic powder", "1/2 tsp. salt", "1/4 tsp. pepper"]\n\nGeneric ingredients: '}, {'role': 'assistant', 'content': '["frozen corn", "cream cheese", "butter", "garlic powder", "salt", "pepper"]'}]}
    {'messages': [{'role': 'system', 'content': 'You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided.'}, {'role': 'user', 'content': 'Title: Chicken Funny\n\nIngredients: ["1 large whole chicken", "2 (10 1/2 oz.) cans chicken gravy", "1 (10 1/2 oz.) can cream of mushroom soup", "1 (6 oz.) box Stove Top stuffing", "4 oz.


key: _node_content
string_value:
{"id_": "cf709b02-b333-495c-8a2e-b90bdc5ddcdc", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "b1fca908-a8b2-46f1-99df-22a9fb835fd9", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "6ab5424c1e34d9cad6deae7e35f5475d8dddeffb23386433668a5e5e5e3c8509", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9baa4133-d830-4e0f-9972-1e1e66c359e0", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "6e7b0ea03c990eabd302e8bcc87066ef7d3672a4e8236619bb5c2f1d1937abd5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "55501597-192a-4c82-b370-9311ef013f46", "node_type": "1", "metadata": {}, "hash": "9208ea71be36cfec36d584e857f34148846be494cd61eb2b4ffce56ebfad8b80", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 9116, "end_char_idx": 11767, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
You are to extract the generic ingredients from each of the recipes provided.'}, {'role': 'user', 'content': 'Title: Jewell Ball\'S Chicken\n\nIngredients: ["1 small jar chipped beef, cut up", "4 boned chicken breasts", "1 can cream of mushroom soup", "1 carton sour cream"]\n\nGeneric ingredients: '}, {'role': 'assistant', 'content': '["beef", "chicken breasts", "cream of mushroom soup", "sour cream"]'}]}
    {'messages': [{'role': 'system', 'content': 'You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided.'}, {'role': 'user', 'content': 'Title: Creamy Corn\n\nIngredients: ["2 (16 oz.) pkg. frozen corn", "1 (8 oz.) pkg. cream cheese, cubed", "1/3 c. butter, cubed", "1/2 tsp. garlic powder", "1/2 tsp. salt", "1/4 tsp. pepper"]\n\nGeneric ingredients: '}, {'role': 'assistant', 'content': '["frozen corn", "cream cheese", "butter", "garlic powder", "salt", "pepper"]'}]}
    {'messages': [{'role': 'system', 'content': 'You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided.'}, {'role': 'user', 'content': 'Title: Chicken Funny\n\nIngredients: ["1 large whole chicken", "2 (10 1/2 oz.) cans chicken gravy", "1 (10 1/2 oz.) can cream of mushroom soup", "1 (6 oz.) box Stove Top stuffing", "4 oz. shredded cheese"]\n\nGeneric ingredients: '}, {'role': 'assistant', 'content': '["chicken", "chicken gravy", "cream of mushroom soup", "shredded cheese"]'}]}
    {'messages': [{'role': 'system', 'content': 'You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided.'}, {'role': 'user', 'content': 'Title: Reeses Cups(Candy)  \n\nIngredients: ["1 c. peanut butter", "3/4 c. graham cracker crumbs", "1 c. melted butter", "1 lb. (3 1/2 c.) powdered sugar", "1 large pkg. chocolate chips"]\n\nGeneric ingredients: '}, {'role': 'assistant', 'content': '["peanut butter", "graham cracker crumbs", "butter", "powdered sugar", "chocolate chips"]'}]}


In addition to training data, we can also **optionally** provide validation data, which will be used to make sure that the model does not overfit your training set.



```python
validation_df = recipe_df.loc[101:200]
validation_data = validation_df.apply(
    prepare_example_conversation, axis=1).tolist()
```

We then need to save our data as `.jsonl` files, with each line being one training example conversation.



```python
def write_jsonl(data_list: list, filename: str) -> None:
    with open(filename, "w") as out:
        for ddict in data_list:
            jout = json.dumps(ddict) + "\n"
            out.write(jout)
```


key: _node_content
string_value:
{"id_": "55501597-192a-4c82-b370-9311ef013f46", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "b1fca908-a8b2-46f1-99df-22a9fb835fd9", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "6ab5424c1e34d9cad6deae7e35f5475d8dddeffb23386433668a5e5e5e3c8509", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "cf709b02-b333-495c-8a2e-b90bdc5ddcdc", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "8a4928c1c9587869a375971ef4e511218427a7ac43428cfe38aeb8bb1c422a81", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f2be088e-228e-45b1-bea5-b8d08ccf6e46", "node_type": "1", "metadata": {}, "hash": "54b4be081534789424611182cb1ea01f2684e6c1a267afafc2958927bc25b0f5", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 10365, "end_char_idx": 12954, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
can cream of mushroom soup", "1 (6 oz.) box Stove Top stuffing", "4 oz. shredded cheese"]\n\nGeneric ingredients: '}, {'role': 'assistant', 'content': '["chicken", "chicken gravy", "cream of mushroom soup", "shredded cheese"]'}]}
    {'messages': [{'role': 'system', 'content': 'You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided.'}, {'role': 'user', 'content': 'Title: Reeses Cups(Candy)  \n\nIngredients: ["1 c. peanut butter", "3/4 c. graham cracker crumbs", "1 c. melted butter", "1 lb. (3 1/2 c.) powdered sugar", "1 large pkg. chocolate chips"]\n\nGeneric ingredients: '}, {'role': 'assistant', 'content': '["peanut butter", "graham cracker crumbs", "butter", "powdered sugar", "chocolate chips"]'}]}


In addition to training data, we can also **optionally** provide validation data, which will be used to make sure that the model does not overfit your training set.



```python
validation_df = recipe_df.loc[101:200]
validation_data = validation_df.apply(
    prepare_example_conversation, axis=1).tolist()
```

We then need to save our data as `.jsonl` files, with each line being one training example conversation.



```python
def write_jsonl(data_list: list, filename: str) -> None:
    with open(filename, "w") as out:
        for ddict in data_list:
            jout = json.dumps(ddict) + "\n"
            out.write(jout)
```


```python
training_file_name = "tmp_recipe_finetune_training.jsonl"
write_jsonl(training_data, training_file_name)

validation_file_name = "tmp_recipe_finetune_validation.jsonl"
write_jsonl(validation_data, validation_file_name)
```

This is what the first 5 lines of our training `.jsonl` file look like:



```python
# print the first 5 lines of the training file
!head -n 5 tmp_recipe_finetune_training.jsonl
```

    {"messages": [{"role": "system", "content": "You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided."}, {"role": "user", "content": "Title: No-Bake Nut Cookies\n\nIngredients: [\"1 c. firmly packed brown sugar\", \"1/2 c. evaporated milk\", \"1/2 tsp. vanilla\", \"1/2 c. broken nuts (pecans)\", \"2 Tbsp. butter or margarine\", \"3 1/2 c. bite size shredded rice biscuits\"]\n\nGeneric ingredients: "}, {"role": "assistant", "content": "[\"brown sugar\", \"milk\", \"vanilla\", \"nuts\", \"butter\", \"bite size shredded rice biscuits\"]"}]}
    {"messages": [{"role": "system", "content": "You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided.


key: _node_content
string_value:
{"id_": "f2be088e-228e-45b1-bea5-b8d08ccf6e46", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "b1fca908-a8b2-46f1-99df-22a9fb835fd9", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "6ab5424c1e34d9cad6deae7e35f5475d8dddeffb23386433668a5e5e5e3c8509", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "55501597-192a-4c82-b370-9311ef013f46", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "6657808e1355f20f511c4307a490687b49bb763a8317c50d8a89f733d25ae628", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "80a825f8-9ee1-4aec-912c-922370ad171a", "node_type": "1", "metadata": {}, "hash": "5e81877bc99425c24d8448def062cc8df67e144f7fe799385adcb26bbba6cd45", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 11556, "end_char_idx": 14245, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
def write_jsonl(data_list: list, filename: str) -> None:
    with open(filename, "w") as out:
        for ddict in data_list:
            jout = json.dumps(ddict) + "\n"
            out.write(jout)
```


```python
training_file_name = "tmp_recipe_finetune_training.jsonl"
write_jsonl(training_data, training_file_name)

validation_file_name = "tmp_recipe_finetune_validation.jsonl"
write_jsonl(validation_data, validation_file_name)
```

This is what the first 5 lines of our training `.jsonl` file look like:



```python
# print the first 5 lines of the training file
!head -n 5 tmp_recipe_finetune_training.jsonl
```

    {"messages": [{"role": "system", "content": "You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided."}, {"role": "user", "content": "Title: No-Bake Nut Cookies\n\nIngredients: [\"1 c. firmly packed brown sugar\", \"1/2 c. evaporated milk\", \"1/2 tsp. vanilla\", \"1/2 c. broken nuts (pecans)\", \"2 Tbsp. butter or margarine\", \"3 1/2 c. bite size shredded rice biscuits\"]\n\nGeneric ingredients: "}, {"role": "assistant", "content": "[\"brown sugar\", \"milk\", \"vanilla\", \"nuts\", \"butter\", \"bite size shredded rice biscuits\"]"}]}
    {"messages": [{"role": "system", "content": "You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided."}, {"role": "user", "content": "Title: Jewell Ball'S Chicken\n\nIngredients: [\"1 small jar chipped beef, cut up\", \"4 boned chicken breasts\", \"1 can cream of mushroom soup\", \"1 carton sour cream\"]\n\nGeneric ingredients: "}, {"role": "assistant", "content": "[\"beef\", \"chicken breasts\", \"cream of mushroom soup\", \"sour cream\"]"}]}
    {"messages": [{"role": "system", "content": "You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided."}, {"role": "user", "content": "Title: Creamy Corn\n\nIngredients: [\"2 (16 oz.) pkg. frozen corn\", \"1 (8 oz.) pkg. cream cheese, cubed\", \"1/3 c. butter, cubed\", \"1/2 tsp. garlic powder\", \"1/2 tsp. salt\", \"1/4 tsp. pepper\"]\n\nGeneric ingredients: "}, {"role": "assistant", "content": "[\"frozen corn\", \"cream cheese\", \"butter\", \"garlic powder\", \"salt\", \"pepper\"]"}]}
    {"messages": [{"role": "system", "content": "You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided."}, {"role": "user", "content": "Title: Chicken Funny\n\nIngredients: [\"1 large whole chicken\", \"2 (10 1/2 oz.) cans chicken gravy\", \"1 (10 1/2 oz.) can cream of mushroom soup\", \"1 (6 oz.) box Stove Top stuffing\", \"4 oz.


key: _node_content
string_value:
{"id_": "80a825f8-9ee1-4aec-912c-922370ad171a", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "b1fca908-a8b2-46f1-99df-22a9fb835fd9", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "6ab5424c1e34d9cad6deae7e35f5475d8dddeffb23386433668a5e5e5e3c8509", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f2be088e-228e-45b1-bea5-b8d08ccf6e46", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "09c8fa16ed78eb6476af520999e2837cff73b6b9f81966f44ab3a84684861aab", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "825c41a1-f3fe-4619-a5ce-616c59da64ae", "node_type": "1", "metadata": {}, "hash": "73b9730ffe4fcc04e99a7ba4ab6a12301b5274678c55a5abd3c426f94afeeab0", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 12877, "end_char_idx": 15283, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
You are to extract the generic ingredients from each of the recipes provided."}, {"role": "user", "content": "Title: Jewell Ball'S Chicken\n\nIngredients: [\"1 small jar chipped beef, cut up\", \"4 boned chicken breasts\", \"1 can cream of mushroom soup\", \"1 carton sour cream\"]\n\nGeneric ingredients: "}, {"role": "assistant", "content": "[\"beef\", \"chicken breasts\", \"cream of mushroom soup\", \"sour cream\"]"}]}
    {"messages": [{"role": "system", "content": "You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided."}, {"role": "user", "content": "Title: Creamy Corn\n\nIngredients: [\"2 (16 oz.) pkg. frozen corn\", \"1 (8 oz.) pkg. cream cheese, cubed\", \"1/3 c. butter, cubed\", \"1/2 tsp. garlic powder\", \"1/2 tsp. salt\", \"1/4 tsp. pepper\"]\n\nGeneric ingredients: "}, {"role": "assistant", "content": "[\"frozen corn\", \"cream cheese\", \"butter\", \"garlic powder\", \"salt\", \"pepper\"]"}]}
    {"messages": [{"role": "system", "content": "You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided."}, {"role": "user", "content": "Title: Chicken Funny\n\nIngredients: [\"1 large whole chicken\", \"2 (10 1/2 oz.) cans chicken gravy\", \"1 (10 1/2 oz.) can cream of mushroom soup\", \"1 (6 oz.) box Stove Top stuffing\", \"4 oz. shredded cheese\"]\n\nGeneric ingredients: "}, {"role": "assistant", "content": "[\"chicken\", \"chicken gravy\", \"cream of mushroom soup\", \"shredded cheese\"]"}]}
    {"messages": [{"role": "system", "content": "You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided."}, {"role": "user", "content": "Title: Reeses Cups(Candy)  \n\nIngredients: [\"1 c. peanut butter\", \"3/4 c. graham cracker crumbs\", \"1 c. melted butter\", \"1 lb. (3 1/2 c.) powdered sugar\", \"1 large pkg. chocolate chips\"]\n\nGeneric ingredients: "}, {"role": "assistant", "content": "[\"peanut butter\", \"graham cracker crumbs\", \"butter\", \"powdered sugar\", \"chocolate chips\"]"}]}


### Upload files

You can now upload the files to our `Files` endpoint to be used by the fine-tuned model.



```python
def upload_file(file_name: str, purpose: str) -> str:
    with open(file_name, "rb") as file_fd:
        response = client.files.create(file=file_fd, purpose=purpose)
    return response.id


key: _node_content
string_value:
{"id_": "825c41a1-f3fe-4619-a5ce-616c59da64ae", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "b1fca908-a8b2-46f1-99df-22a9fb835fd9", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "6ab5424c1e34d9cad6deae7e35f5475d8dddeffb23386433668a5e5e5e3c8509", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "80a825f8-9ee1-4aec-912c-922370ad171a", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "a14b6272534697a6d79d247c77f68d54cf22b2dbd8ddcfb55cc5acb0a29fc7f7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b53bcc58-eb9d-41d4-a68d-05292ca41e2f", "node_type": "1", "metadata": {}, "hash": "83636768a79fdbf7af00fb74dcc574471ca43ff47663abe84c8e710dd0a97004", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 13939, "end_char_idx": 16358, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
You are to extract the generic ingredients from each of the recipes provided."}, {"role": "user", "content": "Title: Chicken Funny\n\nIngredients: [\"1 large whole chicken\", \"2 (10 1/2 oz.) cans chicken gravy\", \"1 (10 1/2 oz.) can cream of mushroom soup\", \"1 (6 oz.) box Stove Top stuffing\", \"4 oz. shredded cheese\"]\n\nGeneric ingredients: "}, {"role": "assistant", "content": "[\"chicken\", \"chicken gravy\", \"cream of mushroom soup\", \"shredded cheese\"]"}]}
    {"messages": [{"role": "system", "content": "You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided."}, {"role": "user", "content": "Title: Reeses Cups(Candy)  \n\nIngredients: [\"1 c. peanut butter\", \"3/4 c. graham cracker crumbs\", \"1 c. melted butter\", \"1 lb. (3 1/2 c.) powdered sugar\", \"1 large pkg. chocolate chips\"]\n\nGeneric ingredients: "}, {"role": "assistant", "content": "[\"peanut butter\", \"graham cracker crumbs\", \"butter\", \"powdered sugar\", \"chocolate chips\"]"}]}


### Upload files

You can now upload the files to our `Files` endpoint to be used by the fine-tuned model.



```python
def upload_file(file_name: str, purpose: str) -> str:
    with open(file_name, "rb") as file_fd:
        response = client.files.create(file=file_fd, purpose=purpose)
    return response.id


training_file_id = upload_file(training_file_name, "fine-tune")
validation_file_id = upload_file(validation_file_name, "fine-tune")

print("Training file ID:", training_file_id)
print("Validation file ID:", validation_file_id)
```

    Training file ID: file-3wfAfDoYcGrSpaE17qK0vXT0
    Validation file ID: file-HhFhnyGJhazYdPcd3wrtvIoX


## Fine-tuning

Now we can create our fine-tuning job with the generated files and an optional suffix to identify the model. The response will contain an `id` which you can use to retrieve updates on the job.

Note: The files have to first be processed by our system, so you might get a `File not ready` error. In that case, simply retry a few minutes later.



```python
MODEL = "gpt-4o-mini-2024-07-18"

response = client.fine_tuning.jobs.create(
    training_file=training_file_id,
    validation_file=validation_file_id,
    model=MODEL,
    suffix="recipe-ner",
)

job_id = response.id

print("Job ID:", response.id)
print("Status:", response.status)
```

    Job ID: ftjob-UiaiLwGdGBfdLQDBAoQheufN
    Status: validating_files


key: _node_content
string_value:
{"id_": "b53bcc58-eb9d-41d4-a68d-05292ca41e2f", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "b1fca908-a8b2-46f1-99df-22a9fb835fd9", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "6ab5424c1e34d9cad6deae7e35f5475d8dddeffb23386433668a5e5e5e3c8509", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "825c41a1-f3fe-4619-a5ce-616c59da64ae", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "77e51691393497db8802f5e92f6b6584315dfa2dfb93e1ec5612c440a5bce943", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "bdf39518-3d89-4e35-96f6-68c562e57f25", "node_type": "1", "metadata": {}, "hash": "0e59a71316639288d38c7447232beab1bab2ac348cf7c50aaf8d52a82c592347", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 14974, "end_char_idx": 17242, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
### Upload files

You can now upload the files to our `Files` endpoint to be used by the fine-tuned model.



```python
def upload_file(file_name: str, purpose: str) -> str:
    with open(file_name, "rb") as file_fd:
        response = client.files.create(file=file_fd, purpose=purpose)
    return response.id


training_file_id = upload_file(training_file_name, "fine-tune")
validation_file_id = upload_file(validation_file_name, "fine-tune")

print("Training file ID:", training_file_id)
print("Validation file ID:", validation_file_id)
```

    Training file ID: file-3wfAfDoYcGrSpaE17qK0vXT0
    Validation file ID: file-HhFhnyGJhazYdPcd3wrtvIoX


## Fine-tuning

Now we can create our fine-tuning job with the generated files and an optional suffix to identify the model. The response will contain an `id` which you can use to retrieve updates on the job.

Note: The files have to first be processed by our system, so you might get a `File not ready` error. In that case, simply retry a few minutes later.



```python
MODEL = "gpt-4o-mini-2024-07-18"

response = client.fine_tuning.jobs.create(
    training_file=training_file_id,
    validation_file=validation_file_id,
    model=MODEL,
    suffix="recipe-ner",
)

job_id = response.id

print("Job ID:", response.id)
print("Status:", response.status)
```

    Job ID: ftjob-UiaiLwGdGBfdLQDBAoQheufN
    Status: validating_files


#### Check job status

You can make a `GET` request to the `https://api.openai.com/v1/alpha/fine-tunes` endpoint to list your alpha fine-tune jobs. In this instance you'll want to check that the ID you got from the previous step ends up as `status: succeeded`.

Once it is completed, you can use the `result_files` to sample the results from the validation set (if you uploaded one), and use the ID from the `fine_tuned_model` parameter to invoke your trained model.



```python
response = client.fine_tuning.jobs.retrieve(job_id)

print("Job ID:", response.id)
print("Status:", response.status)
print("Trained Tokens:", response.trained_tokens)
```

    Job ID: ftjob-UiaiLwGdGBfdLQDBAoQheufN
    Status: running
    Trained Tokens: None


We can track the progress of the fine-tune with the events endpoint. You can rerun the cell below a few times until the fine-tune is ready.


key: _node_content
string_value:
{"id_": "bdf39518-3d89-4e35-96f6-68c562e57f25", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "b1fca908-a8b2-46f1-99df-22a9fb835fd9", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "6ab5424c1e34d9cad6deae7e35f5475d8dddeffb23386433668a5e5e5e3c8509", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b53bcc58-eb9d-41d4-a68d-05292ca41e2f", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "0044610978303c95aaca7eaf4ae19cebedb4393f9e6fc5645ed29f27cf0e0cfd", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f59d239a-91f7-4bf5-b2f5-b46cbe6bc7fa", "node_type": "1", "metadata": {}, "hash": "b6c6e19d0619cd01641f9562ea00ddceab7ae8d2adeb54e0c6e0a274918340dc", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 15988, "end_char_idx": 18444, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
MODEL = "gpt-4o-mini-2024-07-18"

response = client.fine_tuning.jobs.create(
    training_file=training_file_id,
    validation_file=validation_file_id,
    model=MODEL,
    suffix="recipe-ner",
)

job_id = response.id

print("Job ID:", response.id)
print("Status:", response.status)
```

    Job ID: ftjob-UiaiLwGdGBfdLQDBAoQheufN
    Status: validating_files


#### Check job status

You can make a `GET` request to the `https://api.openai.com/v1/alpha/fine-tunes` endpoint to list your alpha fine-tune jobs. In this instance you'll want to check that the ID you got from the previous step ends up as `status: succeeded`.

Once it is completed, you can use the `result_files` to sample the results from the validation set (if you uploaded one), and use the ID from the `fine_tuned_model` parameter to invoke your trained model.



```python
response = client.fine_tuning.jobs.retrieve(job_id)

print("Job ID:", response.id)
print("Status:", response.status)
print("Trained Tokens:", response.trained_tokens)
```

    Job ID: ftjob-UiaiLwGdGBfdLQDBAoQheufN
    Status: running
    Trained Tokens: None


We can track the progress of the fine-tune with the events endpoint. You can rerun the cell below a few times until the fine-tune is ready.



```python
response = client.fine_tuning.jobs.list_events(job_id)

events = response.data
events.reverse()

for event in events:
    print(event.message)
```

    Step 288/303: training loss=0.00
    Step 289/303: training loss=0.01
    Step 290/303: training loss=0.00, validation loss=0.31
    Step 291/303: training loss=0.00
    Step 292/303: training loss=0.00
    Step 293/303: training loss=0.00
    Step 294/303: training loss=0.00
    Step 295/303: training loss=0.00
    Step 296/303: training loss=0.00
    Step 297/303: training loss=0.00
    Step 298/303: training loss=0.01
    Step 299/303: training loss=0.00
    Step 300/303: training loss=0.00, validation loss=0.04
    Step 301/303: training loss=0.16
    Step 302/303: training loss=0.00
    Step 303/303: training loss=0.00, full validation loss=0.33
    Checkpoint created at step 101 with Snapshot ID: ft:gpt-4o-mini-2024-07-18:openai-gtm:recipe-ner:9o1eNlSa:ckpt-step-101
    Checkpoint created at step 202 with Snapshot ID: ft:gpt-4o-mini-2024-07-18:openai-gtm:recipe-ner:9o1eNFnj:ckpt-step-202
    New fine-tuned model created: ft:gpt-4o-mini-2024-07-18:openai-gtm:recipe-ner:9o1eNNKO
    The job has successfully completed


key: _node_content
string_value:
{"id_": "f59d239a-91f7-4bf5-b2f5-b46cbe6bc7fa", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "b1fca908-a8b2-46f1-99df-22a9fb835fd9", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "6ab5424c1e34d9cad6deae7e35f5475d8dddeffb23386433668a5e5e5e3c8509", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "bdf39518-3d89-4e35-96f6-68c562e57f25", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb", "title": "How to fine-tune chat models", "tokens": 5550, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "03d25c21569a3f888dcdf70da8e0f4a9bcc77cc09a7bd905bcfb9458ffa524b3", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 18447, "end_char_idx": 20499, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Now that it's done, we can get a fine-tuned model ID from the job:



```python
response = client.fine_tuning.jobs.retrieve(job_id)
fine_tuned_model_id = response.fine_tuned_model

if fine_tuned_model_id is None:
    raise RuntimeError(
        "Fine-tuned model ID not found. Your job has likely not been completed yet."
    )

print("Fine-tuned model ID:", fine_tuned_model_id)
```

    Fine-tuned model ID: ft:gpt-4o-mini-2024-07-18:openai-gtm:recipe-ner:9o1eNNKO


## Inference


The last step is to use your fine-tuned model for inference. Similar to the classic `FineTuning`, you simply call `ChatCompletions` with your new fine-tuned model name filling the `model` parameter.



```python
test_df = recipe_df.loc[201:300]
test_row = test_df.iloc[0]
test_messages = []
test_messages.append({"role": "system", "content": system_message})
user_message = create_user_message(test_row)
test_messages.append({"role": "user", "content": user_message})

pprint(test_messages)
```

    [{'content': 'You are a helpful recipe assistant. You are to extract the '
                 'generic ingredients from each of the recipes provided.',
      'role': 'system'},
     {'content': 'Title: Beef Brisket\n'
                 '\n'
                 'Ingredients: ["4 lb. beef brisket", "1 c. catsup", "1 c. water", '
                 '"1/2 onion, minced", "2 Tbsp. cider vinegar", "1 Tbsp. prepared '
                 'horseradish", "1 Tbsp. prepared mustard", "1 tsp. salt", "1/2 '
                 'tsp. pepper"]\n'
                 '\n'
                 'Generic ingredients: ',
      'role': 'user'}]



```python
response = client.chat.completions.create(
    model=fine_tuned_model_id, messages=test_messages, temperature=0, max_tokens=500
)
print(response.choices[0].message.content)
```

    ["beef brisket", "catsup", "water", "onion", "cider vinegar", "horseradish", "mustard", "salt", "pepper"]


## Conclusion

Congratulations, you are now ready to fine-tune your own models using the `ChatCompletion` format! We look forward to seeing what you build


key: _node_content
string_value:
{"id_": "3d870823-5747-45de-a390-3e703a0129a3", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Classification_using_embeddings.ipynb", "title": "split data into train and test", "tokens": 708, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "9f9e4677-9b3c-44c7-a29f-a040e5c711da", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Classification_using_embeddings.ipynb", "title": "split data into train and test", "tokens": 708, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "f25f7cd013b2d972d6996d5b5fab50fa34cc88e9502d5962812e89a9e5ca59a3", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2947, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
## Classification using embeddings

There are many ways to classify text. This notebook shares an example of text classification using embeddings. For many text classification tasks, we've seen fine-tuned models do better than embeddings. See an example of fine-tuned models for classification in [Fine-tuned_classification.ipynb](Fine-tuned_classification.ipynb). We also recommend having more examples than embedding dimensions, which we don't quite achieve here.

In this text classification task, we predict the score of a food review (1 to 5) based on the embedding of the review's text. We split the dataset into a training and a testing set for all the following tasks, so we can realistically evaluate performance on unseen data. The dataset is created in the [Get_embeddings_from_dataset Notebook](Get_embeddings_from_dataset.ipynb).



```python
import pandas as pd
import numpy as np
from ast import literal_eval

from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, accuracy_score

datafile_path = "data/fine_food_reviews_with_embeddings_1k.csv"

df = pd.read_csv(datafile_path)
df["embedding"] = df.embedding.apply(literal_eval).apply(np.array)  # convert string to array

# split data into train and test
X_train, X_test, y_train, y_test = train_test_split(
    list(df.embedding.values), df.Score, test_size=0.2, random_state=42
)

# train random forest classifier
clf = RandomForestClassifier(n_estimators=100)
clf.fit(X_train, y_train)
preds = clf.predict(X_test)
probas = clf.predict_proba(X_test)

report = classification_report(y_test, preds)
print(report)

```

                  precision    recall  f1-score   support
    
               1       0.90      0.45      0.60        20
               2       1.00      0.38      0.55         8
               3       1.00      0.18      0.31        11
               4       0.88      0.26      0.40        27
               5       0.76      1.00      0.86       134
    
        accuracy                           0.78       200
       macro avg       0.91      0.45      0.54       200
    weighted avg       0.81      0.78      0.73       200
    


We can see that the model has learnt to distinguish between the categories decently. 5-star reviews show the best performance overall, and this is not too surprising, since they are the most common in the dataset.


```python
from utils.embeddings_utils import plot_multiclass_precision_recall

plot_multiclass_precision_recall(probas, y_test, [1, 2, 3, 4, 5], clf)
```

    RandomForestClassifier() - Average precision score over all classes: 0.90



    
![png](output_3_1.png)
    


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.


key: url
string_value:
https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb


key: _node_content
string_value:
{"id_": "370c4b9c-73e1-41a7-83c2-be87a3173c32", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "c5b4335a-c8a5-49df-96ef-7bbf23dbed0c", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "c24edc3ba0f4627e0a356055aecd989311421ef871953d9b3ade6a19889df5a8", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b212d5b7-83a6-48e0-8f07-30cd00a070dc", "node_type": "1", "metadata": {}, "hash": "a012f786d7175571e429554d3ac6c488b913dc2f7366b9201ab4cb2f7cd0c9d1", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 1143, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Using Tool Required for Customer Service

The `ChatCompletion` endpoint now includes the ability to specify whether a tool **must** be called every time, by adding `tool_choice='required'` as a parameter. 

This adds an element of determinism to how you build your wrapping application, as you can count on a tool being provided with every call. We'll demonstrate here how this can be useful for a contained flow like customer service, where having the ability to define specific exit points gives more control.

The notebook concludes with a multi-turn evaluation, where we spin up a customer GPT to imitate our customer and test the LLM customer service agent we've set up.


```python
import json
from openai import OpenAI
import os

client = OpenAI()
GPT_MODEL = 'gpt-4-turbo'
```

## Config definition

We will define `tools` and `instructions` which our LLM customer service agent will use. It will source the right instructions for the problem the customer is facing, and use those to answer the customer's query.

As this is a demo example, we'll ask the model to make up values where it doesn't have external systems to source info.


key: _node_content
string_value:
{"id_": "b212d5b7-83a6-48e0-8f07-30cd00a070dc", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "c5b4335a-c8a5-49df-96ef-7bbf23dbed0c", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "c24edc3ba0f4627e0a356055aecd989311421ef871953d9b3ade6a19889df5a8", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "370c4b9c-73e1-41a7-83c2-be87a3173c32", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "092d78e00d12a2be3af476a25c30511623ea6b902f52544ef2981e71872ad3ec", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ae925a4c-9600-4a75-a68f-bcb7ebe8d5fd", "node_type": "1", "metadata": {}, "hash": "df15be066edc4d9b5322771a0d5b997b53ec1470fdb4b41ad89768474d0a3556", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3912, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Using Tool Required for Customer Service

The `ChatCompletion` endpoint now includes the ability to specify whether a tool **must** be called every time, by adding `tool_choice='required'` as a parameter. 

This adds an element of determinism to how you build your wrapping application, as you can count on a tool being provided with every call. We'll demonstrate here how this can be useful for a contained flow like customer service, where having the ability to define specific exit points gives more control.

The notebook concludes with a multi-turn evaluation, where we spin up a customer GPT to imitate our customer and test the LLM customer service agent we've set up.


```python
import json
from openai import OpenAI
import os

client = OpenAI()
GPT_MODEL = 'gpt-4-turbo'
```

## Config definition

We will define `tools` and `instructions` which our LLM customer service agent will use. It will source the right instructions for the problem the customer is facing, and use those to answer the customer's query.

As this is a demo example, we'll ask the model to make up values where it doesn't have external systems to source info.


```python
# The tools our customer service LLM will use to communicate
tools = [
{
  "type": "function",
  "function": {
    "name": "speak_to_user",
    "description": "Use this to speak to the user to give them information and to ask for anything required for their case.",
    "parameters": {
      "type": "object",
      "properties": {
        "message": {
          "type": "string",
          "description": "Text of message to send to user. Can cover multiple topics."
        }
      },
      "required": ["message"]
    }
  }
},
{
  "type": "function",
  "function": {
    "name": "get_instructions",
    "description": "Used to get instructions to deal with the user's problem.",
    "parameters": {
      "type": "object",
      "properties": {
        "problem": {
          "type": "string",
          "enum": ["fraud","refund","information"],
          "description": """The type of problem the customer has. Can be one of:
          - fraud: Required to report and resolve fraud.
          - refund: Required to submit a refund request.
          - information: Used for any other informational queries."""
        }
      },
      "required": [
        "problem"
      ]
    }
  }
}
]

# Example instructions that the customer service assistant can consult for relevant customer problems
INSTRUCTIONS = [ {"type": "fraud",
                  "instructions": """• Ask the customer to describe the fraudulent activity, including the the date and items involved in the suspected fraud.
• Offer the customer a refund.
• Report the fraud to the security team for further investigation.
• Thank the customer for contacting support and invite them to reach out with any future queries."""},
                {"type": "refund",
                 "instructions": """• Confirm the customer's purchase details and verify the transaction in the system.
• Check the company's refund policy to ensure the request meets the criteria.
• Ask the customer to provide a reason for the refund.
• Submit the refund request to the accounting department.
• Inform the customer of the expected time frame for the refund processing.
• Thank the customer for contacting support and invite them to reach out with any future queries."""},
                {"type": "information",
                 "instructions": """• Greet the customer and ask how you can assist them today.
• Listen carefully to the customer's query and clarify if necessary.
• Provide accurate and clear information based on the customer's questions.
• Offer to assist with any additional questions or provide further details if needed.
• Ensure the customer is satisfied with the information provided.
• Thank the customer for contacting support and invite them to reach out with any future queries.""" }]
```


key: _node_content
string_value:
{"id_": "ae925a4c-9600-4a75-a68f-bcb7ebe8d5fd", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "c5b4335a-c8a5-49df-96ef-7bbf23dbed0c", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "c24edc3ba0f4627e0a356055aecd989311421ef871953d9b3ade6a19889df5a8", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b212d5b7-83a6-48e0-8f07-30cd00a070dc", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "a8487aa8738f5cfcb800409ca5dc1c25f724019114093e2e4c051cf5da9d45d0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1fad9f36-8795-45ac-8b66-4a0626afbdf1", "node_type": "1", "metadata": {}, "hash": "23cf9c7df1e679e8bab065da1adc06295ad8046465a29c0fd0aba67bf26c550b", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3915, "end_char_idx": 8198, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
assistant_system_prompt = """You are a customer service assistant. Your role is to answer user questions politely and competently.
You should follow these instructions to solve the case:
- Understand their problem and get the relevant instructions.
- Follow the instructions to solve the customer's problem. Get their confirmation before performing a permanent operation like a refund or similar.
- Help them with any other problems or close the case.

Only call a tool once in a single message.
If you need to fetch a piece of information from a system or document that you don't have access to, give a clear, confident answer with some dummy values."""

def submit_user_message(user_query,conversation_messages=[]):
    """Message handling function which loops through tool calls until it reaches one that requires a response.
    Once it receives respond=True it returns the conversation_messages to the user."""

    # Initiate a respond object. This will be set to True by our functions when a response is required
    respond = False
    
    user_message = {"role":"user","content": user_query}
    conversation_messages.append(user_message)

    print(f"User: {user_query}")

    while respond is False:

        # Build a transient messages object to add the conversation messages to
        messages = [
            {
                "role": "system",
                "content": assistant_system_prompt
            }
        ]

        # Add the conversation messages to our messages call to the API
        [messages.append(x) for x in conversation_messages]

        # Make the ChatCompletion call with tool_choice='required' so we can guarantee tools will be used
        response = client.chat.completions.create(model=GPT_MODEL
                                                  ,messages=messages
                                                  ,temperature=0
                                                  ,tools=tools
                                                  ,tool_choice='required'
                                                 )

        conversation_messages.append(response.choices[0].message)

        # Execute the function and get an updated conversation_messages object back
        # If it doesn't require a response, it will ask the assistant again. 
        # If not the results are returned to the user.
        respond, conversation_messages = execute_function(response.choices[0].message,conversation_messages)
    
    return conversation_messages

def execute_function(function_calls,messages):
    """Wrapper function to execute the tool calls"""

    for function_call in function_calls.tool_calls:
    
        function_id = function_call.id
        function_name = function_call.function.name
        print(f"Calling function {function_name}")
        function_arguments = json.loads(function_call.function.arguments)
    
        if function_name == 'get_instructions':

            respond = False
    
            instruction_name = function_arguments['problem']
            instructions = INSTRUCTIONS['type' == instruction_name]
    
            messages.append(
                                {
                                    "tool_call_id": function_id,
                                    "role": "tool",
                                    "name": function_name,
                                    "content": instructions['instructions'],
                                }
                            )
    
        elif function_name != 'get_instructions':

            respond = True
    
            messages.append(
                                {
                                    "tool_call_id": function_id,
                                    "role": "tool",
                                    "name": function_name,
                                    "content": function_arguments['message'],
                                }
                            )
    
            print(f"Assistant: {function_arguments['message']}")
    
    return (respond, messages)
    
```

## Example

To test this we will run an example for a customer who has experienced fraud, and see how the model handles it.

Play the role of the user and provide plausible next steps to keep the conversation going.


key: _node_content
string_value:
{"id_": "1fad9f36-8795-45ac-8b66-4a0626afbdf1", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "c5b4335a-c8a5-49df-96ef-7bbf23dbed0c", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "c24edc3ba0f4627e0a356055aecd989311421ef871953d9b3ade6a19889df5a8", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ae925a4c-9600-4a75-a68f-bcb7ebe8d5fd", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "0891b353cc1f2fd369111df7c9efbae2ad555144c2b581de1253511e25b2a3eb", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "352cd57a-f938-4eb5-a40f-64d96be01271", "node_type": "1", "metadata": {}, "hash": "1e7b7aaf3b01987d1487cf2b52da79ab714942b8654a6d592f87671379808c5b", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 8201, "end_char_idx": 11338, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
messages = submit_user_message("Hi, I have had an item stolen that was supposed to be delivered to me yesterday.")
```

    User: Hi, I have had an item stolen that was supposed to be delivered to me yesterday.
    Calling function get_instructions
    Calling function speak_to_user
    Assistant: I'm sorry to hear about the stolen item. Could you please provide me with more details about the fraudulent activity, including the date and the items involved? This information will help us to investigate the issue further and proceed with the necessary actions, including offering you a refund.



```python
messages = submit_user_message("For sure, it was a shirt, it was supposed to be delivered yesterday but it never arrived.",messages)
```

    User: For sure, it was a shirt, it was supposed to be delivered yesterday but it never arrived.
    Calling function speak_to_user
    Assistant: Thank you for providing the details. I will now proceed to report this incident to our security team for further investigation and arrange a refund for the stolen shirt. Please confirm if you would like me to go ahead with the refund.
    Calling function speak_to_user
    Assistant: Thank you for contacting us about this issue. Please don't hesitate to reach out if you have any more questions or need further assistance in the future.



```python
messages = submit_user_message("Yes I would like to proceed with the refund.",messages)
```

    User: Yes I would like to proceed with the refund.
    Calling function get_instructions
    Calling function speak_to_user
    Assistant: Thank you for confirming. I have processed the refund for the stolen shirt. The amount should be reflected in your account within 5-7 business days. If you have any more questions or need further assistance, please feel free to contact us.



```python
messages = submit_user_message("Thanks very much.",messages)
```

    User: Thanks very much.
    Calling function speak_to_user
    Assistant: You're welcome! If you need any more help in the future, don't hesitate to reach out. Have a great day!


## Evaluation

Now we'll do a simple evaluation where a GPT will pretend to be our customer. The two will go back and forth until a resolution is reached.

We'll reuse the functions above, adding an `execute_conversation` function where the customer GPT will continue answering.


```python
customer_system_prompt = """You are a user calling in to customer service.
You will talk to the agent until you have a resolution to your query.
Your query is {query}.
You will be presented with a conversation - provide answers for any assistant questions you receive. 
Here is the conversation - you are the "user" and you are speaking with the "assistant":
{chat_history}

If you don't know the details, respond with dummy values.
Once your query is resolved, respond with "DONE" """

# Initiate a bank of questions run through
questions = ['I want to get a refund for the suit I ordered last Friday.',
            'Can you tell me what your policy is for returning damaged goods?',
            'Please tell me what your complaint policy is']
```


key: _node_content
string_value:
{"id_": "352cd57a-f938-4eb5-a40f-64d96be01271", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "c5b4335a-c8a5-49df-96ef-7bbf23dbed0c", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "c24edc3ba0f4627e0a356055aecd989311421ef871953d9b3ade6a19889df5a8", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1fad9f36-8795-45ac-8b66-4a0626afbdf1", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "04e1d6042d4676d45a4dba632d37773a2c21bc75a36f19fbdd770bf9b2bfb3a3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "94531615-eb4d-4723-8c7d-ae7e2e87ef51", "node_type": "1", "metadata": {}, "hash": "fcc9e78b1db92e14c424f56c897c2ef3475f2fa24fa91a410c55e3c4babc4894", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 9550, "end_char_idx": 13207, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
messages = submit_user_message("Yes I would like to proceed with the refund.",messages)
```

    User: Yes I would like to proceed with the refund.
    Calling function get_instructions
    Calling function speak_to_user
    Assistant: Thank you for confirming. I have processed the refund for the stolen shirt. The amount should be reflected in your account within 5-7 business days. If you have any more questions or need further assistance, please feel free to contact us.



```python
messages = submit_user_message("Thanks very much.",messages)
```

    User: Thanks very much.
    Calling function speak_to_user
    Assistant: You're welcome! If you need any more help in the future, don't hesitate to reach out. Have a great day!


## Evaluation

Now we'll do a simple evaluation where a GPT will pretend to be our customer. The two will go back and forth until a resolution is reached.

We'll reuse the functions above, adding an `execute_conversation` function where the customer GPT will continue answering.


```python
customer_system_prompt = """You are a user calling in to customer service.
You will talk to the agent until you have a resolution to your query.
Your query is {query}.
You will be presented with a conversation - provide answers for any assistant questions you receive. 
Here is the conversation - you are the "user" and you are speaking with the "assistant":
{chat_history}

If you don't know the details, respond with dummy values.
Once your query is resolved, respond with "DONE" """

# Initiate a bank of questions run through
questions = ['I want to get a refund for the suit I ordered last Friday.',
            'Can you tell me what your policy is for returning damaged goods?',
            'Please tell me what your complaint policy is']
```


```python
def execute_conversation(objective):

    conversation_messages = []

    done = False

    user_query = objective

    while done is False:

        conversation_messages = submit_user_message(user_query,conversation_messages)

        messages_string = ''
        for x in conversation_messages:
            if isinstance(x,dict):
                if x['role'] == 'user':
                    messages_string += 'User: ' + x['content'] + '\n'
                elif x['role'] == 'tool':
                    if x['name'] == 'speak_to_user':
                        messages_string += 'Assistant: ' + x['content'] + '\n'
            else:
                continue

        messages = [
            {
            "role": "system",
            "content": customer_system_prompt.format(query=objective,chat_history=messages_string)
            },
            {
            "role": "user",
            "content": "Continue the chat to solve your query. Remember, you are in the user in this exchange. Do not provide User: or Assistant: in your response"
            }
        ]

        user_response = client.chat.completions.create(model=GPT_MODEL,messages=messages,temperature=0.5)

        conversation_messages.append({
            "role": "user",
            "content": user_response.choices[0].message.content
            })

        if 'DONE' in user_response.choices[0].message.content:
            done = True
            print("Achieved objective, closing conversation\n\n")

        else:
            user_query = user_response.choices[0].message.content
```


```python
for x in questions:

    execute_conversation(x)
```

    User: I want to get a refund for the suit I ordered last Friday.
    Calling function get_instructions
    Calling function speak_to_user
    Assistant: I understand you'd like a refund for the suit you ordered last Friday.


key: _node_content
string_value:
{"id_": "94531615-eb4d-4723-8c7d-ae7e2e87ef51", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "c5b4335a-c8a5-49df-96ef-7bbf23dbed0c", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "c24edc3ba0f4627e0a356055aecd989311421ef871953d9b3ade6a19889df5a8", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "352cd57a-f938-4eb5-a40f-64d96be01271", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "b4dfeeecd0222d2b1f4e9f5f59d0045dc0c1696790307b812df6c1a9b11c3d20", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "529004ac-3e84-4b3c-8487-4085b96e374f", "node_type": "1", "metadata": {}, "hash": "ea7fa1c7850943888862015156f00198482cfdfd65aa04044f86bb54687efad8", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 11341, "end_char_idx": 14997, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
def execute_conversation(objective):

    conversation_messages = []

    done = False

    user_query = objective

    while done is False:

        conversation_messages = submit_user_message(user_query,conversation_messages)

        messages_string = ''
        for x in conversation_messages:
            if isinstance(x,dict):
                if x['role'] == 'user':
                    messages_string += 'User: ' + x['content'] + '\n'
                elif x['role'] == 'tool':
                    if x['name'] == 'speak_to_user':
                        messages_string += 'Assistant: ' + x['content'] + '\n'
            else:
                continue

        messages = [
            {
            "role": "system",
            "content": customer_system_prompt.format(query=objective,chat_history=messages_string)
            },
            {
            "role": "user",
            "content": "Continue the chat to solve your query. Remember, you are in the user in this exchange. Do not provide User: or Assistant: in your response"
            }
        ]

        user_response = client.chat.completions.create(model=GPT_MODEL,messages=messages,temperature=0.5)

        conversation_messages.append({
            "role": "user",
            "content": user_response.choices[0].message.content
            })

        if 'DONE' in user_response.choices[0].message.content:
            done = True
            print("Achieved objective, closing conversation\n\n")

        else:
            user_query = user_response.choices[0].message.content
```


```python
for x in questions:

    execute_conversation(x)
```

    User: I want to get a refund for the suit I ordered last Friday.
    Calling function get_instructions
    Calling function speak_to_user
    Assistant: I understand you'd like a refund for the suit you ordered last Friday. Could you please provide more details about the issue with the suit? This will help us process your refund request accurately.
    User: The suit I received is not the color I ordered. I ordered a navy blue suit, but the one I received is black.
    Calling function speak_to_user
    Assistant: Thank you for providing the details. I will proceed with the refund for the navy blue suit that was incorrectly sent as black. Please confirm if you would like me to go ahead with the refund.
    User: Yes, please go ahead with the refund.
    Calling function speak_to_user
    Assistant: The refund for the incorrectly colored suit has been processed. You should see the amount credited back to your original payment method within 5-7 business days. Thank you for contacting us, and if you have any more questions or need further assistance, please feel free to reach out.
    Achieved objective, closing conversation
    
    
    User: Can you tell me what your policy is for returning damaged goods?
    Calling function get_instructions
    Calling function speak_to_user
    Assistant: It seems there was a misunderstanding in my previous request. I'm looking for information on our policy for returning damaged goods. Could you please provide me with the details on how to handle returns for damaged items?
    User: Yes, I'd appreciate that. Could you please tell me the steps I need to follow to return a damaged item?
    Calling function get_instructions
    Calling function speak_to_user
    Assistant: I apologize for the confusion earlier. Here's the correct information regarding our policy for returning damaged goods:
    
    1. Please provide a description of the damage and the item involved.
    2. Include the date of purchase and your order number if available.
    3.


key: _node_content
string_value:
{"id_": "529004ac-3e84-4b3c-8487-4085b96e374f", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "c5b4335a-c8a5-49df-96ef-7bbf23dbed0c", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "c24edc3ba0f4627e0a356055aecd989311421ef871953d9b3ade6a19889df5a8", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "94531615-eb4d-4723-8c7d-ae7e2e87ef51", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "6bc656da392fdaf8562a67eb147ef4e25474f036daca05b8c65e5df4d7e9125c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "0c2ebffd-7522-44b5-9cfa-275685ddd2dd", "node_type": "1", "metadata": {}, "hash": "77a8ad006666af5a70ebb37d4db72df52db78556f9dbc41242793d730a1f18de", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 13208, "end_char_idx": 16842, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Could you please provide more details about the issue with the suit? This will help us process your refund request accurately.
    User: The suit I received is not the color I ordered. I ordered a navy blue suit, but the one I received is black.
    Calling function speak_to_user
    Assistant: Thank you for providing the details. I will proceed with the refund for the navy blue suit that was incorrectly sent as black. Please confirm if you would like me to go ahead with the refund.
    User: Yes, please go ahead with the refund.
    Calling function speak_to_user
    Assistant: The refund for the incorrectly colored suit has been processed. You should see the amount credited back to your original payment method within 5-7 business days. Thank you for contacting us, and if you have any more questions or need further assistance, please feel free to reach out.
    Achieved objective, closing conversation
    
    
    User: Can you tell me what your policy is for returning damaged goods?
    Calling function get_instructions
    Calling function speak_to_user
    Assistant: It seems there was a misunderstanding in my previous request. I'm looking for information on our policy for returning damaged goods. Could you please provide me with the details on how to handle returns for damaged items?
    User: Yes, I'd appreciate that. Could you please tell me the steps I need to follow to return a damaged item?
    Calling function get_instructions
    Calling function speak_to_user
    Assistant: I apologize for the confusion earlier. Here's the correct information regarding our policy for returning damaged goods:
    
    1. Please provide a description of the damage and the item involved.
    2. Include the date of purchase and your order number if available.
    3. You can choose to return the item by mail or in person at one of our stores. Please let us know which method you prefer, and we will provide the necessary details for the return process.
    4. Once we receive the item, we will inspect it and process a refund or exchange based on your preference and our return policy guidelines.
    
    Please let me know if you need further assistance with this process or if there's anything else I can help you with!
    User: I would like to return the item by mail. Could you please provide me with the details on how to do that?
    Calling function speak_to_user
    Assistant: Certainly! To return the damaged item by mail, please follow these steps:
    
    1. Pack the item securely in its original packaging, if possible.
    2. Include all original materials such as manuals, accessories, and receipts.
    3. Address the package to our returns department at the following address:
       [Your Company's Return Address]
    4. Use a trackable shipping service and keep the tracking number for your records.
    5. Once we receive and inspect the item, we will process your refund or exchange as per your request.
    
    Please let me know if you need a prepaid shipping label or any other assistance with your return!
    User: Yes, please, I would need a prepaid shipping label.
    Calling function speak_to_user
    Assistant: I will arrange for a prepaid shipping label to be sent to your email address. Please ensure that the email address we have on file is correct. You should receive the label shortly, which you can print and attach to your return package.
    
    Once you've shipped the item, please provide us with the tracking number so we can monitor the return's progress. If there's anything else you need help with, feel free to ask!
    User: That sounds great, thank you!


key: _node_content
string_value:
{"id_": "0c2ebffd-7522-44b5-9cfa-275685ddd2dd", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "c5b4335a-c8a5-49df-96ef-7bbf23dbed0c", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "c24edc3ba0f4627e0a356055aecd989311421ef871953d9b3ade6a19889df5a8", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "529004ac-3e84-4b3c-8487-4085b96e374f", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "ef6dde0e11f8c9ab05bc0e8d48cd4db905e2861ce32ce1e8cf343fed8124fc22", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8b809a24-2fe0-4bf6-8b09-5af58a3f1ea4", "node_type": "1", "metadata": {}, "hash": "a702238baed74aae3ee6020a2199b841723aff01893a1f7ccc6a150d1664a079", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 14998, "end_char_idx": 18570, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
You can choose to return the item by mail or in person at one of our stores. Please let us know which method you prefer, and we will provide the necessary details for the return process.
    4. Once we receive the item, we will inspect it and process a refund or exchange based on your preference and our return policy guidelines.
    
    Please let me know if you need further assistance with this process or if there's anything else I can help you with!
    User: I would like to return the item by mail. Could you please provide me with the details on how to do that?
    Calling function speak_to_user
    Assistant: Certainly! To return the damaged item by mail, please follow these steps:
    
    1. Pack the item securely in its original packaging, if possible.
    2. Include all original materials such as manuals, accessories, and receipts.
    3. Address the package to our returns department at the following address:
       [Your Company's Return Address]
    4. Use a trackable shipping service and keep the tracking number for your records.
    5. Once we receive and inspect the item, we will process your refund or exchange as per your request.
    
    Please let me know if you need a prepaid shipping label or any other assistance with your return!
    User: Yes, please, I would need a prepaid shipping label.
    Calling function speak_to_user
    Assistant: I will arrange for a prepaid shipping label to be sent to your email address. Please ensure that the email address we have on file is correct. You should receive the label shortly, which you can print and attach to your return package.
    
    Once you've shipped the item, please provide us with the tracking number so we can monitor the return's progress. If there's anything else you need help with, feel free to ask!
    User: That sounds great, thank you! My email address is correct on file. I'll look out for the prepaid shipping label and send the package back as soon as I receive it.
    Calling function speak_to_user
    Assistant: You're welcome! I'm glad I could assist you. Once you receive the prepaid shipping label, please proceed with the return as discussed. If you have any more questions or need further assistance in the future, don't hesitate to reach out. Have a great day!
    Achieved objective, closing conversation
    
    
    User: Please tell me what your complaint policy is
    Calling function get_instructions
    Calling function speak_to_user
    Assistant: It seems there was a misunderstanding. I will provide you with information about our complaint policy. Please give me a moment to gather the correct details for you.
    User: Sure, I'll wait. Thank you.
    Calling function speak_to_user
    Assistant: Our complaint policy is designed to ensure that any issues you encounter are addressed promptly and fairly. Here’s a brief overview:
    
    1. **Submission**: You can submit your complaint through our website, by email, or by calling our customer service hotline.
    2. **Acknowledgment**: We will acknowledge receipt of your complaint within 24 hours.
    3. **Investigation**: We will investigate your complaint thoroughly. This process typically takes 3-5 business days.
    4. **Resolution**: After the investigation, we will contact you with the outcome and any steps we will take to resolve the issue.
    5. **Follow-up**: If you are not satisfied with the resolution, you can request a review of the decision.
    
    Please let me know if you need more detailed information or if there's anything else I can assist you with!


key: _node_content
string_value:
{"id_": "8b809a24-2fe0-4bf6-8b09-5af58a3f1ea4", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "c5b4335a-c8a5-49df-96ef-7bbf23dbed0c", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "c24edc3ba0f4627e0a356055aecd989311421ef871953d9b3ade6a19889df5a8", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "0c2ebffd-7522-44b5-9cfa-275685ddd2dd", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_tool_required_for_customer_service.ipynb", "title": "Using Tool Required for Customer Service", "tokens": 3814, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "4c9187f2010da335b341cb1876043a49c166bb2a6fc0c57dd96c4ccfbf529b01", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 16740, "end_char_idx": 19201, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
If there's anything else you need help with, feel free to ask!
    User: That sounds great, thank you! My email address is correct on file. I'll look out for the prepaid shipping label and send the package back as soon as I receive it.
    Calling function speak_to_user
    Assistant: You're welcome! I'm glad I could assist you. Once you receive the prepaid shipping label, please proceed with the return as discussed. If you have any more questions or need further assistance in the future, don't hesitate to reach out. Have a great day!
    Achieved objective, closing conversation
    
    
    User: Please tell me what your complaint policy is
    Calling function get_instructions
    Calling function speak_to_user
    Assistant: It seems there was a misunderstanding. I will provide you with information about our complaint policy. Please give me a moment to gather the correct details for you.
    User: Sure, I'll wait. Thank you.
    Calling function speak_to_user
    Assistant: Our complaint policy is designed to ensure that any issues you encounter are addressed promptly and fairly. Here’s a brief overview:
    
    1. **Submission**: You can submit your complaint through our website, by email, or by calling our customer service hotline.
    2. **Acknowledgment**: We will acknowledge receipt of your complaint within 24 hours.
    3. **Investigation**: We will investigate your complaint thoroughly. This process typically takes 3-5 business days.
    4. **Resolution**: After the investigation, we will contact you with the outcome and any steps we will take to resolve the issue.
    5. **Follow-up**: If you are not satisfied with the resolution, you can request a review of the decision.
    
    Please let me know if you need more detailed information or if there's anything else I can assist you with!
    User: That covers everything I needed to know, thank you!
    Calling function speak_to_user
    Assistant: You're welcome! I'm glad I could help. If you have any more questions in the future or need further assistance, feel free to reach out. Have a great day!
    Achieved objective, closing conversation
    
    


## Conclusion

You can now control your LLM's behaviour explicitly by making tool use mandatory, as well as spin up GPT testers to challenge your LLM and to act as automated test cases.

We hope this has given you an appreciation for a great use case for tool use, and look forward to seeing what you build!


key: url
string_value:
https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb


key: _node_content
string_value:
{"id_": "2408a17d-4ad8-4980-a57b-0b0ef1857b36", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "437245ec-9ed7-4b92-aadd-05422f4792e9", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "54f90d7499f88d3942fd0d36a197c9e9e66835e8c51789f7a058b96e96409ab0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "fa6b6602-7c9b-4c2e-8c56-8f62bbef1658", "node_type": "1", "metadata": {}, "hash": "4b067052d386a0317f3945fbd2903e8a701548261f091d41579e2840cca189bc", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2766, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App

Welcome to the Clothing Matchmaker App Jupyter Notebook! This project demonstrates the power of the GPT-4o mini model in analyzing images of clothing items and extracting key features such as color, style, and type. The core of our app relies on this advanced image analysis model developed by OpenAI, which enables us to accurately identify the characteristics of the input clothing item.

GPT-4o mini is a small model that combines natural language processing with image recognition, allowing it to understand and generate responses based on both text and visual inputs with low latency.

Building on the capabilities of the GPT-4o mini model, we employ a custom matching algorithm and the RAG technique to search our knowledge base for items that complement the identified features. This algorithm takes into account factors like color compatibility and style coherence to provide users with suitable recommendations. Through this notebook, we aim to showcase the practical application of these technologies in creating a clothing recommendation system.

Using the combination of GPT-4o mini + RAG (Retrieval-Augmented Generation) offers several advantages:

1. **Contextual Understanding**: GPT-4o mini can analyze input images and understand the context, such as the objects, scenes, and activities depicted. This allows for more accurate and relevant suggestions or information across various domains, whether it's interior design, cooking, or education.
2. **Rich Knowledge Base**: RAG combines the generative capabilities of GPT-4 with a retrieval component that accesses a large corpus of information across different fields. This means the system can provide suggestions or insights based on a wide range of knowledge, from historical facts to scientific concepts.
3. **Customization**: The approach allows for easy customization to cater to specific user needs or preferences in various applications. Whether it's tailoring suggestions to a user's taste in art or providing educational content based on a student's learning level, the system can be adapted to deliver personalized experiences.

Overall, the GPT-4o mini + RAG approach offers a fast, powerful, and flexible solution for various fashion-related applications, leveraging the strengths of both generative and retrieval-based AI techniques.


### Environment Setup

First we will install the necessary dependencies, then import the libraries and write some utility functions that we will use later on. 


```python
%pip install openai --quiet
%pip install tenacity --quiet
%pip install tqdm --quiet
%pip install numpy --quiet
%pip install typing --quiet
%pip install tiktoken --quiet
%pip install concurrent --quiet
```


key: _node_content
string_value:
{"id_": "fa6b6602-7c9b-4c2e-8c56-8f62bbef1658", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "437245ec-9ed7-4b92-aadd-05422f4792e9", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "54f90d7499f88d3942fd0d36a197c9e9e66835e8c51789f7a058b96e96409ab0", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2408a17d-4ad8-4980-a57b-0b0ef1857b36", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "2d171c9e00f0df8a4626d2c278bfd49583a803c2b89c6f5ad582a950a5b0d1ac", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "980f8e57-52c4-4a56-a93a-aad85b343229", "node_type": "1", "metadata": {}, "hash": "6b66e0159e73f62d933b1cc4c7787df75cf4da5339012fa0f25b2a82472feedd", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2390, "end_char_idx": 4626, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
### Environment Setup

First we will install the necessary dependencies, then import the libraries and write some utility functions that we will use later on. 


```python
%pip install openai --quiet
%pip install tenacity --quiet
%pip install tqdm --quiet
%pip install numpy --quiet
%pip install typing --quiet
%pip install tiktoken --quiet
%pip install concurrent --quiet
```


```python
import pandas as pd
import numpy as np
import json
import ast
import tiktoken
import concurrent
from openai import OpenAI
from tqdm import tqdm
from tenacity import retry, wait_random_exponential, stop_after_attempt
from IPython.display import Image, display, HTML
from typing import List

client = OpenAI()

GPT_MODEL = "gpt-4o-mini"
EMBEDDING_MODEL = "text-embedding-3-large"
EMBEDDING_COST_PER_1K_TOKENS = 0.00013
```

### Creating the Embeddings
We will now set up the knowledge base by choosing a database and generating embeddings for it. I am using the `sample_styles.csv` file for this in the data folder. This is a sample of a bigger dataset that contains `~44K` items. This step can also be replaced by using an out-of-the-box vector database. For example, you can follow one of [these cookbooks](https://github.com/openai/openai-cookbook/tree/main/examples/vector_databases) to set up your vector database.


```python
styles_filepath = "data/sample_clothes/sample_styles.csv"
styles_df = pd.read_csv(styles_filepath, on_bad_lines='skip')
print(styles_df.head())
print("Opened dataset successfully. Dataset has {} items of clothing.".format(len(styles_df)))
```

Now we will generate embeddings for the entire dataset. We can parallelize the execution of these embeddings to ensure that the script scales up for larger datasets. With this logic, the time to create embeddings for the full `44K` entry dataset decreases from ~4h to ~2-3min. 


```python
## Batch Embedding Logic

# Simple function to take in a list of text objects and return them as a list of embeddings
@retry(wait=wait_random_exponential(min=1, max=40), stop=stop_after_attempt(10))
def get_embeddings(input: List):
    response = client.embeddings.create(
        input=input,
        model=EMBEDDING_MODEL
    ).data
    return [data.embedding for data in response]


key: _node_content
string_value:
{"id_": "980f8e57-52c4-4a56-a93a-aad85b343229", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "437245ec-9ed7-4b92-aadd-05422f4792e9", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "54f90d7499f88d3942fd0d36a197c9e9e66835e8c51789f7a058b96e96409ab0", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "fa6b6602-7c9b-4c2e-8c56-8f62bbef1658", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "855cddd476f117df126c302c65f24d2a3b496bde4c717b50955f1da5f5838eb6", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ca74db01-da1e-4a8c-93c4-81c282dec940", "node_type": "1", "metadata": {}, "hash": "1e035c0284c164f9a9e376b5d1b21ff4838b6bca87ace823f02581026da7db24", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3699, "end_char_idx": 7475, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
styles_filepath = "data/sample_clothes/sample_styles.csv"
styles_df = pd.read_csv(styles_filepath, on_bad_lines='skip')
print(styles_df.head())
print("Opened dataset successfully. Dataset has {} items of clothing.".format(len(styles_df)))
```

Now we will generate embeddings for the entire dataset. We can parallelize the execution of these embeddings to ensure that the script scales up for larger datasets. With this logic, the time to create embeddings for the full `44K` entry dataset decreases from ~4h to ~2-3min. 


```python
## Batch Embedding Logic

# Simple function to take in a list of text objects and return them as a list of embeddings
@retry(wait=wait_random_exponential(min=1, max=40), stop=stop_after_attempt(10))
def get_embeddings(input: List):
    response = client.embeddings.create(
        input=input,
        model=EMBEDDING_MODEL
    ).data
    return [data.embedding for data in response]


# Splits an iterable into batches of size n.
def batchify(iterable, n=1):
    l = len(iterable)
    for ndx in range(0, l, n):
        yield iterable[ndx : min(ndx + n, l)]
     

# Function for batching and parallel processing the embeddings
def embed_corpus(
    corpus: List[str],
    batch_size=64,
    num_workers=8,
    max_context_len=8191,
):
    # Encode the corpus, truncating to max_context_len
    encoding = tiktoken.get_encoding("cl100k_base")
    encoded_corpus = [
        encoded_article[:max_context_len] for encoded_article in encoding.encode_batch(corpus)
    ]

    # Calculate corpus statistics: the number of inputs, the total number of tokens, and the estimated cost to embed
    num_tokens = sum(len(article) for article in encoded_corpus)
    cost_to_embed_tokens = num_tokens / 1000 * EMBEDDING_COST_PER_1K_TOKENS
    print(
        f"num_articles={len(encoded_corpus)}, num_tokens={num_tokens}, est_embedding_cost={cost_to_embed_tokens:.2f} USD"
    )

    # Embed the corpus
    with concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) as executor:
        
        futures = [
            executor.submit(get_embeddings, text_batch)
            for text_batch in batchify(encoded_corpus, batch_size)
        ]

        with tqdm(total=len(encoded_corpus)) as pbar:
            for _ in concurrent.futures.as_completed(futures):
                pbar.update(batch_size)

        embeddings = []
        for future in futures:
            data = future.result()
            embeddings.extend(data)

        return embeddings
    

# Function to generate embeddings for a given column in a DataFrame
def generate_embeddings(df, column_name):
    # Initialize an empty list to store embeddings
    descriptions = df[column_name].astype(str).tolist()
    embeddings = embed_corpus(descriptions)

    # Add the embeddings as a new column to the DataFrame
    df['embeddings'] = embeddings
    print("Embeddings created successfully.")
```

#### Two options for creating the embeddings: 
The next line will **create the embeddings** for the sample clothes dataset. This will take around 0.02s to process and another ~30s to write the results to a local .csv file. The process is using our `text_embedding_3_large` model which is priced at `$0.00013/1K` tokens. Given that the dataset has around `1K` entries, the following operation will cost approximately `$0.001`. If you decide to work with the entire dataset of `44K` entries, this operation will take 2-3min to process and it will cost approximately `$0.07`.

**If you would not like to proceed with creating your own embeddings**, we will use a dataset of pre-computed embeddings. You can skip this cell and uncomment the code in the following cell to proceed with loading the pre-computed vectors. This operation takes ~1min to load all the data in memory.


key: _node_content
string_value:
{"id_": "ca74db01-da1e-4a8c-93c4-81c282dec940", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "437245ec-9ed7-4b92-aadd-05422f4792e9", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "54f90d7499f88d3942fd0d36a197c9e9e66835e8c51789f7a058b96e96409ab0", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "980f8e57-52c4-4a56-a93a-aad85b343229", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "bc48b1f94cdcd2258aa81313eaf84d85abec458bff1364d16d50785e4148f647", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "cf52bb0f-fb32-49aa-ac91-e79748ec3cf1", "node_type": "1", "metadata": {}, "hash": "9283f32949a6f26278109f8a2ecd9b7f681ed63b10893f0fdb668541ea556f63", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 7478, "end_char_idx": 10780, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
generate_embeddings(styles_df, 'productDisplayName')
print("Writing embeddings to file ...")
styles_df.to_csv('data/sample_clothes/sample_styles_with_embeddings.csv', index=False)
print("Embeddings successfully stored in sample_styles_with_embeddings.csv")
```


```python
# styles_df = pd.read_csv('data/sample_clothes/sample_styles_with_embeddings.csv', on_bad_lines='skip')

# # Convert the 'embeddings' column from string representations of lists to actual lists of floats
# styles_df['embeddings'] = styles_df['embeddings'].apply(lambda x: ast.literal_eval(x))

print(styles_df.head())
print("Opened dataset successfully. Dataset has {} items of clothing along with their embeddings.".format(len(styles_df)))
```

### Building the Matching Algorithm

In this section, we'll develop a cosine similarity retrieval algorithm to find similar items in our dataframe. We'll utilize our custom cosine similarity function for this purpose. While the `sklearn` library offers a built-in cosine similarity function, recent updates to its SDK have led to compatibility issues, prompting us to implement our own standard cosine similarity calculation.

If you already have a vector database set up, you can skip this step. Most standard databases come with their own search functions, which simplify the subsequent steps outlined in this guide. However, we aim to demonstrate that the matching algorithm can be tailored to meet specific requirements, such as a particular threshold or a specified number of matches returned.

The `find_similar_items` function accepts four parameters:
- `embedding`: The embedding for which we want to find a match.
- `embeddings`: A list of embeddings to search through for the best matches.
- `threshold` (optional): This parameter specifies the minimum similarity score for a match to be considered valid. A higher threshold results in closer (better) matches, while a lower threshold allows for more items to be returned, though they may not be as closely matched to the initial `embedding`.
- `top_k` (optional): This parameter determines the number of items to return that exceed the given threshold. These will be the top-scoring matches for the provided `embedding`.


```python
def cosine_similarity_manual(vec1, vec2):
    """Calculate the cosine similarity between two vectors."""
    vec1 = np.array(vec1, dtype=float)
    vec2 = np.array(vec2, dtype=float)


    dot_product = np.dot(vec1, vec2)
    norm_vec1 = np.linalg.norm(vec1)
    norm_vec2 = np.linalg.norm(vec2)
    return dot_product / (norm_vec1 * norm_vec2)


def find_similar_items(input_embedding, embeddings, threshold=0.5, top_k=2):
    """Find the most similar items based on cosine similarity."""
    
    # Calculate cosine similarity between the input embedding and all other embeddings
    similarities = [(index, cosine_similarity_manual(input_embedding, vec)) for index, vec in enumerate(embeddings)]
    
    # Filter out any similarities below the threshold
    filtered_similarities = [(index, sim) for index, sim in similarities if sim >= threshold]
    
    # Sort the filtered similarities by similarity score
    sorted_indices = sorted(filtered_similarities, key=lambda x: x[1], reverse=True)[:top_k]

    # Return the top-k most similar items
    return sorted_indices
```


key: _node_content
string_value:
{"id_": "cf52bb0f-fb32-49aa-ac91-e79748ec3cf1", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "437245ec-9ed7-4b92-aadd-05422f4792e9", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "54f90d7499f88d3942fd0d36a197c9e9e66835e8c51789f7a058b96e96409ab0", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ca74db01-da1e-4a8c-93c4-81c282dec940", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "787d5ae53eddcec4f4b7f3977105123955507f4f8193785b753b84bd8b9e8070", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5e22d787-de35-43df-bce6-32bf3ec0dabc", "node_type": "1", "metadata": {}, "hash": "354e8aed5aaa11445d1eacf62dbf48624f92213325c6b4af4d2f640a5589a786", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 9691, "end_char_idx": 13332, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
def cosine_similarity_manual(vec1, vec2):
    """Calculate the cosine similarity between two vectors."""
    vec1 = np.array(vec1, dtype=float)
    vec2 = np.array(vec2, dtype=float)


    dot_product = np.dot(vec1, vec2)
    norm_vec1 = np.linalg.norm(vec1)
    norm_vec2 = np.linalg.norm(vec2)
    return dot_product / (norm_vec1 * norm_vec2)


def find_similar_items(input_embedding, embeddings, threshold=0.5, top_k=2):
    """Find the most similar items based on cosine similarity."""
    
    # Calculate cosine similarity between the input embedding and all other embeddings
    similarities = [(index, cosine_similarity_manual(input_embedding, vec)) for index, vec in enumerate(embeddings)]
    
    # Filter out any similarities below the threshold
    filtered_similarities = [(index, sim) for index, sim in similarities if sim >= threshold]
    
    # Sort the filtered similarities by similarity score
    sorted_indices = sorted(filtered_similarities, key=lambda x: x[1], reverse=True)[:top_k]

    # Return the top-k most similar items
    return sorted_indices
```


```python
def find_matching_items_with_rag(df_items, item_descs):
   """Take the input item descriptions and find the most similar items based on cosine similarity for each description."""
   
   # Select the embeddings from the DataFrame.
   embeddings = df_items['embeddings'].tolist()

   
   similar_items = []
   for desc in item_descs:
      
      # Generate the embedding for the input item
      input_embedding = get_embeddings([desc])
    
      # Find the most similar items based on cosine similarity
      similar_indices = find_similar_items(input_embedding, embeddings, threshold=0.6)
      similar_items += [df_items.iloc[i] for i in similar_indices]
    
   return similar_items
```

### Analysis Module

In this module, we leverage `gpt-4o-mini` to analyze input images and extract important features like detailed descriptions, styles, and types. The analysis is performed through a straightforward API call, where we provide the URL of the image for analysis and request the model to identify relevant features.

To ensure the model returns accurate results, we use specific techniques in our prompt:

1. **Output Format Specification**: We instruct the model to return a JSON block with a predefined structure, consisting of:
   - `items` (str[]): A list of strings, each representing a concise title for an item of clothing, including style, color, and gender. These titles closely resemble the `productDisplayName` property in our original database.
   - `category` (str): The category that best represents the given item. The model selects from a list of all unique `articleTypes` present in the original styles dataframe.
   - `gender` (str): A label indicating the gender the item is intended for. The model chooses from the options `[Men, Women, Boys, Girls, Unisex]`.

2. **Clear and Concise Instructions**: 
   - We provide clear instructions on what the item titles should include and what the output format should be. The output should be in JSON format, but without the `json` tag that the model response normally contains.

3. **One Shot Example**: 
   - To further clarify the expected output, we provide the model with an example input description and a corresponding example output. Although this may increase the number of tokens used (and thus the cost of the call), it helps to guide the model and results in better overall performance.

By following this structured approach, we aim to obtain precise and useful information from the `gpt-4o-mini` model for further analysis and integration into our database.


key: _node_content
string_value:
{"id_": "5e22d787-de35-43df-bce6-32bf3ec0dabc", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "437245ec-9ed7-4b92-aadd-05422f4792e9", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "54f90d7499f88d3942fd0d36a197c9e9e66835e8c51789f7a058b96e96409ab0", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "cf52bb0f-fb32-49aa-ac91-e79748ec3cf1", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "45935f0aee06e40c8547c0a0f613eb28e7463780fe7bc4e47212b89e5159a4c1", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "59fbde11-1426-4450-a194-d9ae3a8d2e22", "node_type": "1", "metadata": {}, "hash": "88985f770e9bbc61ac012155e9d3556de2ccd967051a6eeac3219bdd4bea22c3", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 13335, "end_char_idx": 16438, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
def analyze_image(image_base64, subcategories):
    response = client.chat.completions.create(
        model=GPT_MODEL,
        messages=[
            {
            "role": "user",
            "content": [
                {
                "type": "text",
                "text": """Given an image of an item of clothing, analyze the item and generate a JSON output with the following fields: "items", "category", and "gender". 
                           Use your understanding of fashion trends, styles, and gender preferences to provide accurate and relevant suggestions for how to complete the outfit.
                           The items field should be a list of items that would go well with the item in the picture. Each item should represent a title of an item of clothing that contains the style, color, and gender of the item.
                           The category needs to be chosen between the types in this list: {subcategories}.
                           You have to choose between the genders in this list: [Men, Women, Boys, Girls, Unisex]
                           Do not include the description of the item in the picture. Do not include the ```json ``` tag in the output.
                           
                           Example Input: An image representing a black leather jacket.

                           Example Output: {"items": ["Fitted White Women's T-shirt", "White Canvas Sneakers", "Women's Black Skinny Jeans"], "category": "Jackets", "gender": "Women"}
                           """,
                },
                {
                "type": "image_url",
                "image_url": {
                    "url": f"data:image/jpeg;base64,{image_base64}",
                },
                }
            ],
            }
        ]
    )
    # Extract relevant features from the response
    features = response.choices[0].message.content
    return features
```

### Testing the Prompt with Sample Images

To evaluate the effectiveness of our prompt, let's load and test it with a selection of images from our dataset. We'll use images from the `"data/sample_clothes/sample_images"` folder, ensuring a variety of styles, genders, and types. Here are the chosen samples:

- `2133.jpg`: Men's shirt
- `7143.jpg`: Women's shirt
- `4226.jpg`: Casual men's printed t-shirt

By testing the prompt with these diverse images, we can assess its ability to accurately analyze and extract relevant features from different types of clothing items and accessories.

We need a utility function to encode the .jpg images in base64


```python
import base64

def encode_image_to_base64(image_path):
    with open(image_path, 'rb') as image_file:
        encoded_image = base64.b64encode(image_file.read())
        return encoded_image.decode('utf-8')
```


```python
# Set the path to the images and select a test image
image_path = "data/sample_clothes/sample_images/"
test_images = ["2133.jpg", "7143.jpg", "4226.jpg"]

# Encode the test image to base64
reference_image = image_path + test_images[0]
encoded_image = encode_image_to_base64(reference_image)
```


key: _node_content
string_value:
{"id_": "59fbde11-1426-4450-a194-d9ae3a8d2e22", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "437245ec-9ed7-4b92-aadd-05422f4792e9", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "54f90d7499f88d3942fd0d36a197c9e9e66835e8c51789f7a058b96e96409ab0", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5e22d787-de35-43df-bce6-32bf3ec0dabc", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "1b3b3aa44cddb2147db091208badf2abde719602a336749ad7bbdccd1226ba10", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "905b75f6-c3ff-4a4e-802a-d17c7baf17ab", "node_type": "1", "metadata": {}, "hash": "dbdf0aa517644f727fb8328e942df9604c1e74a7867e5348711ac4195312a672", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 15911, "end_char_idx": 18122, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
import base64

def encode_image_to_base64(image_path):
    with open(image_path, 'rb') as image_file:
        encoded_image = base64.b64encode(image_file.read())
        return encoded_image.decode('utf-8')
```


```python
# Set the path to the images and select a test image
image_path = "data/sample_clothes/sample_images/"
test_images = ["2133.jpg", "7143.jpg", "4226.jpg"]

# Encode the test image to base64
reference_image = image_path + test_images[0]
encoded_image = encode_image_to_base64(reference_image)
```


```python
# Select the unique subcategories from the DataFrame
unique_subcategories = styles_df['articleType'].unique()

# Analyze the image and return the results
analysis = analyze_image(encoded_image, unique_subcategories)
image_analysis = json.loads(analysis)

# Display the image and the analysis results
display(Image(filename=reference_image))
print(image_analysis)
```

Next, we process the output from the image analysis and use it to filter and display matching items from our dataset. Here's a breakdown of the code:

1. **Extracting Image Analysis Results**: We extract the item descriptions, category, and gender from the `image_analysis` dictionary.

2. **Filtering the Dataset**: We filter the `styles_df` DataFrame to include only items that match the gender from the image analysis (or are unisex) and exclude items of the same category as the analyzed image.

3. **Finding Matching Items**: We use the `find_matching_items_with_rag` function to find items in the filtered dataset that match the descriptions extracted from the analyzed image.

4. **Displaying Matching Items**: We create an HTML string to display images of the matching items. We construct the image paths using the item IDs and append each image to the HTML string. Finally, we use `display(HTML(html))` to render the images in the notebook.

This cell effectively demonstrates how to use the results of image analysis to filter a dataset and visually display items that match the analyzed image's characteristics.


```python
# Extract the relevant features from the analysis
item_descs = image_analysis['items']
item_category = image_analysis['category']
item_gender = image_analysis['gender']


key: _node_content
string_value:
{"id_": "905b75f6-c3ff-4a4e-802a-d17c7baf17ab", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "437245ec-9ed7-4b92-aadd-05422f4792e9", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "54f90d7499f88d3942fd0d36a197c9e9e66835e8c51789f7a058b96e96409ab0", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "59fbde11-1426-4450-a194-d9ae3a8d2e22", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "0568fa15a10720712726686688afb9645457fae066e9ebc31956a10ba10b8111", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "761bf6bd-0700-4873-af85-8496830448db", "node_type": "1", "metadata": {}, "hash": "e8a43e256bc187afe201b01859a1207c94c5bf706fa1cb3a9247c894dc27d417", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 16441, "end_char_idx": 21055, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
# Select the unique subcategories from the DataFrame
unique_subcategories = styles_df['articleType'].unique()

# Analyze the image and return the results
analysis = analyze_image(encoded_image, unique_subcategories)
image_analysis = json.loads(analysis)

# Display the image and the analysis results
display(Image(filename=reference_image))
print(image_analysis)
```

Next, we process the output from the image analysis and use it to filter and display matching items from our dataset. Here's a breakdown of the code:

1. **Extracting Image Analysis Results**: We extract the item descriptions, category, and gender from the `image_analysis` dictionary.

2. **Filtering the Dataset**: We filter the `styles_df` DataFrame to include only items that match the gender from the image analysis (or are unisex) and exclude items of the same category as the analyzed image.

3. **Finding Matching Items**: We use the `find_matching_items_with_rag` function to find items in the filtered dataset that match the descriptions extracted from the analyzed image.

4. **Displaying Matching Items**: We create an HTML string to display images of the matching items. We construct the image paths using the item IDs and append each image to the HTML string. Finally, we use `display(HTML(html))` to render the images in the notebook.

This cell effectively demonstrates how to use the results of image analysis to filter a dataset and visually display items that match the analyzed image's characteristics.


```python
# Extract the relevant features from the analysis
item_descs = image_analysis['items']
item_category = image_analysis['category']
item_gender = image_analysis['gender']


# Filter data such that we only look through the items of the same gender (or unisex) and different category
filtered_items = styles_df.loc[styles_df['gender'].isin([item_gender, 'Unisex'])]
filtered_items = filtered_items[filtered_items['articleType'] != item_category]
print(str(len(filtered_items)) + " Remaining Items")

# Find the most similar items based on the input item descriptions
matching_items = find_matching_items_with_rag(filtered_items, item_descs)

# Display the matching items (this will display 2 items for each description in the image analysis)
html = ""
paths = []
for i, item in enumerate(matching_items):
    item_id = item['id']
        
    # Path to the image file
    image_path = f'data/sample_clothes/sample_images/{item_id}.jpg'
    paths.append(image_path)
    html += f'<img src="{image_path}" style="display:inline;margin:1px"/>'

# Print the matching item description as a reminder of what we are looking for
print(item_descs)
# Display the image
display(HTML(html))
```

### Guardrails

In the context of using Large Language Models (LLMs) like GPT-4o mini, "guardrails" refer to mechanisms or checks put in place to ensure that the model's output remains within desired parameters or boundaries. These guardrails are crucial for maintaining the quality and relevance of the model's responses, especially when dealing with complex or nuanced tasks.

Guardrails are useful for several reasons:

1. **Accuracy**: They help ensure that the model's output is accurate and relevant to the input provided.
2. **Consistency**: They maintain consistency in the model's responses, especially when dealing with similar or related inputs.
3. **Safety**: They prevent the model from generating harmful, offensive, or inappropriate content.
4. **Contextual Relevance**: They ensure that the model's output is contextually relevant to the specific task or domain it is being used for.

In our case, we are using GPT-4o mini to analyze fashion images and suggest items that would complement an original outfit. To implement guardrails, we can **refine results**: After obtaining initial suggestions from GPT-4o mini, we can send the original image and the suggested items back to the model. We can then ask GPT-4o mini to evaluate whether each suggested item would indeed be a good fit for the original outfit.

This gives the model the ability to self-correct and adjust its own output based on feedback or additional information. By implementing these guardrails and enabling self-correction, we can enhance the reliability and usefulness of the model's output in the context of fashion analysis and recommendation.

To facilitate this, we write a prompt that asks the LLM for a simple "yes" or "no" answer to the question of whether the suggested items match the original outfit or not. This binary response helps streamline the refinement process and ensures clear and actionable feedback from the model.


key: _node_content
string_value:
{"id_": "761bf6bd-0700-4873-af85-8496830448db", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "437245ec-9ed7-4b92-aadd-05422f4792e9", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "54f90d7499f88d3942fd0d36a197c9e9e66835e8c51789f7a058b96e96409ab0", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "905b75f6-c3ff-4a4e-802a-d17c7baf17ab", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "8b4bbd959c254c6ac61c9eda41e6dd36d2b1d4905900e0d2c381b56db2b34b0d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3df1b3d2-847d-4358-8701-81d9e35fdc1f", "node_type": "1", "metadata": {}, "hash": "c28c47bfbaf2aebf870df6fc4556b8a4fb442d651e652bbcd7fa8a114ee531a7", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 21058, "end_char_idx": 23017, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
def check_match(reference_image_base64, suggested_image_base64):
    response = client.chat.completions.create(
        model=GPT_MODEL,
        messages=[
            {
            "role": "user",
            "content": [
                {
                "type": "text",
                "text": """ You will be given two images of two different items of clothing.
                            Your goal is to decide if the items in the images would work in an outfit together.
                            The first image is the reference item (the item that the user is trying to match with another item).
                            You need to decide if the second item would work well with the reference item.
                            Your response must be a JSON output with the following fields: "answer", "reason".
                            The "answer" field must be either "yes" or "no", depending on whether you think the items would work well together.
                            The "reason" field must be a short explanation of your reasoning for your decision. Do not include the descriptions of the 2 images.
                            Do not include the ```json ``` tag in the output.
                           """,
                },
                {
                "type": "image_url",
                "image_url": {
                    "url": f"data:image/jpeg;base64,{reference_image_base64}",
                },
                },
                {
                "type": "image_url",
                "image_url": {
                    "url": f"data:image/jpeg;base64,{suggested_image_base64}",
                },
                }
            ],
            }
        ],
        max_tokens=300,
    )
    # Extract relevant features from the response
    features = response.choices[0].message.content
    return features
```

Finally, let's determine which of the items identified above truly complement the outfit.


key: _node_content
string_value:
{"id_": "3df1b3d2-847d-4358-8701-81d9e35fdc1f", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "437245ec-9ed7-4b92-aadd-05422f4792e9", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "54f90d7499f88d3942fd0d36a197c9e9e66835e8c51789f7a058b96e96409ab0", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "761bf6bd-0700-4873-af85-8496830448db", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_combine_GPT4o_with_RAG_Outfit_Assistant.ipynb", "title": "How to Combine GPT-4o Mini with RAG - Create a Clothing Matchmaker App", "tokens": 5266, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "9b8f114e34f4493f3c382dbdd949e797deb7a93b5873344bcb73899cb7750256", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 21058, "end_char_idx": 25503, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
def check_match(reference_image_base64, suggested_image_base64):
    response = client.chat.completions.create(
        model=GPT_MODEL,
        messages=[
            {
            "role": "user",
            "content": [
                {
                "type": "text",
                "text": """ You will be given two images of two different items of clothing.
                            Your goal is to decide if the items in the images would work in an outfit together.
                            The first image is the reference item (the item that the user is trying to match with another item).
                            You need to decide if the second item would work well with the reference item.
                            Your response must be a JSON output with the following fields: "answer", "reason".
                            The "answer" field must be either "yes" or "no", depending on whether you think the items would work well together.
                            The "reason" field must be a short explanation of your reasoning for your decision. Do not include the descriptions of the 2 images.
                            Do not include the ```json ``` tag in the output.
                           """,
                },
                {
                "type": "image_url",
                "image_url": {
                    "url": f"data:image/jpeg;base64,{reference_image_base64}",
                },
                },
                {
                "type": "image_url",
                "image_url": {
                    "url": f"data:image/jpeg;base64,{suggested_image_base64}",
                },
                }
            ],
            }
        ],
        max_tokens=300,
    )
    # Extract relevant features from the response
    features = response.choices[0].message.content
    return features
```

Finally, let's determine which of the items identified above truly complement the outfit.


```python
# Select the unique paths for the generated images
paths = list(set(paths))

for path in paths:
    # Encode the test image to base64
    suggested_image = encode_image_to_base64(path)
    
    # Check if the items match
    match = json.loads(check_match(encoded_image, suggested_image))
    
    # Display the image and the analysis results
    if match["answer"] == 'yes':
        display(Image(filename=path))
        print("The items match!")
        print(match["reason"])
```

We can observe that the initial list of potential items has been further refined, resulting in a more curated selection that aligns well with the outfit. Additionally, the model provides explanations for why each item is considered a good match, offering valuable insights into the decision-making process.

### Conclusion

In this Jupyter Notebook, we explored the application of GPT-4o mini and other machine learning techniques to the domain of fashion. We demonstrated how to analyze images of clothing items, extract relevant features, and use this information to find matching items that complement an original outfit. Through the implementation of guardrails and self-correction mechanisms, we refined the model's suggestions to ensure they are accurate and contextually relevant.

This approach has several practical uses in the real world, including:

1. **Personalized Shopping Assistants**: Retailers can use this technology to offer personalized outfit recommendations to customers, enhancing the shopping experience and increasing customer satisfaction.
2. **Virtual Wardrobe Applications**: Users can upload images of their own clothing items to create a virtual wardrobe and receive suggestions for new items that match their existing pieces.
3. **Fashion Design and Styling**: Fashion designers and stylists can use this tool to experiment with different combinations and styles, streamlining the creative process.

However, one of the considerations to keep in mind is **cost**. The use of LLMs and image analysis models can incur costs, especially if used extensively. It's important to consider the cost-effectiveness of implementing these technologies. `gpt-4o-mini` is priced at `$0.01` per 1000 tokens. This adds up to `$0.00255` for one 256px x 256px image.

Overall, this notebook serves as a foundation for further exploration and development in the intersection of fashion and AI, opening doors to more personalized and intelligent fashion recommendation systems.


key: _node_content
string_value:
{"id_": "66b472cc-889c-4eca-94f7-65fcc691f01a", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb", "title": "Fine tuning classification example", "tokens": 3848, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "6522ec4e-6932-4b07-a80a-22c6e45e5602", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb", "title": "Fine tuning classification example", "tokens": 3848, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "ba4e67ea68b645ec93fe770b4d7ccfa221ec7add0c2a439f442571930ab51f9b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ae2525b7-dc94-4253-a2ca-729a310aad17", "node_type": "1", "metadata": {}, "hash": "496b3b34efacd1ef7deb4f5596dae7db9fb3d2f7b5a17acc8f28fc8f1dc7a1df", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2962, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Fine tuning classification example

We will fine-tune a `babbage-002` classifier (replacement for the `ada` models) to distinguish between the two sports: Baseball and Hockey.


```python
from sklearn.datasets import fetch_20newsgroups
import pandas as pd
import openai
import os

client = openai.OpenAI(api_key=os.environ.get("OPENAI_API_KEY", "<your OpenAI API key if not set as env var>"))

categories = ['rec.sport.baseball', 'rec.sport.hockey']
sports_dataset = fetch_20newsgroups(subset='train', shuffle=True, random_state=42, categories=categories)
```

 ## Data exploration
 The newsgroup dataset can be loaded using sklearn. First we will look at the data itself:


```python
print(sports_dataset['data'][0])
```

    From: dougb@comm.mot.com (Doug Bank)
    Subject: Re: Info needed for Cleveland tickets
    Reply-To: dougb@ecs.comm.mot.com
    Organization: Motorola Land Mobile Products Sector
    Distribution: usa
    Nntp-Posting-Host: 145.1.146.35
    Lines: 17
    
    In article <1993Apr1.234031.4950@leland.Stanford.EDU>, bohnert@leland.Stanford.EDU (matthew bohnert) writes:
    
    |> I'm going to be in Cleveland Thursday, April 15 to Sunday, April 18.
    |> Does anybody know if the Tribe will be in town on those dates, and
    |> if so, who're they playing and if tickets are available?
    
    The tribe will be in town from April 16 to the 19th.
    There are ALWAYS tickets available! (Though they are playing Toronto,
    and many Toronto fans make the trip to Cleveland as it is easier to
    get tickets in Cleveland than in Toronto.  Either way, I seriously
    doubt they will sell out until the end of the season.)
    
    -- 
    Doug Bank                       Private Systems Division
    dougb@ecs.comm.mot.com          Motorola Communications Sector
    dougb@nwu.edu                   Schaumburg, Illinois
    dougb@casbah.acns.nwu.edu       708-576-8207                    
    



```python
sports_dataset.target_names[sports_dataset['target'][0]]

```




    'rec.sport.baseball'




```python
len_all, len_baseball, len_hockey = len(sports_dataset.data), len([e for e in sports_dataset.target if e == 0]), len([e for e in sports_dataset.target if e == 1])
print(f"Total examples: {len_all}, Baseball examples: {len_baseball}, Hockey examples: {len_hockey}")
```

    Total examples: 1197, Baseball examples: 597, Hockey examples: 600


One sample from the baseball category can be seen above. It is an email to a mailing list. We can observe that we have 1197 examples in total, which are evenly split between the two sports.

## Data Preparation
We transform the dataset into a pandas dataframe, with a column for prompt and completion. The prompt contains the email from the mailing list, and the completion is a name of the sport, either hockey or baseball. For demonstration purposes only and speed of fine-tuning we take only 300 examples. In a real use case the more examples the better the performance.


key: _node_content
string_value:
{"id_": "ae2525b7-dc94-4253-a2ca-729a310aad17", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb", "title": "Fine tuning classification example", "tokens": 3848, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "6522ec4e-6932-4b07-a80a-22c6e45e5602", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb", "title": "Fine tuning classification example", "tokens": 3848, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "ba4e67ea68b645ec93fe770b4d7ccfa221ec7add0c2a439f442571930ab51f9b", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "66b472cc-889c-4eca-94f7-65fcc691f01a", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb", "title": "Fine tuning classification example", "tokens": 3848, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "c73cfba256d2c6cddab65484c7e7eaad57e366e8dbab269ee19563bff73e566e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1d3e6f59-2bff-44a5-87e7-ef804835d6d0", "node_type": "1", "metadata": {}, "hash": "f88b789bef18a50b8cc6d4dcc834d0b0434aaf41dce7fcab75fb866a03177347", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1931, "end_char_idx": 4391, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
sports_dataset.target_names[sports_dataset['target'][0]]

```




    'rec.sport.baseball'




```python
len_all, len_baseball, len_hockey = len(sports_dataset.data), len([e for e in sports_dataset.target if e == 0]), len([e for e in sports_dataset.target if e == 1])
print(f"Total examples: {len_all}, Baseball examples: {len_baseball}, Hockey examples: {len_hockey}")
```

    Total examples: 1197, Baseball examples: 597, Hockey examples: 600


One sample from the baseball category can be seen above. It is an email to a mailing list. We can observe that we have 1197 examples in total, which are evenly split between the two sports.

## Data Preparation
We transform the dataset into a pandas dataframe, with a column for prompt and completion. The prompt contains the email from the mailing list, and the completion is a name of the sport, either hockey or baseball. For demonstration purposes only and speed of fine-tuning we take only 300 examples. In a real use case the more examples the better the performance.


```python
import pandas as pd

labels = [sports_dataset.target_names[x].split('.')[-1] for x in sports_dataset['target']]
texts = [text.strip() for text in sports_dataset['data']]
df = pd.DataFrame(zip(texts, labels), columns = ['prompt','completion']) #[:300]
df.head()
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>prompt</th>
      <th>completion</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>From: dougb@comm.mot.com (Doug Bank)\nSubject:...</td>
      <td>baseball</td>
    </tr>
    <tr>
      <th>1</th>
      <td>From: gld@cunixb.cc.columbia.edu (Gary L Dare)...</td>
      <td>hockey</td>
    </tr>
    <tr>
      <th>2</th>
      <td>From: rudy@netcom.com (Rudy Wade)\nSubject: Re...</td>
      <td>baseball</td>
    </tr>
    <tr>
      <th>3</th>
      <td>From: monack@helium.gas.uug.arizona.edu (david...</td>
      <td>hockey</td>
    </tr>
    <tr>
      <th>4</th>
      <td>Subject: Let it be Known\nFrom: &lt;ISSBTL@BYUVM....</td>
      <td>baseball</td>
    </tr>
  </tbody>
</table>
</div>



Both baseball and hockey are single tokens. We save the dataset as a jsonl file.


key: _node_content
string_value:
{"id_": "1d3e6f59-2bff-44a5-87e7-ef804835d6d0", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb", "title": "Fine tuning classification example", "tokens": 3848, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "6522ec4e-6932-4b07-a80a-22c6e45e5602", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb", "title": "Fine tuning classification example", "tokens": 3848, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "ba4e67ea68b645ec93fe770b4d7ccfa221ec7add0c2a439f442571930ab51f9b", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ae2525b7-dc94-4253-a2ca-729a310aad17", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb", "title": "Fine tuning classification example", "tokens": 3848, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "4ef8867a316c3d2ddc1484b2ed34eb944ca6378a22a3033ade919c287e40c846", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9bacfa5e-235b-4f10-896a-c22b1a230525", "node_type": "1", "metadata": {}, "hash": "12a332fba1557fc351bbac88bbb8b8d5e0ceb0d2c6c625a740cd6a611d9271ec", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3244, "end_char_idx": 4779, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>prompt</th>
      <th>completion</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>From: dougb@comm.mot.com (Doug Bank)\nSubject:...</td>
      <td>baseball</td>
    </tr>
    <tr>
      <th>1</th>
      <td>From: gld@cunixb.cc.columbia.edu (Gary L Dare)...</td>
      <td>hockey</td>
    </tr>
    <tr>
      <th>2</th>
      <td>From: rudy@netcom.com (Rudy Wade)\nSubject: Re...</td>
      <td>baseball</td>
    </tr>
    <tr>
      <th>3</th>
      <td>From: monack@helium.gas.uug.arizona.edu (david...</td>
      <td>hockey</td>
    </tr>
    <tr>
      <th>4</th>
      <td>Subject: Let it be Known\nFrom: &lt;ISSBTL@BYUVM....</td>
      <td>baseball</td>
    </tr>
  </tbody>
</table>
</div>



Both baseball and hockey are single tokens. We save the dataset as a jsonl file.


```python
df.to_json("sport2.jsonl", orient='records', lines=True)
```

### Data Preparation tool
We can now use a data preparation tool which will suggest a few improvements to our dataset before fine-tuning. Before launching the tool we update the openai library to ensure we're using the latest data preparation tool. We additionally specify `-q` which auto-accepts all suggestions.


key: _node_content
string_value:
{"id_": "9bacfa5e-235b-4f10-896a-c22b1a230525", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb", "title": "Fine tuning classification example", "tokens": 3848, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "6522ec4e-6932-4b07-a80a-22c6e45e5602", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb", "title": "Fine tuning classification example", "tokens": 3848, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "ba4e67ea68b645ec93fe770b4d7ccfa221ec7add0c2a439f442571930ab51f9b", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1d3e6f59-2bff-44a5-87e7-ef804835d6d0", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb", "title": "Fine tuning classification example", "tokens": 3848, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "d3d793e2e2ca9cd6cf1c9f6e2cabcc7c2ccaa088d575d0a5991d20b15510d2c0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9b106b08-fa51-4ded-9618-bae41fead6ff", "node_type": "1", "metadata": {}, "hash": "fe30c63f0f2368bf4efd3b9736e3f67123d12caa2982566be8a35ec763da702c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 4311, "end_char_idx": 7360, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Both baseball and hockey are single tokens. We save the dataset as a jsonl file.


```python
df.to_json("sport2.jsonl", orient='records', lines=True)
```

### Data Preparation tool
We can now use a data preparation tool which will suggest a few improvements to our dataset before fine-tuning. Before launching the tool we update the openai library to ensure we're using the latest data preparation tool. We additionally specify `-q` which auto-accepts all suggestions.


```python
!openai tools fine_tunes.prepare_data -f sport2.jsonl -q
```

    Analyzing...
    
    - Your file contains 1197 prompt-completion pairs
    - Based on your data it seems like you're trying to fine-tune a model for classification
    - For classification, we recommend you try one of the faster and cheaper models, such as `ada`
    - For classification, you can estimate the expected model performance by keeping a held out dataset, which is not used for training
    - There are 11 examples that are very long. These are rows: [134, 200, 281, 320, 404, 595, 704, 838, 1113, 1139, 1174]
    For conditional generation, and for classification the examples shouldn't be longer than 2048 tokens.
    - Your data does not contain a common separator at the end of your prompts. Having a separator string appended to the end of the prompt makes it clearer to the fine-tuned model where the completion should begin. See https://platform.openai.com/docs/guides/fine-tuning/preparing-your-dataset for more detail and examples. If you intend to do open-ended generation, then you should leave the prompts empty
    - The completion should start with a whitespace character (` `). This tends to produce better results due to the tokenization we use. See https://platform.openai.com/docs/guides/fine-tuning/preparing-your-dataset for more details
    
    Based on the analysis we will perform the following actions:
    - [Recommended] Remove 11 long examples [Y/n]: Y
    - [Recommended] Add a suffix separator `\n\n###\n\n` to all prompts [Y/n]: Y
    - [Recommended] Add a whitespace character to the beginning of the completion [Y/n]: Y
    - [Recommended] Would you like to split into training and validation set? [Y/n]: Y
    
    
    Your data will be written to a new JSONL file. Proceed [Y/n]: Y
    
    Wrote modified files to `sport2_prepared_train (1).jsonl` and `sport2_prepared_valid (1).jsonl`
    Feel free to take a look!
    
    Now use that file when fine-tuning:
    > openai api fine_tunes.create -t "sport2_prepared_train (1).jsonl" -v "sport2_prepared_valid (1).jsonl" --compute_classification_metrics --classification_positive_class " baseball"
    
    After you’ve fine-tuned a model, remember that your prompt has to end with the indicator string `\n\n###\n\n` for the model to start generating completions, rather than continuing with the prompt.
    Once your model starts training, it'll approximately take 30.8 minutes to train a `curie` model, and less for `ada` and `babbage`. Queue will approximately take half an hour per job ahead of you.


key: _node_content
string_value:
{"id_": "9b106b08-fa51-4ded-9618-bae41fead6ff", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb", "title": "Fine tuning classification example", "tokens": 3848, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "6522ec4e-6932-4b07-a80a-22c6e45e5602", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb", "title": "Fine tuning classification example", "tokens": 3848, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "ba4e67ea68b645ec93fe770b4d7ccfa221ec7add0c2a439f442571930ab51f9b", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9bacfa5e-235b-4f10-896a-c22b1a230525", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb", "title": "Fine tuning classification example", "tokens": 3848, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "257bb25c7254ee3d5a1c1495182f897ea2ab9ac7c3999e03c71bce050e37bb15", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8e1f1cab-a4d5-4409-a9c4-7fa265c10e99", "node_type": "1", "metadata": {}, "hash": "0f5b50bc048d4ce3b94e62537ac3d47fe58cd5a7c62bc5e30ff6d4c46276f876", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 7363, "end_char_idx": 10399, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The tool helpfully suggests a few improvements to the dataset and splits the dataset into training and validation set.

A suffix between a prompt and a completion is necessary to tell the model that the input text has stopped, and that it now needs to predict the class. Since we use the same separator in each example, the model is able to learn that it is meant to predict either baseball or hockey following the separator.
A whitespace prefix in completions is useful, as most word tokens are tokenized with a space prefix.
The tool also recognized that this is likely a classification task, so it suggested to split the dataset into training and validation datasets. This will allow us to easily measure expected performance on new data.

## Fine-tuning
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.

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. 


```python
train_file = client.files.create(file=open("sport2_prepared_train.jsonl", "rb"), purpose="fine-tune")
valid_file = client.files.create(file=open("sport2_prepared_valid.jsonl", "rb"), purpose="fine-tune")

fine_tuning_job = client.fine_tuning.jobs.create(training_file=train_file.id, validation_file=valid_file.id, model="babbage-002")

print(fine_tuning_job)
```

    FineTuningJob(id='ftjob-REo0uLpriEAm08CBRNDlPJZC', created_at=1704413736, error=None, fine_tuned_model=None, finished_at=None, hyperparameters=Hyperparameters(n_epochs='auto', batch_size='auto', learning_rate_multiplier='auto'), model='babbage-002', object='fine_tuning.job', organization_id='org-9HXYFy8ux4r6aboFyec2OLRf', result_files=[], status='validating_files', trained_tokens=None, training_file='file-82XooA2AUDBAUbN5z2DuKRMs', validation_file='file-wTOcQF8vxQ0Z6fNY2GSm0z4P')


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/)

You can also check on its status programatically:


```python
fine_tune_results = client.fine_tuning.jobs.retrieve(fine_tuning_job.id)
print(fine_tune_results.finished_at)
```

    1704414393


### [Advanced] Results and expected model performance
We can now download the results file to observe the expected performance on a held out validation set.


```python
fine_tune_results = client.fine_tuning.jobs.retrieve(fine_tuning_job.id).result_files
result_file = client.files.retrieve(fine_tune_results[0])
content = client.files.content(result_file.id)
# save content to file
with open("result.csv", "wb") as f:
    f.write(content.text.encode("utf-8"))
```


```python
results = pd.read_csv('result.csv')
results[results['train_accuracy'].notnull()].tail(1)
```


key: _node_content
string_value:
{"id_": "8e1f1cab-a4d5-4409-a9c4-7fa265c10e99", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb", "title": "Fine tuning classification example", "tokens": 3848, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "6522ec4e-6932-4b07-a80a-22c6e45e5602", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb", "title": "Fine tuning classification example", "tokens": 3848, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "ba4e67ea68b645ec93fe770b4d7ccfa221ec7add0c2a439f442571930ab51f9b", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9b106b08-fa51-4ded-9618-bae41fead6ff", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb", "title": "Fine tuning classification example", "tokens": 3848, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "7091c3e25f4f6c0e718a2401c8b1b2848127a60ee5694a5056ea276c2525cbdf", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c646d198-9d6e-4148-a04b-712dbc823d8f", "node_type": "1", "metadata": {}, "hash": "a11a4f4c3079fd66d0e932ca3850d9541077479f5ba9ae281056ed74777849f8", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 9463, "end_char_idx": 11451, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
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/)

You can also check on its status programatically:


```python
fine_tune_results = client.fine_tuning.jobs.retrieve(fine_tuning_job.id)
print(fine_tune_results.finished_at)
```

    1704414393


### [Advanced] Results and expected model performance
We can now download the results file to observe the expected performance on a held out validation set.


```python
fine_tune_results = client.fine_tuning.jobs.retrieve(fine_tuning_job.id).result_files
result_file = client.files.retrieve(fine_tune_results[0])
content = client.files.content(result_file.id)
# save content to file
with open("result.csv", "wb") as f:
    f.write(content.text.encode("utf-8"))
```


```python
results = pd.read_csv('result.csv')
results[results['train_accuracy'].notnull()].tail(1)
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>step</th>
      <th>train_loss</th>
      <th>train_accuracy</th>
      <th>valid_loss</th>
      <th>valid_mean_token_accuracy</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>2843</th>
      <td>2844</td>
      <td>0.0</td>
      <td>1.0</td>
      <td>NaN</td>
      <td>NaN</td>
    </tr>
  </tbody>
</table>
</div>



The accuracy reaches 99.6%. On the plot below we can see how accuracy on the validation set increases during the training run. 


```python
results[results['train_accuracy'].notnull()]['train_accuracy'].plot()
```

## Using the model
We can now call the model to get the predictions.


```python
test = pd.read_json('sport2_prepared_valid.jsonl', lines=True)
test.head()
```


key: _node_content
string_value:
{"id_": "c646d198-9d6e-4148-a04b-712dbc823d8f", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb", "title": "Fine tuning classification example", "tokens": 3848, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "6522ec4e-6932-4b07-a80a-22c6e45e5602", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb", "title": "Fine tuning classification example", "tokens": 3848, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "ba4e67ea68b645ec93fe770b4d7ccfa221ec7add0c2a439f442571930ab51f9b", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8e1f1cab-a4d5-4409-a9c4-7fa265c10e99", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb", "title": "Fine tuning classification example", "tokens": 3848, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "2e86149c4d24752481fc8fe21903146cfe0b46ff496606647776f25c6bb2d2fa", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "12b4f4a9-f91b-4d6a-9ca5-df9c5790d1c5", "node_type": "1", "metadata": {}, "hash": "391b23d57b7bd8beee64c415e326421082260cd52f28cc4176b314032c3d5302", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 10297, "end_char_idx": 12816, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
results = pd.read_csv('result.csv')
results[results['train_accuracy'].notnull()].tail(1)
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>step</th>
      <th>train_loss</th>
      <th>train_accuracy</th>
      <th>valid_loss</th>
      <th>valid_mean_token_accuracy</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>2843</th>
      <td>2844</td>
      <td>0.0</td>
      <td>1.0</td>
      <td>NaN</td>
      <td>NaN</td>
    </tr>
  </tbody>
</table>
</div>



The accuracy reaches 99.6%. On the plot below we can see how accuracy on the validation set increases during the training run. 


```python
results[results['train_accuracy'].notnull()]['train_accuracy'].plot()
```

## Using the model
We can now call the model to get the predictions.


```python
test = pd.read_json('sport2_prepared_valid.jsonl', lines=True)
test.head()
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>prompt</th>
      <th>completion</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>From: gld@cunixb.cc.columbia.edu (Gary L Dare)...</td>
      <td>hockey</td>
    </tr>
    <tr>
      <th>1</th>
      <td>From: smorris@venus.lerc.nasa.gov (Ron Morris ...</td>
      <td>hockey</td>
    </tr>
    <tr>
      <th>2</th>
      <td>From: golchowy@alchemy.chem.utoronto.ca (Geral...</td>
      <td>hockey</td>
    </tr>
    <tr>
      <th>3</th>
      <td>From: krattige@hpcc01.corp.hp.com (Kim Krattig...</td>
      <td>baseball</td>
    </tr>
    <tr>
      <th>4</th>
      <td>From: warped@cs.montana.edu (Doug Dolven)\nSub...</td>
      <td>baseball</td>
    </tr>
  </tbody>
</table>
</div>



We need to use the same separator following the prompt which we used during fine-tuning. In this case it is `\n\n###\n\n`. Since we're concerned with classification, we want the temperature to be as low as possible, and we only require one token completion to determine the prediction of the model.


key: _node_content
string_value:
{"id_": "12b4f4a9-f91b-4d6a-9ca5-df9c5790d1c5", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb", "title": "Fine tuning classification example", "tokens": 3848, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "6522ec4e-6932-4b07-a80a-22c6e45e5602", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb", "title": "Fine tuning classification example", "tokens": 3848, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "ba4e67ea68b645ec93fe770b4d7ccfa221ec7add0c2a439f442571930ab51f9b", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c646d198-9d6e-4148-a04b-712dbc823d8f", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb", "title": "Fine tuning classification example", "tokens": 3848, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "a19df5199e92a644ebcf37b227404bed16d19e754d967212cd5f6786684ab814", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 12518, "end_char_idx": 14628, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
We need to use the same separator following the prompt which we used during fine-tuning. In this case it is `\n\n###\n\n`. Since we're concerned with classification, we want the temperature to be as low as possible, and we only require one token completion to determine the prediction of the model.


```python
ft_model = fine_tune_results.fine_tuned_model

# note that this calls the legacy completions api - https://platform.openai.com/docs/api-reference/completions
res = client.completions.create(model=ft_model, prompt=test['prompt'][0] + '\n\n###\n\n', max_tokens=1, temperature=0)
res.choices[0].text

```




    ' hockey'



To get the log probabilities, we can specify logprobs parameter on the completion request


```python
res = client.completions.create(model=ft_model, prompt=test['prompt'][0] + '\n\n###\n\n', max_tokens=1, temperature=0, logprobs=2)
res.choices[0].logprobs.top_logprobs
```




    [{' hockey': 0.0, ' Hockey': -22.504879}]



We can see that the model predicts hockey as a lot more likely than baseball, which is the correct prediction. By requesting log_probs, we can see the prediction (log) probability for each class.

### Generalization
Interestingly, our fine-tuned classifier is quite versatile. Despite being trained on emails to different mailing lists, it also successfully predicts tweets.


```python
sample_hockey_tweet = """Thank you to the 
@Canes
 and all you amazing Caniacs that have been so supportive! You guys are some of the best fans in the NHL without a doubt! Really excited to start this new chapter in my career with the 
@DetroitRedWings
 !!"""
res = client.completions.create(model=ft_model, prompt=sample_hockey_tweet + '\n\n###\n\n', max_tokens=1, temperature=0, logprobs=2)
res.choices[0].text
```




    ' hockey'




```python
sample_baseball_tweet="""BREAKING: The Tampa Bay Rays are finalizing a deal to acquire slugger Nelson Cruz from the Minnesota Twins, sources tell ESPN."""
res = client.completions.create(model=ft_model, prompt=sample_baseball_tweet + '\n\n###\n\n', max_tokens=1, temperature=0, logprobs=2)
res.choices[0].text
```


key: url
string_value:
https://github.com/openai/openai-cookbook/blob/main/examples/Zero-shot_classification_with_embeddings.ipynb


key: _node_content
string_value:
{"id_": "2793e59c-a7c0-402c-a630-fdb37c38bc18", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Zero-shot_classification_with_embeddings.ipynb", "title": "convert 5-star rating to binary sentiment", "tokens": 1100, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "85bd23b1-db11-47eb-bef2-344b7b9bb36e", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Zero-shot_classification_with_embeddings.ipynb", "title": "convert 5-star rating to binary sentiment", "tokens": 1100, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "8c7751a56222acbe419c31314988a6508627bdf20d976b155f22099978d997b9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "bf626854-4d60-4626-99f5-891075210277", "node_type": "1", "metadata": {}, "hash": "f63bde134c6ccb69a8a48f40a60e1b7740e1ec19f131765c75ec0de4ed998dce", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3402, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
## Zero-shot classification with embeddings

In this notebook we will classify the sentiment of reviews using embeddings and zero labeled data! The dataset is created in the [Get_embeddings_from_dataset Notebook](Get_embeddings_from_dataset.ipynb).

We'll define positive sentiment to be 4- and 5-star reviews, and negative sentiment to be 1- and 2-star reviews. 3-star reviews are considered neutral and we won't use them for this example.

We will perform zero-shot classification by embedding descriptions of each class and then comparing new samples to those class embeddings.


```python
import pandas as pd
import numpy as np
from ast import literal_eval

from sklearn.metrics import classification_report

EMBEDDING_MODEL = "text-embedding-3-small"

datafile_path = "data/fine_food_reviews_with_embeddings_1k.csv"

df = pd.read_csv(datafile_path)
df["embedding"] = df.embedding.apply(literal_eval).apply(np.array)

# convert 5-star rating to binary sentiment
df = df[df.Score != 3]
df["sentiment"] = df.Score.replace({1: "negative", 2: "negative", 4: "positive", 5: "positive"})

```

### Zero-Shot Classification
To perform zero shot classification, we want to predict labels for our samples without any training. To do this, we can simply embed short descriptions of each label, such as positive and negative, and then compare the cosine distance between embeddings of samples and label descriptions. 

The highest similarity label to the sample input is the predicted label. We can also define a prediction score to be the difference between the cosine distance to the positive and to the negative label. This score can be used for plotting a precision-recall curve, which can be used to select a different tradeoff between precision and recall, by selecting a different threshold.


```python
from utils.embeddings_utils import cosine_similarity, get_embedding
from sklearn.metrics import PrecisionRecallDisplay

def evaluate_embeddings_approach(
    labels = ['negative', 'positive'],
    model = EMBEDDING_MODEL,
):
    label_embeddings = [get_embedding(label, model=model) for label in labels]

    def label_score(review_embedding, label_embeddings):
        return cosine_similarity(review_embedding, label_embeddings[1]) - cosine_similarity(review_embedding, label_embeddings[0])

    probas = df["embedding"].apply(lambda x: label_score(x, label_embeddings))
    preds = probas.apply(lambda x: 'positive' if x>0 else 'negative')

    report = classification_report(df.sentiment, preds)
    print(report)

    display = PrecisionRecallDisplay.from_predictions(df.sentiment, probas, pos_label='positive')
    _ = display.ax_.set_title("2-class Precision-Recall curve")

evaluate_embeddings_approach(labels=['negative', 'positive'], model=EMBEDDING_MODEL)

```

                  precision    recall  f1-score   support
    
        negative       0.54      0.92      0.68       136
        positive       0.98      0.87      0.92       789
    
        accuracy                           0.87       925
       macro avg       0.76      0.89      0.80       925
    weighted avg       0.92      0.87      0.89       925
    



    
![png](output_3_1.png)
    


We can see that this classifier already performs extremely well. We used similarity embeddings, and the simplest possible label name. Let's try to improve on this by using more descriptive label names, and search embeddings.


key: _node_content
string_value:
{"id_": "bf626854-4d60-4626-99f5-891075210277", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Zero-shot_classification_with_embeddings.ipynb", "title": "convert 5-star rating to binary sentiment", "tokens": 1100, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "85bd23b1-db11-47eb-bef2-344b7b9bb36e", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Zero-shot_classification_with_embeddings.ipynb", "title": "convert 5-star rating to binary sentiment", "tokens": 1100, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "8c7751a56222acbe419c31314988a6508627bdf20d976b155f22099978d997b9", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2793e59c-a7c0-402c-a630-fdb37c38bc18", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Zero-shot_classification_with_embeddings.ipynb", "title": "convert 5-star rating to binary sentiment", "tokens": 1100, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "ec97be1b3f6e7a2345b3ebbbed2cbd3f9be6f567e25e52e14ff542f6bbf8efe8", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1794, "end_char_idx": 4761, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
from utils.embeddings_utils import cosine_similarity, get_embedding
from sklearn.metrics import PrecisionRecallDisplay

def evaluate_embeddings_approach(
    labels = ['negative', 'positive'],
    model = EMBEDDING_MODEL,
):
    label_embeddings = [get_embedding(label, model=model) for label in labels]

    def label_score(review_embedding, label_embeddings):
        return cosine_similarity(review_embedding, label_embeddings[1]) - cosine_similarity(review_embedding, label_embeddings[0])

    probas = df["embedding"].apply(lambda x: label_score(x, label_embeddings))
    preds = probas.apply(lambda x: 'positive' if x>0 else 'negative')

    report = classification_report(df.sentiment, preds)
    print(report)

    display = PrecisionRecallDisplay.from_predictions(df.sentiment, probas, pos_label='positive')
    _ = display.ax_.set_title("2-class Precision-Recall curve")

evaluate_embeddings_approach(labels=['negative', 'positive'], model=EMBEDDING_MODEL)

```

                  precision    recall  f1-score   support
    
        negative       0.54      0.92      0.68       136
        positive       0.98      0.87      0.92       789
    
        accuracy                           0.87       925
       macro avg       0.76      0.89      0.80       925
    weighted avg       0.92      0.87      0.89       925
    



    
![png](output_3_1.png)
    


We can see that this classifier already performs extremely well. We used similarity embeddings, and the simplest possible label name. Let's try to improve on this by using more descriptive label names, and search embeddings.


```python
evaluate_embeddings_approach(labels=['An Amazon review with a negative sentiment.', 'An Amazon review with a positive sentiment.'])

```

                  precision    recall  f1-score   support
    
        negative       0.76      0.96      0.85       136
        positive       0.99      0.95      0.97       789
    
        accuracy                           0.95       925
       macro avg       0.88      0.96      0.91       925
    weighted avg       0.96      0.95      0.95       925
    



    
![png](output_5_1.png)
    


Using the search embeddings and descriptive names leads to an additional improvement in performance.


```python
evaluate_embeddings_approach(labels=['An Amazon review with a negative sentiment.', 'An Amazon review with a positive sentiment.'])

```

                  precision    recall  f1-score   support
    
        negative       0.76      0.96      0.85       136
        positive       0.99      0.95      0.97       789
    
        accuracy                           0.95       925
       macro avg       0.88      0.96      0.91       925
    weighted avg       0.96      0.95      0.95       925
    



    
![png](output_7_1.png)
    


As shown above, zero-shot classification with embeddings can lead to great results, especially when the labels are more descriptive than just simple words.


key: url
string_value:
https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_finding_nearby_places.ipynb


key: _node_content
string_value:
{"id_": "2b00237f-e1d9-4385-9173-616ea8878a8a", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_finding_nearby_places.ipynb", "title": "Function calling for nearby places: Leveraging the Google Places API and customer profiles", "tokens": 3051, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "fc02d140-d995-403e-bcdc-0522f07b649e", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_finding_nearby_places.ipynb", "title": "Function calling for nearby places: Leveraging the Google Places API and customer profiles", "tokens": 3051, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "ae144e3e2e57460a535be1bf281347c7489ba13f41dc118da7554305a299cf35", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5ffd19d5-5399-4551-b639-c39359f0a1ae", "node_type": "1", "metadata": {}, "hash": "bea9ed1ddf87d57e70d5b8fd7adb7e8b73d56224a723751484ad8cd4409cb998", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3298, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Function calling for nearby places: Leveraging the Google Places API and customer profiles

This notebook is centered around the integration of the Google Places API and custom user profiles to enhance location-based searches. Our approach involves using the Google Places API in combination with user preferences, aiming to make location discovery more personal and relevant. Please note that while we focus on the Google Places API in this instance, there are numerous other APIs you could explore and apply in a similar fashion.

We'll explore the application of three main components:

- Customer profile: This mock profile captures individual preferences for types of places (e.g., restaurants, parks, museums), budget, preferred ratings, and other specific requirements. 

- Google Places API: This API provides real-time data about nearby places. It factors in various data points such as ratings, types of venues, costs, and more from the locations around you.

- Function calling: A single command such as "I'm hungry" or "I want to visit a museum" activates the function which combines the user profile data and Google Places API to identify suitable venues.

This notebook introduces two primary use cases:

- Profile-based recommendations: Learn how to create a user profile and make place recommendations based on individual preferences.

- API integration with function calling: Understand how to integrate and call Google Places API effectively to source real-time data of various places using function calling.

Please note that while this system is highly versatile, its effectiveness may vary based on user preferences and available place data. For the purposes of this notebook, the customer data is fake and the location is hardcoded. 

## Setup

Google Places API

To use the Google Places API, you'll need two things:

- Google Account: If you don't already have one, you will need to create a Google account.

- Google Places API Key: The API key is a unique identifier that is used to authenticate requests associated with your project for usage and billing purposes. You can get your API key from the [Google Cloud Console](https://console.cloud.google.com/getting-started?authuser=1). 



Please note that Google Places API is a paid service, and the cost is associated with the number of API calls made. Keep track of your usage to avoid any unexpected charges.



The requests library is also needed, you can download it by using the following command: 

```python
pip install requests


```python
import json
from openai import OpenAI
import os
import requests

client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY", "<your OpenAI API key if not set as env var>"))
```

In this code snippet, we are defining a function `fetch_customer_profile` that accepts a `user_id` and returns a mock user profile.

This function simulates an API call that fetches user data from a database. For this demo, we're using hard-coded data. The user profile contains various details such as the user's location (set to the coordinates of the Golden Gate Bridge for this example), preferences in food and activities, app usage metrics, recent interactions, and user rank.

In a production environment, you would replace this hard-coded data with a real API call to your user database.


key: _node_content
string_value:
{"id_": "5ffd19d5-5399-4551-b639-c39359f0a1ae", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_finding_nearby_places.ipynb", "title": "Function calling for nearby places: Leveraging the Google Places API and customer profiles", "tokens": 3051, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "fc02d140-d995-403e-bcdc-0522f07b649e", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_finding_nearby_places.ipynb", "title": "Function calling for nearby places: Leveraging the Google Places API and customer profiles", "tokens": 3051, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "ae144e3e2e57460a535be1bf281347c7489ba13f41dc118da7554305a299cf35", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2b00237f-e1d9-4385-9173-616ea8878a8a", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_finding_nearby_places.ipynb", "title": "Function calling for nearby places: Leveraging the Google Places API and customer profiles", "tokens": 3051, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "68b73559efc71fff382909a8fa9363c0139e031c4e75f4541af62dcd513baa50", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "191bce70-dca5-4f32-a5c5-4992c3464961", "node_type": "1", "metadata": {}, "hash": "4206d179f50d496b05cd0ba193a03ec5c8afdff2f7ac7d64d550c45ca96f8ac0", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2217, "end_char_idx": 5838, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Please note that Google Places API is a paid service, and the cost is associated with the number of API calls made. Keep track of your usage to avoid any unexpected charges.



The requests library is also needed, you can download it by using the following command: 

```python
pip install requests


```python
import json
from openai import OpenAI
import os
import requests

client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY", "<your OpenAI API key if not set as env var>"))
```

In this code snippet, we are defining a function `fetch_customer_profile` that accepts a `user_id` and returns a mock user profile.

This function simulates an API call that fetches user data from a database. For this demo, we're using hard-coded data. The user profile contains various details such as the user's location (set to the coordinates of the Golden Gate Bridge for this example), preferences in food and activities, app usage metrics, recent interactions, and user rank.

In a production environment, you would replace this hard-coded data with a real API call to your user database.



```python
def fetch_customer_profile(user_id):
    # You can replace this with a real API call in the production code
    if user_id == "user1234":
        return {
            "name": "John Doe",
            "location": {
                "latitude": 37.7955,
                "longitude": -122.4026,
            },
            "preferences": {
                "food": ["Italian", "Sushi"],
                "activities": ["Hiking", "Reading"],
            },
            "behavioral_metrics": {
                "app_usage": {
                    "daily": 2,  # hours
                    "weekly": 14  # hours
                },
                "favourite_post_categories": ["Nature", "Food", "Books"],
                "active_time": "Evening",
            },
            "recent_searches": ["Italian restaurants nearby", "Book clubs"],
            "recent_interactions": ["Liked a post about 'Best Pizzas in New York'", "Commented on a post about 'Central Park Trails'"],
            "user_rank": "Gold",  # based on some internal ranking system
        }
    else:
        return None

```

## Requesting and processing data from Google Places API

The function call_google_places_api serves to request information from the Google Places API and provide a list of the top two places based on a given place_type and optional food_preference. We've limited this function to the top two results to manage usage since this is a paid service. However, you can modify this to retrieve any number of results as per your requirement.

The function is configured with a hardcoded location (set to the coordinates of the Transamerica Pyramid), your Google API key, and specific request parameters. Depending on the place_type, it formulates the appropriate API request URL. If the place_type is a restaurant and a food_preference is specified, it is included in the API request.

After sending the GET request, the function checks the response status. If it's successful, it processes the JSON response, extracts the relevant details using the get_place_details function, and returns them in a human-readable format. If the request fails, it prints out the error for debugging.

The get_place_details function is used to retrieve more detailed information about a place, given its place_id. It sends a GET request to the Google Place Details API and returns the result if the request is successful. If the request fails, it prints out the error for debugging.

Both functions handle exceptions and return an error message if something goes wrong.


key: _node_content
string_value:
{"id_": "191bce70-dca5-4f32-a5c5-4992c3464961", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_finding_nearby_places.ipynb", "title": "Function calling for nearby places: Leveraging the Google Places API and customer profiles", "tokens": 3051, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "fc02d140-d995-403e-bcdc-0522f07b649e", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_finding_nearby_places.ipynb", "title": "Function calling for nearby places: Leveraging the Google Places API and customer profiles", "tokens": 3051, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "ae144e3e2e57460a535be1bf281347c7489ba13f41dc118da7554305a299cf35", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5ffd19d5-5399-4551-b639-c39359f0a1ae", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_finding_nearby_places.ipynb", "title": "Function calling for nearby places: Leveraging the Google Places API and customer profiles", "tokens": 3051, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "bbf9b65cb2c334bea8b19255d272bedc0cc994ebae50e062bd92d08f2d69e0a3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "847c2193-6813-4f85-944e-ee38aaf78da7", "node_type": "1", "metadata": {}, "hash": "160df5a76f123e402041069ca73dfcd0cf47588b2631860c0a3ef77e7bf98fad", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5842, "end_char_idx": 8960, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
def get_place_details(place_id, api_key):
    URL = f"https://maps.googleapis.com/maps/api/place/details/json?place_id={place_id}&key={api_key}"
    response = requests.get(URL)
    if response.status_code == 200:
        result = json.loads(response.content)["result"]
        return result
    else:
        print(f"Google Place Details API request failed with status code {response.status_code}")
        print(f"Response content: {response.content}")
        return None

```


```python
def call_google_places_api(user_id, place_type, food_preference=None):
    try:
        # Fetch customer profile
        customer_profile = fetch_customer_profile(user_id)
        if customer_profile is None:
            return "I couldn't find your profile. Could you please verify your user ID?"

        # Get location from customer profile
        lat = customer_profile["location"]["latitude"]
        lng = customer_profile["location"]["longitude"]

        API_KEY = os.getenv('GOOGLE_PLACES_API_KEY')  # retrieve API key from environment variable
        LOCATION = f"{lat},{lng}"
        RADIUS = 500  # search within a radius of 500 meters
        TYPE = place_type

        # If the place_type is restaurant and food_preference is not None, include it in the API request
        if place_type == 'restaurant' and food_preference:
            URL = f"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={LOCATION}&radius={RADIUS}&type={TYPE}&keyword={food_preference}&key={API_KEY}"
        else:
            URL = f"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={LOCATION}&radius={RADIUS}&type={TYPE}&key={API_KEY}"

        response = requests.get(URL)
        if response.status_code == 200:
            results = json.loads(response.content)["results"]
            places = []
            for place in results[:2]:  # limit to top 2 results
                place_id = place.get("place_id")
                place_details = get_place_details(place_id, API_KEY)  # Get the details of the place

                place_name = place_details.get("name", "N/A")
                place_types = next((t for t in place_details.get("types", []) if t not in ["food", "point_of_interest"]), "N/A")  # Get the first type of the place, excluding "food" and "point_of_interest"
                place_rating = place_details.get("rating", "N/A")  # Get the rating of the place
                total_ratings = place_details.get("user_ratings_total", "N/A")  # Get the total number of ratings
                place_address = place_details.get("vicinity", "N/A")  # Get the vicinity of the place

                if ',' in place_address:  # If the address contains a comma
                    street_address = place_address.split(',')[0]  # Split by comma and keep only the first part
                else:
                    street_address = place_address

                # Prepare the output string for this place
                place_info = f"{place_name} is a {place_types} located at {street_address}. It has a rating of {place_rating} based on {total_ratings} user reviews."


key: _node_content
string_value:
{"id_": "847c2193-6813-4f85-944e-ee38aaf78da7", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_finding_nearby_places.ipynb", "title": "Function calling for nearby places: Leveraging the Google Places API and customer profiles", "tokens": 3051, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "fc02d140-d995-403e-bcdc-0522f07b649e", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_finding_nearby_places.ipynb", "title": "Function calling for nearby places: Leveraging the Google Places API and customer profiles", "tokens": 3051, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "ae144e3e2e57460a535be1bf281347c7489ba13f41dc118da7554305a299cf35", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "191bce70-dca5-4f32-a5c5-4992c3464961", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_finding_nearby_places.ipynb", "title": "Function calling for nearby places: Leveraging the Google Places API and customer profiles", "tokens": 3051, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "53d44e03dcc1c84ad4d208fb1daece51853f870f8ec93d66bc7f7f1a238e9749", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2d05f5c8-7e77-4878-8db3-3e6a22a0a754", "node_type": "1", "metadata": {}, "hash": "2e77f5432fdc227d1171ed7416c78e39fdee1a5138525b779e7c5cc4f94ac18d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 8887, "end_char_idx": 10962, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
It has a rating of {place_rating} based on {total_ratings} user reviews."

                places.append(place_info)

            return places
        else:
            print(f"Google Places API request failed with status code {response.status_code}")
            print(f"Response content: {response.content}")  # print out the response content for debugging
            return []
    except Exception as e:
        print(f"Error during the Google Places API call: {e}")
        return []

```

## Generating user-specific recommendations with GPT-3.5-Turbo and Google Places API

The function `provide_user_specific_recommendations` interacts with GPT-3.5-Turbo and the Google Places API to provide responses tailored to a user's preferences and location.

First, it fetches the customer's profile using their `user_id`. If no profile is found, it returns an error message.

With a valid profile, it extracts the customer's food preferences and then interacts with the OpenAI model. It provides an initial system message, giving context to the AI model about its role, user preferences, and the usage of the Google Places API function.

The user input is also sent to the model as a message, and the function `call_google_places_api` is defined in the `functions` parameter for the AI model to call as needed.

Finally, it processes the model's response. If the model makes a function call to the Google Places API, the function is executed with the appropriate arguments, and the names of nearby places are returned. If there are no such places or the request isn't understood, appropriate error messages are returned.



```python
def provide_user_specific_recommendations(user_input, user_id):
    customer_profile = fetch_customer_profile(user_id)
    if customer_profile is None:
        return "I couldn't find your profile. Could you please verify your user ID?"

    customer_profile_str = json.dumps(customer_profile)

    food_preference = customer_profile.get('preferences', {}).get('food', [])[0] if customer_profile.get('preferences', {}).get('food') else None


key: _node_content
string_value:
{"id_": "2d05f5c8-7e77-4878-8db3-3e6a22a0a754", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_finding_nearby_places.ipynb", "title": "Function calling for nearby places: Leveraging the Google Places API and customer profiles", "tokens": 3051, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "fc02d140-d995-403e-bcdc-0522f07b649e", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_finding_nearby_places.ipynb", "title": "Function calling for nearby places: Leveraging the Google Places API and customer profiles", "tokens": 3051, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "ae144e3e2e57460a535be1bf281347c7489ba13f41dc118da7554305a299cf35", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "847c2193-6813-4f85-944e-ee38aaf78da7", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_finding_nearby_places.ipynb", "title": "Function calling for nearby places: Leveraging the Google Places API and customer profiles", "tokens": 3051, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "6331a5d24aa54b5764619c444db9926655403d17173fd4a4a6ca050778f38540", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "40ad23d3-7f34-41b4-b3b3-52ee0d86cf1e", "node_type": "1", "metadata": {}, "hash": "8020961bdbe50a065e95d60ec2e433250468fad0dcb436760ea84145f2c98674", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 9646, "end_char_idx": 13868, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
First, it fetches the customer's profile using their `user_id`. If no profile is found, it returns an error message.

With a valid profile, it extracts the customer's food preferences and then interacts with the OpenAI model. It provides an initial system message, giving context to the AI model about its role, user preferences, and the usage of the Google Places API function.

The user input is also sent to the model as a message, and the function `call_google_places_api` is defined in the `functions` parameter for the AI model to call as needed.

Finally, it processes the model's response. If the model makes a function call to the Google Places API, the function is executed with the appropriate arguments, and the names of nearby places are returned. If there are no such places or the request isn't understood, appropriate error messages are returned.



```python
def provide_user_specific_recommendations(user_input, user_id):
    customer_profile = fetch_customer_profile(user_id)
    if customer_profile is None:
        return "I couldn't find your profile. Could you please verify your user ID?"

    customer_profile_str = json.dumps(customer_profile)

    food_preference = customer_profile.get('preferences', {}).get('food', [])[0] if customer_profile.get('preferences', {}).get('food') else None


    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
    {
        "role": "system",
        "content": f"You are a sophisticated AI assistant, a specialist in user intent detection and interpretation. Your task is to perceive and respond to the user's needs, even when they're expressed in an indirect or direct manner. You excel in recognizing subtle cues: for example, if a user states they are 'hungry', you should assume they are seeking nearby dining options such as a restaurant or a cafe. If they indicate feeling 'tired', 'weary', or mention a long journey, interpret this as a request for accommodation options like hotels or guest houses. However, remember to navigate the fine line of interpretation and assumption: if a user's intent is unclear or can be interpreted in multiple ways, do not hesitate to politely ask for additional clarification. Make sure to tailor your responses to the user based on their preferences and past experiences which can be found here {customer_profile_str}"
    },
    {"role": "user", "content": user_input}
],
        temperature=0,
        tools=[
            {
                "type": "function",
                "function" : {
                    "name": "call_google_places_api",
                    "description": "This function calls the Google Places API to find the top places of a specified type near a specific location. It can be used when a user expresses a need (e.g., feeling hungry or tired) or wants to find a certain type of place (e.g., restaurant or hotel).",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "place_type": {
                                "type": "string",
                                "description": "The type of place to search for."
                            }
                        }
                    },
                    "result": {
                        "type": "array",
                        "items": {
                            "type": "string"
                        }
                    }
                }
            }
        ],
    )

    print(response.choices[0].message.tool_calls)

    if response.choices[0].finish_reason=='tool_calls':
        function_call = response.choices[0].message.tool_calls[0].function
        if function_call.name == "call_google_places_api":
            place_type = json.loads(function_call.arguments)["place_type"]
            places = call_google_places_api(user_id, place_type, food_preference)
            if places:  # If the list of places is not empty
                return f"Here are some places you might be interested in: {' '.join(places)}"
            else:
                return "I couldn't find any places of interest nearby."

    return "I am sorry, but I could not understand your request."


key: _node_content
string_value:
{"id_": "40ad23d3-7f34-41b4-b3b3-52ee0d86cf1e", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_finding_nearby_places.ipynb", "title": "Function calling for nearby places: Leveraging the Google Places API and customer profiles", "tokens": 3051, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "fc02d140-d995-403e-bcdc-0522f07b649e", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_finding_nearby_places.ipynb", "title": "Function calling for nearby places: Leveraging the Google Places API and customer profiles", "tokens": 3051, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "ae144e3e2e57460a535be1bf281347c7489ba13f41dc118da7554305a299cf35", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2d05f5c8-7e77-4878-8db3-3e6a22a0a754", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_finding_nearby_places.ipynb", "title": "Function calling for nearby places: Leveraging the Google Places API and customer profiles", "tokens": 3051, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "a86ac5848624685063ce47ee6d5e2e4c7331e778d6f93774f34fc9612df62534", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 13871, "end_char_idx": 14870, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```

## Executing user-specific recommendations

Upon execution, the function fetches the user's profile, interacts with the AI model, processes the model's response, calls the Google Places API if necessary, and ultimately returns a list of recommendations tailored to the user's preferences and location. The printed output would consist of these personalized recommendations.



```python
user_id = "user1234"
user_input = "I'm hungry"
output = provide_user_specific_recommendations(user_input, user_id)
print(output)

```

    [ChatCompletionMessageToolCall(id='call_Q1mXIi7D6GhobfE4tkruX7nB', function=Function(arguments='{\n  "place_type": "restaurant"\n}', name='call_google_places_api'), type='function')]
    Here are some places you might be interested in: Sotto Mare is a restaurant located at 552 Green Street. It has a rating of 4.6 based on 3765 user reviews. Mona Lisa Restaurant is a restaurant located at 353 Columbus Avenue #3907. It has a rating of 4.4 based on 1888 user reviews.


key: _node_content
string_value:
{"id_": "8f733195-f94c-40e8-84a3-8c3da49eb53b", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "44cc12a7-4de4-4632-929b-400a14fd6543", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "3e04f35828f454f6d816ce30a12988ae3c465da006c47f77279a9443341ef664", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2e6d3747-3b7a-4cd7-9df3-5c1121a6115d", "node_type": "1", "metadata": {}, "hash": "1a0fd541b0b3735b5aad881b2f8c784bf9b97664e71f42627aa4fa1d475152f6", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3533, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Whisper prompting guide

OpenAI's audio transcription API has an optional parameter called `prompt`.

The prompt is intended to help stitch together multiple audio segments. By submitting the prior segment's transcript via the prompt, the Whisper model can use that context to better understand the speech and maintain a consistent writing style.

However, prompts do not need to be genuine transcripts from prior audio segments. _Fictitious_ prompts can be submitted to steer the model to use particular spellings or styles.

This notebook shares two techniques for using fictitious prompts to steer the model outputs:

- **Transcript generation**: GPT can convert instructions into fictitious transcripts for Whisper to emulate. 
- **Spelling guide**: A spelling guide can tell the model how to spell names of people, products, companies, etc.

These techniques are not especially reliable, but can be useful in some situations.

## Comparison with GPT prompting

Prompting Whisper is not the same as prompting GPT. For example, if you submit an attempted instruction like "Format lists in Markdown format", the model will not comply, as it follows the style of the prompt, rather than any instructions contained within.

In addition, the prompt is limited to only 224 tokens. If the prompt is longer than 224 tokens, only the final 224 tokens of the prompt will be considered; all prior tokens will be silently ignored. The tokenizer used is the [multilingual Whisper tokenizer](https://github.com/openai/whisper/blob/main/whisper/tokenizer.py#L361).

To get good results, craft examples that portray your desired style.

## Setup

To get started, let's:
- Import the OpenAI Python library (if you don't have it, you'll need to install it with `pip install openai`)
- Download a few example audio files


```python
# imports
from openai import OpenAI  # for making OpenAI API calls
import urllib  # for downloading example audio files
import os

client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY", "<your OpenAI API key if not set as env var>"))
```


```python
# set download paths
up_first_remote_filepath = "https://cdn.openai.com/API/examples/data/upfirstpodcastchunkthree.wav"
bbq_plans_remote_filepath = "https://cdn.openai.com/API/examples/data/bbq_plans.wav"
product_names_remote_filepath = "https://cdn.openai.com/API/examples/data/product_names.wav"

# set local save locations
up_first_filepath = "data/upfirstpodcastchunkthree.wav"
bbq_plans_filepath = "data/bbq_plans.wav"
product_names_filepath = "data/product_names.wav"

# download example audio files and save locally
urllib.request.urlretrieve(up_first_remote_filepath, up_first_filepath)
urllib.request.urlretrieve(bbq_plans_remote_filepath, bbq_plans_filepath)
urllib.request.urlretrieve(product_names_remote_filepath, product_names_filepath)

```




    ('data/product_names.wav', <http.client.HTTPMessage at 0x1105ac490>)



## As a baseline, we'll transcribe an NPR podcast segment

Our audio file for this example will be a segment of the NPR podcast, [_Up First_](https://www.npr.org/podcasts/510318/up-first). 

Let's get our baseline transcription, then introduce prompts. 


```python
# define a wrapper function for seeing how prompts affect transcriptions
def transcribe(audio_filepath, prompt: str) -> str:
    """Given a prompt, transcribe the audio file."""
    transcript = client.audio.transcriptions.create(
        file=open(audio_filepath, "rb"),
        model="whisper-1",
        prompt=prompt,
    )
    return transcript.text

```


key: _node_content
string_value:
{"id_": "2e6d3747-3b7a-4cd7-9df3-5c1121a6115d", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "44cc12a7-4de4-4632-929b-400a14fd6543", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "3e04f35828f454f6d816ce30a12988ae3c465da006c47f77279a9443341ef664", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8f733195-f94c-40e8-84a3-8c3da49eb53b", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "91b4e24d4c29d9754e5aa359c3270c0ce01a186a9fca9c1ab7f5646aed80e6c2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1b2c6b24-16c6-463e-ac48-5366100a4800", "node_type": "1", "metadata": {}, "hash": "db46000f6222a005e9933d2b651195d3117f467c76567fcc3860d7b8296b365a", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2062, "end_char_idx": 5044, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
# set download paths
up_first_remote_filepath = "https://cdn.openai.com/API/examples/data/upfirstpodcastchunkthree.wav"
bbq_plans_remote_filepath = "https://cdn.openai.com/API/examples/data/bbq_plans.wav"
product_names_remote_filepath = "https://cdn.openai.com/API/examples/data/product_names.wav"

# set local save locations
up_first_filepath = "data/upfirstpodcastchunkthree.wav"
bbq_plans_filepath = "data/bbq_plans.wav"
product_names_filepath = "data/product_names.wav"

# download example audio files and save locally
urllib.request.urlretrieve(up_first_remote_filepath, up_first_filepath)
urllib.request.urlretrieve(bbq_plans_remote_filepath, bbq_plans_filepath)
urllib.request.urlretrieve(product_names_remote_filepath, product_names_filepath)

```




    ('data/product_names.wav', <http.client.HTTPMessage at 0x1105ac490>)



## As a baseline, we'll transcribe an NPR podcast segment

Our audio file for this example will be a segment of the NPR podcast, [_Up First_](https://www.npr.org/podcasts/510318/up-first). 

Let's get our baseline transcription, then introduce prompts. 


```python
# define a wrapper function for seeing how prompts affect transcriptions
def transcribe(audio_filepath, prompt: str) -> str:
    """Given a prompt, transcribe the audio file."""
    transcript = client.audio.transcriptions.create(
        file=open(audio_filepath, "rb"),
        model="whisper-1",
        prompt=prompt,
    )
    return transcript.text

```


```python
# baseline transcription with no prompt
transcribe(up_first_filepath, prompt="")
```




    "I stick contacts in my eyes. Do you really? Yeah. That works okay? You don't have to, like, just kind of pain in the butt every day to do that? No, it is. It is. And I sometimes just kind of miss the eye. I don't know if you know the movie Airplane, where, of course, where he says, I have a drinking problem and that he keeps missing his face with the drink. That's me and the contact lens. Surely, you must know that I know the movie Airplane. I do. I do know that. Stop calling me Shirley. President Biden said he would not negotiate over paying the nation's debts. But he is meeting today with House Speaker Kevin McCarthy. Other leaders of Congress will also attend. So how much progress can they make? I'm E. Martinez with Steve Inskeep, and this is Up First from NPR News. Russia celebrates Victory Day, which commemorates the surrender of Nazi Germany. Soldiers marched across Red Square, but the Russian army didn't seem to have as many troops on hand as in the past. So what does this ritual say about the war Russia is fighting right now?"



## Transcripts follow the style of the prompt

In the unprompted transcript, 'President Biden' is capitalized. However, if we pass in a fictitious prompt of 'president biden' in lowercase, Whisper matches the style and generates a transcript in all lowercase.


```python
# lowercase prompt
transcribe(up_first_filepath, prompt="president biden")
```


key: _node_content
string_value:
{"id_": "1b2c6b24-16c6-463e-ac48-5366100a4800", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "44cc12a7-4de4-4632-929b-400a14fd6543", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "3e04f35828f454f6d816ce30a12988ae3c465da006c47f77279a9443341ef664", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2e6d3747-3b7a-4cd7-9df3-5c1121a6115d", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "0b0fcaaf6e9d6a21d0f2de673b4d4a85b5604e295ca1db2ea9d7a89c1f3115e9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a79b3374-d333-4ea2-a2b5-e68fc7ae9260", "node_type": "1", "metadata": {}, "hash": "8f236fbf81ffce49a518074ab9f0193acc9760c153e327a834a918db76ecbbf3", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3536, "end_char_idx": 6326, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
# baseline transcription with no prompt
transcribe(up_first_filepath, prompt="")
```




    "I stick contacts in my eyes. Do you really? Yeah. That works okay? You don't have to, like, just kind of pain in the butt every day to do that? No, it is. It is. And I sometimes just kind of miss the eye. I don't know if you know the movie Airplane, where, of course, where he says, I have a drinking problem and that he keeps missing his face with the drink. That's me and the contact lens. Surely, you must know that I know the movie Airplane. I do. I do know that. Stop calling me Shirley. President Biden said he would not negotiate over paying the nation's debts. But he is meeting today with House Speaker Kevin McCarthy. Other leaders of Congress will also attend. So how much progress can they make? I'm E. Martinez with Steve Inskeep, and this is Up First from NPR News. Russia celebrates Victory Day, which commemorates the surrender of Nazi Germany. Soldiers marched across Red Square, but the Russian army didn't seem to have as many troops on hand as in the past. So what does this ritual say about the war Russia is fighting right now?"



## Transcripts follow the style of the prompt

In the unprompted transcript, 'President Biden' is capitalized. However, if we pass in a fictitious prompt of 'president biden' in lowercase, Whisper matches the style and generates a transcript in all lowercase.


```python
# lowercase prompt
transcribe(up_first_filepath, prompt="president biden")
```




    "I stick contacts in my eyes. Do you really? Yeah. That works okay? You don't have to, like, just kind of pain in the butt every day to do that? No, it is. It is. And I sometimes just kind of miss the eye. I don't know if you know the movie Airplane? Yes. Of course. Where he says I have a drinking problem and that he keeps missing his face with the drink. That's me and the contact lens. Surely, you must know that I know the movie Airplane. I do. I do know that. Don't call me Shirley. Stop calling me Shirley. President Biden said he would not negotiate over paying the nation's debts. But he is meeting today with House Speaker Kevin McCarthy. Other leaders of Congress will also attend. So how much progress can they make? I'm E. Martinez with Steve Inskeep and this is Up First from NPR News. Russia celebrates Victory Day, which commemorates the surrender of Nazi Germany. Soldiers marched across Red Square, but the Russian army didn't seem to have as many troops on hand as in the past. So what does this ritual say about the war Russia is fighting right now?"



Be aware that when prompts are short, Whisper may be less reliable at following their style.


```python
# short prompts are less reliable
transcribe(up_first_filepath, prompt="president biden.")
```


key: _node_content
string_value:
{"id_": "a79b3374-d333-4ea2-a2b5-e68fc7ae9260", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "44cc12a7-4de4-4632-929b-400a14fd6543", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "3e04f35828f454f6d816ce30a12988ae3c465da006c47f77279a9443341ef664", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1b2c6b24-16c6-463e-ac48-5366100a4800", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "6f57ba47f131e38054d8a137eb4d549ce51a6a2fc4f9a9e5c1f5ca5968606eda", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b4fa56b2-57bf-4c36-9701-1f8e8ae9e64b", "node_type": "1", "metadata": {}, "hash": "f31e60e6482288f21aac9396e411cf2c096b115cbd0948ba5ae7e4d933292915", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 4694, "end_char_idx": 7866, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
## Transcripts follow the style of the prompt

In the unprompted transcript, 'President Biden' is capitalized. However, if we pass in a fictitious prompt of 'president biden' in lowercase, Whisper matches the style and generates a transcript in all lowercase.


```python
# lowercase prompt
transcribe(up_first_filepath, prompt="president biden")
```




    "I stick contacts in my eyes. Do you really? Yeah. That works okay? You don't have to, like, just kind of pain in the butt every day to do that? No, it is. It is. And I sometimes just kind of miss the eye. I don't know if you know the movie Airplane? Yes. Of course. Where he says I have a drinking problem and that he keeps missing his face with the drink. That's me and the contact lens. Surely, you must know that I know the movie Airplane. I do. I do know that. Don't call me Shirley. Stop calling me Shirley. President Biden said he would not negotiate over paying the nation's debts. But he is meeting today with House Speaker Kevin McCarthy. Other leaders of Congress will also attend. So how much progress can they make? I'm E. Martinez with Steve Inskeep and this is Up First from NPR News. Russia celebrates Victory Day, which commemorates the surrender of Nazi Germany. Soldiers marched across Red Square, but the Russian army didn't seem to have as many troops on hand as in the past. So what does this ritual say about the war Russia is fighting right now?"



Be aware that when prompts are short, Whisper may be less reliable at following their style.


```python
# short prompts are less reliable
transcribe(up_first_filepath, prompt="president biden.")
```




    "I stick contacts in my eyes. Do you really? Yeah. That works okay? You don't have to, like, just kind of pain in the butt every day to do that? No, it is. It is. And I sometimes just kind of miss the eye. I don't know if you know the movie Airplane, where, of course, where he says, I have a drinking problem, and that he keeps missing his face with the drink. That's me and the contact lens. Surely, you must know that I know the movie Airplane. I do. I do know that. Stop calling me Shirley. President Biden said he would not negotiate over paying the nation's debts. But he is meeting today with House Speaker Kevin McCarthy. Other leaders of Congress will also attend. So how much progress can they make? I'm E. Martinez with Steve Inskeep, and this is Up First from NPR News. Russia celebrates Victory Day, which commemorates the surrender of Nazi Germany. Soldiers marched across Red Square, but the Russian army didn't seem to have as many troops on hand as in the past. So what does this ritual say about the war Russia is fighting right now?"



Long prompts may be more reliable at steering Whisper.


```python
# long prompts are more reliable
transcribe(up_first_filepath, prompt="i have some advice for you. multiple sentences help establish a pattern. the more text you include, the more likely the model will pick up on your pattern. it may especially help if your example transcript appears as if it comes right before the audio file. in this case, that could mean mentioning the contacts i stick in my eyes.")
```


key: _node_content
string_value:
{"id_": "b4fa56b2-57bf-4c36-9701-1f8e8ae9e64b", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "44cc12a7-4de4-4632-929b-400a14fd6543", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "3e04f35828f454f6d816ce30a12988ae3c465da006c47f77279a9443341ef664", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a79b3374-d333-4ea2-a2b5-e68fc7ae9260", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "906d98e40087c4cbb3299a0ee508ba6c08163dea56d07caa0bffd6509c4fbb13", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "14b1415b-8e83-4d5b-888d-f345bf691674", "node_type": "1", "metadata": {}, "hash": "631f7d6ed5944d124e57ddeb81e468ae6525f7997e618178003cd2154adcfb3f", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 6127, "end_char_idx": 9177, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Be aware that when prompts are short, Whisper may be less reliable at following their style.


```python
# short prompts are less reliable
transcribe(up_first_filepath, prompt="president biden.")
```




    "I stick contacts in my eyes. Do you really? Yeah. That works okay? You don't have to, like, just kind of pain in the butt every day to do that? No, it is. It is. And I sometimes just kind of miss the eye. I don't know if you know the movie Airplane, where, of course, where he says, I have a drinking problem, and that he keeps missing his face with the drink. That's me and the contact lens. Surely, you must know that I know the movie Airplane. I do. I do know that. Stop calling me Shirley. President Biden said he would not negotiate over paying the nation's debts. But he is meeting today with House Speaker Kevin McCarthy. Other leaders of Congress will also attend. So how much progress can they make? I'm E. Martinez with Steve Inskeep, and this is Up First from NPR News. Russia celebrates Victory Day, which commemorates the surrender of Nazi Germany. Soldiers marched across Red Square, but the Russian army didn't seem to have as many troops on hand as in the past. So what does this ritual say about the war Russia is fighting right now?"



Long prompts may be more reliable at steering Whisper.


```python
# long prompts are more reliable
transcribe(up_first_filepath, prompt="i have some advice for you. multiple sentences help establish a pattern. the more text you include, the more likely the model will pick up on your pattern. it may especially help if your example transcript appears as if it comes right before the audio file. in this case, that could mean mentioning the contacts i stick in my eyes.")
```




    "i stick contacts in my eyes. do you really? yeah. that works okay? you don't have to, like, just kind of pain in the butt? no, it is. it is. and i sometimes just kind of miss the eye. i don't know if you know, um, the movie airplane? yes. of course. where he says i have a drinking problem. and that he keeps missing his face with the drink. that's me in the contact lens. surely, you must know that i know the movie airplane. i do. i do know that. don't call me surely. stop calling me surely. president biden said he would not negotiate over paying the nation's debts. but he is meeting today with house speaker kevin mccarthy. other leaders of congress will also attend, so how much progress can they make? i'm amy martinez with steve inskeep, and this is up first from npr news. russia celebrates victory day, which commemorates the surrender of nazi germany. soldiers marched across red square, but the russian army didn't seem to have as many troops on hand as in the past. so what does this ritual say about the war russia is fighting right now?"



Whisper is also less likely to follow rare or odd styles.


```python
# rare styles are less reliable
transcribe(up_first_filepath, prompt="""Hi there and welcome to the show.
###
Today we are quite excited.
###
Let's jump right in.
###""")
```


key: _node_content
string_value:
{"id_": "14b1415b-8e83-4d5b-888d-f345bf691674", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "44cc12a7-4de4-4632-929b-400a14fd6543", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "3e04f35828f454f6d816ce30a12988ae3c465da006c47f77279a9443341ef664", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b4fa56b2-57bf-4c36-9701-1f8e8ae9e64b", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "011c4b9dfb71b88a8164878c351082d7fedb3946c6cd7d8af2024a8591db3f2d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5addfdec-03a1-4499-a236-9947b7c19a17", "node_type": "1", "metadata": {}, "hash": "07c24f2630871f08643a033af8da3de234e4cf0d6d0c3e5b85c1f70a3569535a", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 7448, "end_char_idx": 10543, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
# long prompts are more reliable
transcribe(up_first_filepath, prompt="i have some advice for you. multiple sentences help establish a pattern. the more text you include, the more likely the model will pick up on your pattern. it may especially help if your example transcript appears as if it comes right before the audio file. in this case, that could mean mentioning the contacts i stick in my eyes.")
```




    "i stick contacts in my eyes. do you really? yeah. that works okay? you don't have to, like, just kind of pain in the butt? no, it is. it is. and i sometimes just kind of miss the eye. i don't know if you know, um, the movie airplane? yes. of course. where he says i have a drinking problem. and that he keeps missing his face with the drink. that's me in the contact lens. surely, you must know that i know the movie airplane. i do. i do know that. don't call me surely. stop calling me surely. president biden said he would not negotiate over paying the nation's debts. but he is meeting today with house speaker kevin mccarthy. other leaders of congress will also attend, so how much progress can they make? i'm amy martinez with steve inskeep, and this is up first from npr news. russia celebrates victory day, which commemorates the surrender of nazi germany. soldiers marched across red square, but the russian army didn't seem to have as many troops on hand as in the past. so what does this ritual say about the war russia is fighting right now?"



Whisper is also less likely to follow rare or odd styles.


```python
# rare styles are less reliable
transcribe(up_first_filepath, prompt="""Hi there and welcome to the show.
###
Today we are quite excited.
###
Let's jump right in.
###""")
```




    "I stick contacts in my eyes. Do you really? Yeah. That works okay. You don't have to like, it's not a pain in the butt. It is. And I sometimes just kind of miss the eye. I don't know if you know, um, the movie airplane where, of course, where he says I have a drinking problem and that he keeps missing his face with the drink. That's me in the contact lens. Surely you must know that I know the movie airplane. Uh, I do. I do know that. Stop calling me Shirley.  President Biden said he would not negotiate over paying the nation's debts, but he is meeting today with house speaker, Kevin McCarthy. Other leaders of Congress will also attend. So how much progress can they make? I mean, Martinez with Steve Inskeep, and this is up first from NPR news. Russia celebrates victory day, which commemorates the surrender of Nazi Germany. Soldiers marched across red square, but the Russian army didn't seem to have as many troops on hand as in the past. So what does this ritual say about the war? Russia is fighting right now."



## Pass names in the prompt to prevent misspellings

Whisper may incorrectly transcribe uncommon proper nouns such as names of products, companies, or people.

We'll illustrate with an example audio file full of product names.


```python
# baseline transcription with no prompt
transcribe(product_names_filepath, prompt="")
```


key: _node_content
string_value:
{"id_": "5addfdec-03a1-4499-a236-9947b7c19a17", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "44cc12a7-4de4-4632-929b-400a14fd6543", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "3e04f35828f454f6d816ce30a12988ae3c465da006c47f77279a9443341ef664", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "14b1415b-8e83-4d5b-888d-f345bf691674", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "ea89d89d54e15c21469b855bb3792caf5fbe8bd84c8286e3f45d4b229494b3ab", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d5b21987-50af-45a0-8690-edc3c90cca09", "node_type": "1", "metadata": {}, "hash": "e9dcf31ea8148e0ef9a6d1bd4f34ab19c4db2d90800d4e7617cbd54aaf2af7af", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 8933, "end_char_idx": 11663, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Whisper is also less likely to follow rare or odd styles.


```python
# rare styles are less reliable
transcribe(up_first_filepath, prompt="""Hi there and welcome to the show.
###
Today we are quite excited.
###
Let's jump right in.
###""")
```




    "I stick contacts in my eyes. Do you really? Yeah. That works okay. You don't have to like, it's not a pain in the butt. It is. And I sometimes just kind of miss the eye. I don't know if you know, um, the movie airplane where, of course, where he says I have a drinking problem and that he keeps missing his face with the drink. That's me in the contact lens. Surely you must know that I know the movie airplane. Uh, I do. I do know that. Stop calling me Shirley.  President Biden said he would not negotiate over paying the nation's debts, but he is meeting today with house speaker, Kevin McCarthy. Other leaders of Congress will also attend. So how much progress can they make? I mean, Martinez with Steve Inskeep, and this is up first from NPR news. Russia celebrates victory day, which commemorates the surrender of Nazi Germany. Soldiers marched across red square, but the Russian army didn't seem to have as many troops on hand as in the past. So what does this ritual say about the war? Russia is fighting right now."



## Pass names in the prompt to prevent misspellings

Whisper may incorrectly transcribe uncommon proper nouns such as names of products, companies, or people.

We'll illustrate with an example audio file full of product names.


```python
# baseline transcription with no prompt
transcribe(product_names_filepath, prompt="")
```




    'Welcome to Quirk, Quid, Quill, Inc., where finance meets innovation. Explore diverse offerings, from the P3 Quattro, a unique investment portfolio quadrant, to the O3 Omni, a platform for intricate derivative trading strategies. Delve into unconventional bond markets with our B3 Bond X and experience non-standard equity trading with E3 Equity. Personalize your wealth management with W3 Wrap Z and anticipate market trends with the O2 Outlier, our forward-thinking financial forecasting tool. Explore venture capital world with U3 Unifund or move your money with the M3 Mover, our sophisticated monetary transfer module. At Quirk, Quid, Quill, Inc., we turn complex finance into creative solutions. Join us in redefining financial services.'



To get Whisper to use our preferred spellings, let's pass the product and company names in the prompt, as a glossary for Whisper to follow. 


```python
# adding the correct spelling of the product name helps
transcribe(product_names_filepath, prompt="QuirkQuid Quill Inc, P3-Quattro, O3-Omni, B3-BondX, E3-Equity, W3-WrapZ, O2-Outlier, U3-UniFund, M3-Mover")
```


key: _node_content
string_value:
{"id_": "d5b21987-50af-45a0-8690-edc3c90cca09", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "44cc12a7-4de4-4632-929b-400a14fd6543", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "3e04f35828f454f6d816ce30a12988ae3c465da006c47f77279a9443341ef664", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5addfdec-03a1-4499-a236-9947b7c19a17", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "43bf3e57cb7b80b1c0270974c8d34f3ed7e0a35f0d454948e302ba04f983ed9c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1a7b6cbb-3331-4e3a-9196-e6f13798b67b", "node_type": "1", "metadata": {}, "hash": "630bfd49cbb3d33db9cfe6e5d01fa7fe1c224d2189d549109c57c11c5eb9889a", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 10215, "end_char_idx": 13490, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
## Pass names in the prompt to prevent misspellings

Whisper may incorrectly transcribe uncommon proper nouns such as names of products, companies, or people.

We'll illustrate with an example audio file full of product names.


```python
# baseline transcription with no prompt
transcribe(product_names_filepath, prompt="")
```




    'Welcome to Quirk, Quid, Quill, Inc., where finance meets innovation. Explore diverse offerings, from the P3 Quattro, a unique investment portfolio quadrant, to the O3 Omni, a platform for intricate derivative trading strategies. Delve into unconventional bond markets with our B3 Bond X and experience non-standard equity trading with E3 Equity. Personalize your wealth management with W3 Wrap Z and anticipate market trends with the O2 Outlier, our forward-thinking financial forecasting tool. Explore venture capital world with U3 Unifund or move your money with the M3 Mover, our sophisticated monetary transfer module. At Quirk, Quid, Quill, Inc., we turn complex finance into creative solutions. Join us in redefining financial services.'



To get Whisper to use our preferred spellings, let's pass the product and company names in the prompt, as a glossary for Whisper to follow. 


```python
# adding the correct spelling of the product name helps
transcribe(product_names_filepath, prompt="QuirkQuid Quill Inc, P3-Quattro, O3-Omni, B3-BondX, E3-Equity, W3-WrapZ, O2-Outlier, U3-UniFund, M3-Mover")
```




    'Welcome to QuirkQuid Quill Inc, where finance meets innovation. Explore diverse offerings, from the P3-Quattro, a unique investment portfolio quadrant, to the O3-Omni, a platform for intricate derivative trading strategies. Delve into unconventional bond markets with our B3-BondX and experience non-standard equity trading with E3-Equity. Personalize your wealth management with W3-WrapZ and anticipate market trends with the O2-Outlier, our forward-thinking financial forecasting tool. Explore venture capital world with U3-UniFund or move your money with the M3-Mover, our sophisticated monetary transfer module. At QuirkQuid Quill Inc, we turn complex finance into creative solutions. Join us in redefining financial services.'



Now, let's switch to another audio recording authored specifically for this demonstration, on the topic of a odd barbecue.

To begin, we'll establish our baseline transcript using Whisper.


```python
# baseline transcript with no prompt
transcribe(bbq_plans_filepath, prompt="")
```




    "Hello, my name is Preston Tuggle. I'm based in New York City. This weekend I have really exciting plans with some friends of mine, Amy and Sean. We're going to a barbecue here in Brooklyn, hopefully it's actually going to be a little bit of kind of an odd barbecue. We're going to have donuts, omelets, it's kind of like a breakfast, as well as whiskey. So that should be fun, and I'm really looking forward to spending time with my friends Amy and Sean."



While Whisper's transcription was accurate, it had to guess at various spellings. For example, it assumed the friends' names were spelled Amy and Sean rather than Aimee and Shawn. Let's see if we can steer the spelling with a prompt.


```python
# spelling prompt
transcribe(bbq_plans_filepath, prompt="Friends: Aimee, Shawn")
```


key: _node_content
string_value:
{"id_": "1a7b6cbb-3331-4e3a-9196-e6f13798b67b", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "44cc12a7-4de4-4632-929b-400a14fd6543", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "3e04f35828f454f6d816ce30a12988ae3c465da006c47f77279a9443341ef664", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d5b21987-50af-45a0-8690-edc3c90cca09", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "1f40a92295efdbd296db569ab8defdf1efcb7efe3cc955530e36002d0baeed29", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7e5a976d-fc67-437f-9f54-74eda46f875c", "node_type": "1", "metadata": {}, "hash": "faca993a0bb2f66c2aac424a7e62e0f297ecb05428eb4f3d5ec3e36362ba542d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 12408, "end_char_idx": 15473, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Now, let's switch to another audio recording authored specifically for this demonstration, on the topic of a odd barbecue.

To begin, we'll establish our baseline transcript using Whisper.


```python
# baseline transcript with no prompt
transcribe(bbq_plans_filepath, prompt="")
```




    "Hello, my name is Preston Tuggle. I'm based in New York City. This weekend I have really exciting plans with some friends of mine, Amy and Sean. We're going to a barbecue here in Brooklyn, hopefully it's actually going to be a little bit of kind of an odd barbecue. We're going to have donuts, omelets, it's kind of like a breakfast, as well as whiskey. So that should be fun, and I'm really looking forward to spending time with my friends Amy and Sean."



While Whisper's transcription was accurate, it had to guess at various spellings. For example, it assumed the friends' names were spelled Amy and Sean rather than Aimee and Shawn. Let's see if we can steer the spelling with a prompt.


```python
# spelling prompt
transcribe(bbq_plans_filepath, prompt="Friends: Aimee, Shawn")
```




    "Hello, my name is Preston Tuggle. I'm based in New York City. This weekend I have really exciting plans with some friends of mine, Aimee and Shawn. We're going to a barbecue here in Brooklyn. Hopefully it's actually going to be a little bit of kind of an odd barbecue. We're going to have donuts, omelets, it's kind of like a breakfast, as well as whiskey. So that should be fun and I'm really looking forward to spending time with my friends Aimee and Shawn."



Success!

Let's try the same with more ambiguously spelled words.


```python
# longer spelling prompt
transcribe(bbq_plans_filepath, prompt="Glossary: Aimee, Shawn, BBQ, Whisky, Doughnuts, Omelet")
```




    "Hello, my name is Preston Tuggle. I'm based in New York City. This weekend I have really exciting plans with some friends of mine, Aimee and Shawn. We're going to a barbecue here in Brooklyn. Hopefully, it's actually going to be a little bit of an odd barbecue. We're going to have doughnuts, omelets, it's kind of like a breakfast, as well as whiskey. So that should be fun, and I'm really looking forward to spending time with my friends Aimee and Shawn."




```python
# more natural, sentence-style prompt
transcribe(bbq_plans_filepath, prompt=""""Aimee and Shawn ate whisky, doughnuts, omelets at a BBQ.""")
```




    "Hello, my name is Preston Tuggle. I'm based in New York City. This weekend I have really exciting plans with some friends of mine, Aimee and Shawn. We're going to a BBQ here in Brooklyn. Hopefully it's actually going to be a little bit of kind of an odd BBQ. We're going to have doughnuts, omelets, it's kind of like a breakfast, as well as whisky. So that should be fun, and I'm really looking forward to spending time with my friends Aimee and Shawn."



## Fictitious prompts can be generated by GPT

One potential tool to generate fictitious prompts is GPT. We can give GPT instructions and use it to generate long fictitious transcripts with which to prompt Whisper.


key: _node_content
string_value:
{"id_": "7e5a976d-fc67-437f-9f54-74eda46f875c", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "44cc12a7-4de4-4632-929b-400a14fd6543", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "3e04f35828f454f6d816ce30a12988ae3c465da006c47f77279a9443341ef664", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1a7b6cbb-3331-4e3a-9196-e6f13798b67b", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Whisper_prompting_guide.ipynb", "title": "Whisper prompting guide", "tokens": 4980, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "d2a41caebd310e1b97d78d511d42e44b9d38d70c5695e1cc75e6555927b92f1c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "be53e227-c633-461a-acb7-68729942e0cc", "node_type": "1", "metadata": {}, "hash": "8ea29be027554359f8c0caa13ade907b0830dae3daad7d17aea93bd79df8e028", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 13964, "end_char_idx": 16579, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


