# embedding_metadata

key: chroma:document
string_value:
```python
result_list[0]
```




    {'title': 'SBERT studies Meaning Representations: Decomposing Sentence Embeddings into Explainable Semantic Features',
     'summary': 'Models based on large-pretrained language models, such as S(entence)BERT,\nprovide effective and efficient sentence embeddings that show high correlation\nto human similarity ratings, but lack interpretability. On the other hand,\ngraph metrics for graph-based meaning representations (e.g., Abstract Meaning\nRepresentation, AMR) can make explicit the semantic aspects in which two\nsentences are similar. However, such metrics tend to be slow, rely on parsers,\nand do not reach state-of-the-art performance when rating sentence similarity.\n  In this work, we aim at the best of both worlds, by learning to induce\n$S$emantically $S$tructured $S$entence BERT embeddings (S$^3$BERT). Our\nS$^3$BERT embeddings are composed of explainable sub-embeddings that emphasize\nvarious semantic sentence features (e.g., semantic roles, negation, or\nquantification). We show how to i) learn a decomposition of the sentence\nembeddings into semantic features, through approximation of a suite of\ninterpretable AMR graph metrics, and how to ii) preserve the overall power of\nthe neural embeddings by controlling the decomposition learning process with a\nsecond objective that enforces consistency with the similarity ratings of an\nSBERT teacher model. In our experimental studies, we show that our approach\noffers interpretability -- while fully preserving the effectiveness and\nefficiency of the neural sentence embeddings.',
     'article_url': 'http://arxiv.org/abs/2206.07023v2',
     'pdf_url': 'http://arxiv.org/pdf/2206.07023v2'}




```python
for i, result in enumerate(result_list):
    print(f"{i + 1}: {result['title']}")
```

    1: SBERT studies Meaning Representations: Decomposing Sentence Embeddings into Explainable Semantic Features
    2: Are Classes Clusters?
    3: Semantic Composition in Visually Grounded Language Models
    4: Evaluating the Construct Validity of Text Embeddings with Application to Survey Questions
    5: Learning Probabilistic Sentence Representations from Paraphrases
    6: Exploiting Twitter as Source of Large Corpora of Weakly Similar Pairs for Semantic Sentence Embeddings
    7: How to Probe Sentence Embeddings in Low-Resource Languages: On Structural Design Choices for Probing Task Evaluation
    8: Clustering and Network Analysis for the Embedding Spaces of Sentences and Sub-Sentences
    9: Vec2Sent: Probing Sentence Embeddings with Natural Language Generation
    10: Non-Linguistic Supervision for Contrastive Learning of Sentence Embeddings
    11: SentPWNet: A Unified Sentence Pair Weighting Network for Task-specific Sentence Embedding
    12: Learning Joint Representations of Videos and Sentences with Web Image Search
    13: Character-based Neural Networks for Sentence Pair Modeling
    14: Train Once, Test Anywhere: Zero-Shot Learning for Text Classification
    15: Hierarchical GPT with Congruent Transformers for Multi-Sentence Language Models
    16: Sentence-T5: Scalable Sentence Encoders from Pre-trained Text-to-Text Models
    17: In Search for Linear Relations in Sentence Embedding Spaces
    18: Learning to Borrow -- Relation Representation for Without-Mention Entity-Pairs for Knowledge Graph Completion
    19: Efficient and Flexible Topic Modeling using Pretrained Embeddings and Bag of Sentences
    20: Relational Sentence Embedding for Flexible Semantic Matching


key: _node_content
string_value:
{"id_": "3cf46980-4bab-4596-ba55-eae07d6eb399", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "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": "64f6fb54-183f-4a0b-a1e1-9040a6717110", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "e8e0acaf40970dd551e968e92897d3415bd23a6e4bc77c0be91f1270b664426c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "fc95a9dc-78f4-47b3-8183-e08afa5d87aa", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "a41ff6145e81bf72e8ac2f5e61b5270d07a5d8f8a1e2fdc27f47765477bf65c1", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8ac06ea5-8f79-4f41-aa22-929b7e753317", "node_type": "1", "metadata": {}, "hash": "5551b0d12a201998e13de442ff7e88af66237ff9e6e8c42df97a98906f654f26", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 7212, "end_char_idx": 10568, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
## Cross-encoder

We'll create a cross-encoder using the ```Completions``` endpoint - the key factors to consider here are:
- Make your examples domain-specific - the strength of cross-encoders comes when you tailor them to your domain.
- There is a trade-off between how many potential examples to re-rank vs. processing speed. Consider batching and parallel processing cross-encoder requests to process them more quickly.

The steps here are:
- Build a prompt to assess relevance and provide few-shot examples to tune it to your domain.
- Add a ```logit bias``` for the tokens for ``` Yes``` and ``` No``` to decrease the likelihood of any other tokens occurring.
- Return the classification of yes/no as well as the ```logprobs```.
- Rerank the results by the ```logprobs``` keyed on ``` Yes```.


```python
tokens = [" Yes", " No"]
tokenizer = tiktoken.encoding_for_model(OPENAI_MODEL)
ids = [tokenizer.encode(token) for token in tokens]
ids[0], ids[1]
```




    ([3363], [1400])




```python
prompt = '''
You are an Assistant responsible for helping detect whether the retrieved document is relevant to the query. For a given input, you need to output a single token: "Yes" or "No" indicating the retrieved document is relevant to the query.

Query: How to plant a tree?
Document: """Cars were invented in 1886, when German inventor Carl Benz patented his Benz Patent-Motorwagen.[3][4][5] Cars became widely available during the 20th century. One of the first cars affordable by the masses was the 1908 Model T, an American car manufactured by the Ford Motor Company. Cars were rapidly adopted in the US, where they replaced horse-drawn carriages.[6] In Europe and other parts of the world, demand for automobiles did not increase until after World War II.[7] The car is considered an essential part of the developed economy."""
Relevant: No

Query: Has the coronavirus vaccine been approved?
Document: """The Pfizer-BioNTech COVID-19 vaccine was approved for emergency use in the United States on December 11, 2020."""
Relevant: Yes

Query: What is the capital of France?
Document: """Paris, France's capital, is a major European city and a global center for art, fashion, gastronomy and culture. Its 19th-century cityscape is crisscrossed by wide boulevards and the River Seine. Beyond such landmarks as the Eiffel Tower and the 12th-century, Gothic Notre-Dame cathedral, the city is known for its cafe culture and designer boutiques along the Rue du Faubourg Saint-Honoré."""
Relevant: Yes

Query: What are some papers to learn about PPO reinforcement learning?
Document: """Proximal Policy Optimization and its Dynamic Version for Sequence Generation: In sequence generation task, many works use policy gradient for model optimization to tackle the intractable backpropagation issue when maximizing the non-differentiable evaluation metrics or fooling the discriminator in adversarial learning. In this paper, we replace policy gradient with proximal policy optimization (PPO), which is a proved more efficient reinforcement learning algorithm, and propose a dynamic approach for PPO (PPO-dynamic). We demonstrate the efficacy of PPO and PPO-dynamic on conditional sequence generation tasks including synthetic experiment and chit-chat chatbot. The results show that PPO and PPO-dynamic can beat policy gradient by stability and performance."""


key: _node_content
string_value:
{"id_": "8ac06ea5-8f79-4f41-aa22-929b7e753317", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "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": "64f6fb54-183f-4a0b-a1e1-9040a6717110", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "e8e0acaf40970dd551e968e92897d3415bd23a6e4bc77c0be91f1270b664426c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3cf46980-4bab-4596-ba55-eae07d6eb399", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "12bc8423d4ee4fb37f42d53c48c4e2090fbad70ade1b11bd684ef04005950ab0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8e0307fe-8f30-4171-acbf-72606296d677", "node_type": "1", "metadata": {}, "hash": "409ecad44c74d085069fde984bf6542b2ffdd783ed5867f1d9ab377171fa8448", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 8788, "end_char_idx": 11847, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Cars were rapidly adopted in the US, where they replaced horse-drawn carriages.[6] In Europe and other parts of the world, demand for automobiles did not increase until after World War II.[7] The car is considered an essential part of the developed economy."""
Relevant: No

Query: Has the coronavirus vaccine been approved?
Document: """The Pfizer-BioNTech COVID-19 vaccine was approved for emergency use in the United States on December 11, 2020."""
Relevant: Yes

Query: What is the capital of France?
Document: """Paris, France's capital, is a major European city and a global center for art, fashion, gastronomy and culture. Its 19th-century cityscape is crisscrossed by wide boulevards and the River Seine. Beyond such landmarks as the Eiffel Tower and the 12th-century, Gothic Notre-Dame cathedral, the city is known for its cafe culture and designer boutiques along the Rue du Faubourg Saint-Honoré."""
Relevant: Yes

Query: What are some papers to learn about PPO reinforcement learning?
Document: """Proximal Policy Optimization and its Dynamic Version for Sequence Generation: In sequence generation task, many works use policy gradient for model optimization to tackle the intractable backpropagation issue when maximizing the non-differentiable evaluation metrics or fooling the discriminator in adversarial learning. In this paper, we replace policy gradient with proximal policy optimization (PPO), which is a proved more efficient reinforcement learning algorithm, and propose a dynamic approach for PPO (PPO-dynamic). We demonstrate the efficacy of PPO and PPO-dynamic on conditional sequence generation tasks including synthetic experiment and chit-chat chatbot. The results show that PPO and PPO-dynamic can beat policy gradient by stability and performance."""
Relevant: Yes

Query: Explain sentence embeddings
Document: """Inside the bubble: exploring the environments of reionisation-era Lyman-α emitting galaxies with JADES and FRESCO: We present a study of the environments of 16 Lyman-α emitting galaxies (LAEs) in the reionisation era (5.8<z<8) identified by JWST/NIRSpec as part of the JWST Advanced Deep Extragalactic Survey (JADES). Unless situated in sufficiently (re)ionised regions, Lyman-α emission from these galaxies would be strongly absorbed by neutral gas in the intergalactic medium (IGM). We conservatively estimate sizes of the ionised regions required to reconcile the relatively low Lyman-α velocity offsets (ΔvLyα<300kms−1) with moderately high Lyman-α escape fractions (fesc,Lyα>5%) observed in our sample of LAEs, indicating the presence of ionised ``bubbles'' with physical sizes of the order of 0.1pMpc≲Rion≲1pMpc in a patchy reionisation scenario where the bubbles are embedded in a fully neutral IGM. Around half of the LAEs in our sample are found to coincide with large-scale galaxy overdensities seen in FRESCO at z∼5.8-5.9 and z∼7.3, suggesting Lyman-α transmission is strongly enhanced in such overdense regions, and underlining the importance of LAEs as tracers of the first large-scale ionised bubbles.


key: _node_content
string_value:
{"id_": "8e0307fe-8f30-4171-acbf-72606296d677", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "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": "64f6fb54-183f-4a0b-a1e1-9040a6717110", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "e8e0acaf40970dd551e968e92897d3415bd23a6e4bc77c0be91f1270b664426c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8ac06ea5-8f79-4f41-aa22-929b7e753317", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "e924e4f3286a7c352dc70ca7e95a20f250367f78c648c91cf1a854d2dd37f349", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "00e5c312-3943-4aff-8300-ab467bc897c6", "node_type": "1", "metadata": {}, "hash": "c5fbe626d8cacb2ca35eb6d8377665387dbf916d1d1093304e5c614c7bc72162", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 10323, "end_char_idx": 13361, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
We demonstrate the efficacy of PPO and PPO-dynamic on conditional sequence generation tasks including synthetic experiment and chit-chat chatbot. The results show that PPO and PPO-dynamic can beat policy gradient by stability and performance."""
Relevant: Yes

Query: Explain sentence embeddings
Document: """Inside the bubble: exploring the environments of reionisation-era Lyman-α emitting galaxies with JADES and FRESCO: We present a study of the environments of 16 Lyman-α emitting galaxies (LAEs) in the reionisation era (5.8<z<8) identified by JWST/NIRSpec as part of the JWST Advanced Deep Extragalactic Survey (JADES). Unless situated in sufficiently (re)ionised regions, Lyman-α emission from these galaxies would be strongly absorbed by neutral gas in the intergalactic medium (IGM). We conservatively estimate sizes of the ionised regions required to reconcile the relatively low Lyman-α velocity offsets (ΔvLyα<300kms−1) with moderately high Lyman-α escape fractions (fesc,Lyα>5%) observed in our sample of LAEs, indicating the presence of ionised ``bubbles'' with physical sizes of the order of 0.1pMpc≲Rion≲1pMpc in a patchy reionisation scenario where the bubbles are embedded in a fully neutral IGM. Around half of the LAEs in our sample are found to coincide with large-scale galaxy overdensities seen in FRESCO at z∼5.8-5.9 and z∼7.3, suggesting Lyman-α transmission is strongly enhanced in such overdense regions, and underlining the importance of LAEs as tracers of the first large-scale ionised bubbles. Considering only spectroscopically confirmed galaxies, we find our sample of UV-faint LAEs (MUV≳−20mag) and their direct neighbours are generally not able to produce the required ionised regions based on the Lyman-α transmission properties, suggesting lower-luminosity sources likely play an important role in carving out these bubbles. These observations demonstrate the combined power of JWST multi-object and slitless spectroscopy in acquiring a unique view of the early stages of Cosmic Reionisation via the most distant LAEs."""
Relevant: No

Query: {query}
Document: """{document}"""
Relevant:
'''


@retry(wait=wait_random_exponential(min=1, max=40), stop=stop_after_attempt(3))
def document_relevance(query, document):
    response = openai.chat.completions.create(
        model="text-davinci-003",
        message=prompt.format(query=query, document=document),
        temperature=0,
        logprobs=True,
        logit_bias={3363: 1, 1400: 1},
    )

    return (
        query,
        document,
        response.choices[0].message.content,
        response.choices[0].logprobs.token_logprobs[0],
    )
```


```python
content = result_list[0]["title"] + ": " + result_list[0]["summary"]

# Set logprobs to 1 so our response will include the most probable token the model identified
response = openai.chat.completions.create(
    model=OPENAI_MODEL,
    prompt=prompt.format(query=query, document=content),
    temperature=0,
    logprobs=1,
    logit_bias={3363: 1, 1400: 1},
    max_tokens=1,
)
```


key: _node_content
string_value:
{"id_": "00e5c312-3943-4aff-8300-ab467bc897c6", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "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": "64f6fb54-183f-4a0b-a1e1-9040a6717110", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "e8e0acaf40970dd551e968e92897d3415bd23a6e4bc77c0be91f1270b664426c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8e0307fe-8f30-4171-acbf-72606296d677", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "3bc17dcc0e304ed7f6d31c04e1ddbf51ad621766f6e3768afcd67ad1c0ac164a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c400734f-7bec-4840-9305-280811c40d7e", "node_type": "1", "metadata": {}, "hash": "e54dd7e71cf42f3fd9da720f616d855d4058a7f45248ca559200c5d92389c56d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 11848, "end_char_idx": 14767, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Considering only spectroscopically confirmed galaxies, we find our sample of UV-faint LAEs (MUV≳−20mag) and their direct neighbours are generally not able to produce the required ionised regions based on the Lyman-α transmission properties, suggesting lower-luminosity sources likely play an important role in carving out these bubbles. These observations demonstrate the combined power of JWST multi-object and slitless spectroscopy in acquiring a unique view of the early stages of Cosmic Reionisation via the most distant LAEs."""
Relevant: No

Query: {query}
Document: """{document}"""
Relevant:
'''


@retry(wait=wait_random_exponential(min=1, max=40), stop=stop_after_attempt(3))
def document_relevance(query, document):
    response = openai.chat.completions.create(
        model="text-davinci-003",
        message=prompt.format(query=query, document=document),
        temperature=0,
        logprobs=True,
        logit_bias={3363: 1, 1400: 1},
    )

    return (
        query,
        document,
        response.choices[0].message.content,
        response.choices[0].logprobs.token_logprobs[0],
    )
```


```python
content = result_list[0]["title"] + ": " + result_list[0]["summary"]

# Set logprobs to 1 so our response will include the most probable token the model identified
response = openai.chat.completions.create(
    model=OPENAI_MODEL,
    prompt=prompt.format(query=query, document=content),
    temperature=0,
    logprobs=1,
    logit_bias={3363: 1, 1400: 1},
    max_tokens=1,
)
```


```python
result = response.choices[0]
print(f"Result was {result.message.content}")
print(f"Logprobs was {result.logprobs.token_logprobs[0]}")
print("\nBelow is the full logprobs object\n\n")
print(result["logprobs"])
```

    Result was Yes
    Logprobs was -0.05869877
    
    Below is the full logprobs object
    
    
    {
      "tokens": [
        "Yes"
      ],
      "token_logprobs": [
        -0.05869877
      ],
      "top_logprobs": [
        {
          "Yes": -0.05869877
        }
      ],
      "text_offset": [
        5764
      ]
    }



```python
output_list = []
for x in result_list:
    content = x["title"] + ": " + x["summary"]

    try:
        output_list.append(document_relevance(query, document=content))

    except Exception as e:
        print(e)
```


```python
output_list[:10]
```




    [('how do bi-encoders work for sentence embeddings',
      'SBERT studies Meaning Representations: Decomposing Sentence Embeddings into Explainable Semantic Features: Models based on large-pretrained language models, such as S(entence)BERT,\nprovide effective and efficient sentence embeddings that show high correlation\nto human similarity ratings, but lack interpretability. On the other hand,\ngraph metrics for graph-based meaning representations (e.g., Abstract Meaning\nRepresentation, AMR) can make explicit the semantic aspects in which two\nsentences are similar.


key: _node_content
string_value:
{"id_": "c400734f-7bec-4840-9305-280811c40d7e", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "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": "64f6fb54-183f-4a0b-a1e1-9040a6717110", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "e8e0acaf40970dd551e968e92897d3415bd23a6e4bc77c0be91f1270b664426c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "00e5c312-3943-4aff-8300-ab467bc897c6", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "021098f5b5998c28a005c79e67351178440d9c68066b9a268b0d7646bdd94d3f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3bbafb37-bb33-4a9b-95ba-a38b43f60005", "node_type": "1", "metadata": {}, "hash": "69b57bbe8b80f121f619b94de8a976849fd9ddc89d99f2d968ac880bb716bd0a", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 13364, "end_char_idx": 16421, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
result = response.choices[0]
print(f"Result was {result.message.content}")
print(f"Logprobs was {result.logprobs.token_logprobs[0]}")
print("\nBelow is the full logprobs object\n\n")
print(result["logprobs"])
```

    Result was Yes
    Logprobs was -0.05869877
    
    Below is the full logprobs object
    
    
    {
      "tokens": [
        "Yes"
      ],
      "token_logprobs": [
        -0.05869877
      ],
      "top_logprobs": [
        {
          "Yes": -0.05869877
        }
      ],
      "text_offset": [
        5764
      ]
    }



```python
output_list = []
for x in result_list:
    content = x["title"] + ": " + x["summary"]

    try:
        output_list.append(document_relevance(query, document=content))

    except Exception as e:
        print(e)
```


```python
output_list[:10]
```




    [('how do bi-encoders work for sentence embeddings',
      'SBERT studies Meaning Representations: Decomposing Sentence Embeddings into Explainable Semantic Features: Models based on large-pretrained language models, such as S(entence)BERT,\nprovide effective and efficient sentence embeddings that show high correlation\nto human similarity ratings, but lack interpretability. On the other hand,\ngraph metrics for graph-based meaning representations (e.g., Abstract Meaning\nRepresentation, AMR) can make explicit the semantic aspects in which two\nsentences are similar. However, such metrics tend to be slow, rely on parsers,\nand do not reach state-of-the-art performance when rating sentence similarity.\n  In this work, we aim at the best of both worlds, by learning to induce\n$S$emantically $S$tructured $S$entence BERT embeddings (S$^3$BERT). Our\nS$^3$BERT embeddings are composed of explainable sub-embeddings that emphasize\nvarious semantic sentence features (e.g., semantic roles, negation, or\nquantification). We show how to i) learn a decomposition of the sentence\nembeddings into semantic features, through approximation of a suite of\ninterpretable AMR graph metrics, and how to ii) preserve the overall power of\nthe neural embeddings by controlling the decomposition learning process with a\nsecond objective that enforces consistency with the similarity ratings of an\nSBERT teacher model. In our experimental studies, we show that our approach\noffers interpretability -- while fully preserving the effectiveness and\nefficiency of the neural sentence embeddings.',
      'Yes',
      -0.05326408),
     ('how do bi-encoders work for sentence embeddings',
      'Are Classes Clusters?: Sentence embedding models aim to provide general purpose embeddings for\nsentences. Most of the models studied in this paper claim to perform well on\nSTS tasks - but they do not report on their suitability for clustering. This\npaper looks at four recent sentence embedding models (Universal Sentence\nEncoder (Cer et al., 2018), Sentence-BERT (Reimers and Gurevych, 2019), LASER\n(Artetxe and Schwenk, 2019), and DeCLUTR (Giorgi et al., 2020)). It gives a\nbrief overview of the ideas behind their implementations.


key: _node_content
string_value:
{"id_": "3bbafb37-bb33-4a9b-95ba-a38b43f60005", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "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": "64f6fb54-183f-4a0b-a1e1-9040a6717110", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "e8e0acaf40970dd551e968e92897d3415bd23a6e4bc77c0be91f1270b664426c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c400734f-7bec-4840-9305-280811c40d7e", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "4d532d973f552278fb4b4c39bfa4f70dcf12602221d1de2c22841174338704db", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f6f24107-d1e7-49e6-aba6-54932f384a84", "node_type": "1", "metadata": {}, "hash": "ec57d9ad7b08d80c894e8827b95c8b79aea64cd57921ff8a288b8515813212bd", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 14768, "end_char_idx": 17738, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
However, such metrics tend to be slow, rely on parsers,\nand do not reach state-of-the-art performance when rating sentence similarity.\n  In this work, we aim at the best of both worlds, by learning to induce\n$S$emantically $S$tructured $S$entence BERT embeddings (S$^3$BERT). Our\nS$^3$BERT embeddings are composed of explainable sub-embeddings that emphasize\nvarious semantic sentence features (e.g., semantic roles, negation, or\nquantification). We show how to i) learn a decomposition of the sentence\nembeddings into semantic features, through approximation of a suite of\ninterpretable AMR graph metrics, and how to ii) preserve the overall power of\nthe neural embeddings by controlling the decomposition learning process with a\nsecond objective that enforces consistency with the similarity ratings of an\nSBERT teacher model. In our experimental studies, we show that our approach\noffers interpretability -- while fully preserving the effectiveness and\nefficiency of the neural sentence embeddings.',
      'Yes',
      -0.05326408),
     ('how do bi-encoders work for sentence embeddings',
      'Are Classes Clusters?: Sentence embedding models aim to provide general purpose embeddings for\nsentences. Most of the models studied in this paper claim to perform well on\nSTS tasks - but they do not report on their suitability for clustering. This\npaper looks at four recent sentence embedding models (Universal Sentence\nEncoder (Cer et al., 2018), Sentence-BERT (Reimers and Gurevych, 2019), LASER\n(Artetxe and Schwenk, 2019), and DeCLUTR (Giorgi et al., 2020)). It gives a\nbrief overview of the ideas behind their implementations. It then investigates\nhow well topic classes in two text classification datasets (Amazon Reviews (Ni\net al., 2019) and News Category Dataset (Misra, 2018)) map to clusters in their\ncorresponding sentence embedding space. While the performance of the resulting\nclassification model is far from perfect, it is better than random. This is\ninteresting because the classification model has been constructed in an\nunsupervised way. The topic classes in these real life topic classification\ndatasets can be partly reconstructed by clustering the corresponding sentence\nembeddings.',
      'No',
      -0.009535169),
     ('how do bi-encoders work for sentence embeddings',
      "Semantic Composition in Visually Grounded Language Models: What is sentence meaning and its ideal representation? Much of the expressive\npower of human language derives from semantic composition, the mind's ability\nto represent meaning hierarchically & relationally over constituents. At the\nsame time, much sentential meaning is outside the text and requires grounding\nin sensory, motor, and experiential modalities to be adequately learned.\nAlthough large language models display considerable compositional ability,\nrecent work shows that visually-grounded language models drastically fail to\nrepresent compositional structure.


key: _node_content
string_value:
{"id_": "f6f24107-d1e7-49e6-aba6-54932f384a84", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "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": "64f6fb54-183f-4a0b-a1e1-9040a6717110", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "e8e0acaf40970dd551e968e92897d3415bd23a6e4bc77c0be91f1270b664426c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3bbafb37-bb33-4a9b-95ba-a38b43f60005", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "e3f7c41addbdcf0ed849a70d7aa8ab06e025b0eeb1e03d03cfb5de2d3ab40719", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e701ec88-f73f-423a-99c7-7c1a29283561", "node_type": "1", "metadata": {}, "hash": "bf5010e8448d5116cea8ea74ee9ce14367937d7d88bc31f3ce02ad2060ecd3cc", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 15903, "end_char_idx": 19480, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
: Sentence embedding models aim to provide general purpose embeddings for\nsentences. Most of the models studied in this paper claim to perform well on\nSTS tasks - but they do not report on their suitability for clustering. This\npaper looks at four recent sentence embedding models (Universal Sentence\nEncoder (Cer et al., 2018), Sentence-BERT (Reimers and Gurevych, 2019), LASER\n(Artetxe and Schwenk, 2019), and DeCLUTR (Giorgi et al., 2020)). It gives a\nbrief overview of the ideas behind their implementations. It then investigates\nhow well topic classes in two text classification datasets (Amazon Reviews (Ni\net al., 2019) and News Category Dataset (Misra, 2018)) map to clusters in their\ncorresponding sentence embedding space. While the performance of the resulting\nclassification model is far from perfect, it is better than random. This is\ninteresting because the classification model has been constructed in an\nunsupervised way. The topic classes in these real life topic classification\ndatasets can be partly reconstructed by clustering the corresponding sentence\nembeddings.',
      'No',
      -0.009535169),
     ('how do bi-encoders work for sentence embeddings',
      "Semantic Composition in Visually Grounded Language Models: What is sentence meaning and its ideal representation? Much of the expressive\npower of human language derives from semantic composition, the mind's ability\nto represent meaning hierarchically & relationally over constituents. At the\nsame time, much sentential meaning is outside the text and requires grounding\nin sensory, motor, and experiential modalities to be adequately learned.\nAlthough large language models display considerable compositional ability,\nrecent work shows that visually-grounded language models drastically fail to\nrepresent compositional structure. In this thesis, we explore whether & how\nmodels compose visually grounded semantics, and how we might improve their\nability to do so.\n  Specifically, we introduce 1) WinogroundVQA, a new compositional visual\nquestion answering benchmark, 2) Syntactic Neural Module Distillation, a\nmeasure of compositional ability in sentence embedding models, 3) Causal\nTracing for Image Captioning Models to locate neural representations vital for\nvision-language composition, 4) Syntactic MeanPool to inject a compositional\ninductive bias into sentence embeddings, and 5) Cross-modal Attention\nCongruence Regularization, a self-supervised objective function for\nvision-language relation alignment. We close by discussing connections of our\nwork to neuroscience, psycholinguistics, formal semantics, and philosophy.",
      'No',
      -0.008887106),
     ('how do bi-encoders work for sentence embeddings',
      "Evaluating the Construct Validity of Text Embeddings with Application to Survey Questions: Text embedding models from Natural Language Processing can map text data\n(e.g. words, sentences, documents) to supposedly meaningful numerical\nrepresentations (a.k.a. text embeddings). While such models are increasingly\napplied in social science research, one important issue is often not addressed:\nthe extent to which these embeddings are valid representations of constructs\nrelevant for social science research. We therefore propose the use of the\nclassic construct validity framework to evaluate the validity of text\nembeddings. We show how this framework can be adapted to the opaque and\nhigh-dimensional nature of text embeddings, with application to survey\nquestions. We include several popular text embedding methods (e.g.


key: _node_content
string_value:
{"id_": "e701ec88-f73f-423a-99c7-7c1a29283561", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "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": "64f6fb54-183f-4a0b-a1e1-9040a6717110", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "e8e0acaf40970dd551e968e92897d3415bd23a6e4bc77c0be91f1270b664426c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f6f24107-d1e7-49e6-aba6-54932f384a84", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "5f5f5d346a4915384b25c1e25749946570bbd2d640fea1e560a68ffdbb4f6f36", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d0ae91ab-2e04-4d17-ab46-89ae21f5aef6", "node_type": "1", "metadata": {}, "hash": "b2f1b8ba08f4d4366ce16ecff5edb83fd9c2338dbd04f63975f3f6485c6bf97d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 17739, "end_char_idx": 21470, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
In this thesis, we explore whether & how\nmodels compose visually grounded semantics, and how we might improve their\nability to do so.\n  Specifically, we introduce 1) WinogroundVQA, a new compositional visual\nquestion answering benchmark, 2) Syntactic Neural Module Distillation, a\nmeasure of compositional ability in sentence embedding models, 3) Causal\nTracing for Image Captioning Models to locate neural representations vital for\nvision-language composition, 4) Syntactic MeanPool to inject a compositional\ninductive bias into sentence embeddings, and 5) Cross-modal Attention\nCongruence Regularization, a self-supervised objective function for\nvision-language relation alignment. We close by discussing connections of our\nwork to neuroscience, psycholinguistics, formal semantics, and philosophy.",
      'No',
      -0.008887106),
     ('how do bi-encoders work for sentence embeddings',
      "Evaluating the Construct Validity of Text Embeddings with Application to Survey Questions: Text embedding models from Natural Language Processing can map text data\n(e.g. words, sentences, documents) to supposedly meaningful numerical\nrepresentations (a.k.a. text embeddings). While such models are increasingly\napplied in social science research, one important issue is often not addressed:\nthe extent to which these embeddings are valid representations of constructs\nrelevant for social science research. We therefore propose the use of the\nclassic construct validity framework to evaluate the validity of text\nembeddings. We show how this framework can be adapted to the opaque and\nhigh-dimensional nature of text embeddings, with application to survey\nquestions. We include several popular text embedding methods (e.g. fastText,\nGloVe, BERT, Sentence-BERT, Universal Sentence Encoder) in our construct\nvalidity analyses. We find evidence of convergent and discriminant validity in\nsome cases. We also show that embeddings can be used to predict respondent's\nanswers to completely new survey questions. Furthermore, BERT-based embedding\ntechniques and the Universal Sentence Encoder provide more valid\nrepresentations of survey questions than do others. Our results thus highlight\nthe necessity to examine the construct validity of text embeddings before\ndeploying them in social science research.",
      'No',
      -0.008583762),
     ('how do bi-encoders work for sentence embeddings',
      'Learning Probabilistic Sentence Representations from Paraphrases: Probabilistic word embeddings have shown effectiveness in capturing notions\nof generality and entailment, but there is very little work on doing the\nanalogous type of investigation for sentences. In this paper we define\nprobabilistic models that produce distributions for sentences. Our\nbest-performing model treats each word as a linear transformation operator\napplied to a multivariate Gaussian distribution. We train our models on\nparaphrases and demonstrate that they naturally capture sentence specificity.\nWhile our proposed model achieves the best performance overall, we also show\nthat specificity is represented by simpler architectures via the norm of the\nsentence vectors. Qualitative analysis shows that our probabilistic model\ncaptures sentential entailment and provides ways to analyze the specificity and\npreciseness of individual words.',
      'No',
      -0.011975748),
     ('how do bi-encoders work for sentence embeddings',
      "Exploiting Twitter as Source of Large Corpora of Weakly Similar Pairs for Semantic Sentence Embeddings: Semantic sentence embeddings are usually supervisedly built minimizing\ndistances between pairs of embeddings of sentences labelled as semantically\nsimilar by annotators.


key: _node_content
string_value:
{"id_": "d0ae91ab-2e04-4d17-ab46-89ae21f5aef6", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "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": "64f6fb54-183f-4a0b-a1e1-9040a6717110", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "e8e0acaf40970dd551e968e92897d3415bd23a6e4bc77c0be91f1270b664426c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e701ec88-f73f-423a-99c7-7c1a29283561", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "8eb13a895de46b00b3d5eb979d965bfbb890838ed37b77ffac66d40798e7bdf3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "64ca13da-8151-444a-a3a8-bf01cfa79186", "node_type": "1", "metadata": {}, "hash": "78dbfb73c3c8ccf7ea9995913b7e9cd63c473a09dfbf60eb0deacbae86cf9cfe", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 19585, "end_char_idx": 23318, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
We find evidence of convergent and discriminant validity in\nsome cases. We also show that embeddings can be used to predict respondent's\nanswers to completely new survey questions. Furthermore, BERT-based embedding\ntechniques and the Universal Sentence Encoder provide more valid\nrepresentations of survey questions than do others. Our results thus highlight\nthe necessity to examine the construct validity of text embeddings before\ndeploying them in social science research.",
      'No',
      -0.008583762),
     ('how do bi-encoders work for sentence embeddings',
      'Learning Probabilistic Sentence Representations from Paraphrases: Probabilistic word embeddings have shown effectiveness in capturing notions\nof generality and entailment, but there is very little work on doing the\nanalogous type of investigation for sentences. In this paper we define\nprobabilistic models that produce distributions for sentences. Our\nbest-performing model treats each word as a linear transformation operator\napplied to a multivariate Gaussian distribution. We train our models on\nparaphrases and demonstrate that they naturally capture sentence specificity.\nWhile our proposed model achieves the best performance overall, we also show\nthat specificity is represented by simpler architectures via the norm of the\nsentence vectors. Qualitative analysis shows that our probabilistic model\ncaptures sentential entailment and provides ways to analyze the specificity and\npreciseness of individual words.',
      'No',
      -0.011975748),
     ('how do bi-encoders work for sentence embeddings',
      "Exploiting Twitter as Source of Large Corpora of Weakly Similar Pairs for Semantic Sentence Embeddings: Semantic sentence embeddings are usually supervisedly built minimizing\ndistances between pairs of embeddings of sentences labelled as semantically\nsimilar by annotators. Since big labelled datasets are rare, in particular for\nnon-English languages, and expensive, recent studies focus on unsupervised\napproaches that require not-paired input sentences. We instead propose a\nlanguage-independent approach to build large datasets of pairs of informal\ntexts weakly similar, without manual human effort, exploiting Twitter's\nintrinsic powerful signals of relatedness: replies and quotes of tweets. We use\nthe collected pairs to train a Transformer model with triplet-like structures,\nand we test the generated embeddings on Twitter NLP similarity tasks (PIT and\nTURL) and STSb. We also introduce four new sentence ranking evaluation\nbenchmarks of informal texts, carefully extracted from the initial collections\nof tweets, proving not only that our best model learns classical Semantic\nTextual Similarity, but also excels on tasks where pairs of sentences are not\nexact paraphrases. Ablation studies reveal how increasing the corpus size\ninfluences positively the results, even at 2M samples, suggesting that bigger\ncollections of Tweets still do not contain redundant information about semantic\nsimilarities.",
      'No',
      -0.01219046),
     ('how do bi-encoders work for sentence embeddings',
      "How to Probe Sentence Embeddings in Low-Resource Languages: On Structural Design Choices for Probing Task Evaluation: Sentence encoders map sentences to real valued vectors for use in downstream\napplications. To peek into these representations - e.g., to increase\ninterpretability of their results - probing tasks have been designed which\nquery them for linguistic knowledge. However, designing probing tasks for\nlesser-resourced languages is tricky, because these often lack large-scale\nannotated data or (high-quality) dependency parsers as a prerequisite of\nprobing task design in English.


key: _node_content
string_value:
{"id_": "64ca13da-8151-444a-a3a8-bf01cfa79186", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "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": "64f6fb54-183f-4a0b-a1e1-9040a6717110", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "e8e0acaf40970dd551e968e92897d3415bd23a6e4bc77c0be91f1270b664426c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d0ae91ab-2e04-4d17-ab46-89ae21f5aef6", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "c992e938d13310a2c62a6cd5810190b4f5e100812235247e035e93e4cf54079f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9eeddf06-c888-4ffe-8797-2c55faa12309", "node_type": "1", "metadata": {}, "hash": "6b03c60e3055708922808458659a58a182a85c9d075f314ee08e216ceb7112b6", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 21471, "end_char_idx": 25106, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Since big labelled datasets are rare, in particular for\nnon-English languages, and expensive, recent studies focus on unsupervised\napproaches that require not-paired input sentences. We instead propose a\nlanguage-independent approach to build large datasets of pairs of informal\ntexts weakly similar, without manual human effort, exploiting Twitter's\nintrinsic powerful signals of relatedness: replies and quotes of tweets. We use\nthe collected pairs to train a Transformer model with triplet-like structures,\nand we test the generated embeddings on Twitter NLP similarity tasks (PIT and\nTURL) and STSb. We also introduce four new sentence ranking evaluation\nbenchmarks of informal texts, carefully extracted from the initial collections\nof tweets, proving not only that our best model learns classical Semantic\nTextual Similarity, but also excels on tasks where pairs of sentences are not\nexact paraphrases. Ablation studies reveal how increasing the corpus size\ninfluences positively the results, even at 2M samples, suggesting that bigger\ncollections of Tweets still do not contain redundant information about semantic\nsimilarities.",
      'No',
      -0.01219046),
     ('how do bi-encoders work for sentence embeddings',
      "How to Probe Sentence Embeddings in Low-Resource Languages: On Structural Design Choices for Probing Task Evaluation: Sentence encoders map sentences to real valued vectors for use in downstream\napplications. To peek into these representations - e.g., to increase\ninterpretability of their results - probing tasks have been designed which\nquery them for linguistic knowledge. However, designing probing tasks for\nlesser-resourced languages is tricky, because these often lack large-scale\nannotated data or (high-quality) dependency parsers as a prerequisite of\nprobing task design in English. To investigate how to probe sentence embeddings\nin such cases, we investigate sensitivity of probing task results to structural\ndesign choices, conducting the first such large scale study. We show that\ndesign choices like size of the annotated probing dataset and type of\nclassifier used for evaluation do (sometimes substantially) influence probing\noutcomes. We then probe embeddings in a multilingual setup with design choices\nthat lie in a 'stable region', as we identify for English, and find that\nresults on English do not transfer to other languages. Fairer and more\ncomprehensive sentence-level probing evaluation should thus be carried out on\nmultiple languages in the future.",
      'No',
      -0.015550519),
     ('how do bi-encoders work for sentence embeddings',
      'Clustering and Network Analysis for the Embedding Spaces of Sentences and Sub-Sentences: Sentence embedding methods offer a powerful approach for working with short\ntextual constructs or sequences of words. By representing sentences as dense\nnumerical vectors, many natural language processing (NLP) applications have\nimproved their performance. However, relatively little is understood about the\nlatent structure of sentence embeddings. Specifically, research has not\naddressed whether the length and structure of sentences impact the sentence\nembedding space and topology. This paper reports research on a set of\ncomprehensive clustering and network analyses targeting sentence and\nsub-sentence embedding spaces. Results show that one method generates the most\nclusterable embeddings. In general, the embeddings of span sub-sentences have\nbetter clustering properties than the original sentences. The results have\nimplications for future sentence embedding models and applications.


key: _node_content
string_value:
{"id_": "9eeddf06-c888-4ffe-8797-2c55faa12309", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "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": "64f6fb54-183f-4a0b-a1e1-9040a6717110", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "e8e0acaf40970dd551e968e92897d3415bd23a6e4bc77c0be91f1270b664426c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "64ca13da-8151-444a-a3a8-bf01cfa79186", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "bc32c46263f16c0aa050cb1d16aa6972ec0b4f8f0b4bfdf8b65f27fcc94ac9ae", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "536485a8-535b-428d-b5a3-9ad561b51b86", "node_type": "1", "metadata": {}, "hash": "c46a8681ab2e68bb10f4c7f45f736d3412347c95bf944cd65ecc37b6dabca402", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 23099, "end_char_idx": 26787, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
However, designing probing tasks for\nlesser-resourced languages is tricky, because these often lack large-scale\nannotated data or (high-quality) dependency parsers as a prerequisite of\nprobing task design in English. To investigate how to probe sentence embeddings\nin such cases, we investigate sensitivity of probing task results to structural\ndesign choices, conducting the first such large scale study. We show that\ndesign choices like size of the annotated probing dataset and type of\nclassifier used for evaluation do (sometimes substantially) influence probing\noutcomes. We then probe embeddings in a multilingual setup with design choices\nthat lie in a 'stable region', as we identify for English, and find that\nresults on English do not transfer to other languages. Fairer and more\ncomprehensive sentence-level probing evaluation should thus be carried out on\nmultiple languages in the future.",
      'No',
      -0.015550519),
     ('how do bi-encoders work for sentence embeddings',
      'Clustering and Network Analysis for the Embedding Spaces of Sentences and Sub-Sentences: Sentence embedding methods offer a powerful approach for working with short\ntextual constructs or sequences of words. By representing sentences as dense\nnumerical vectors, many natural language processing (NLP) applications have\nimproved their performance. However, relatively little is understood about the\nlatent structure of sentence embeddings. Specifically, research has not\naddressed whether the length and structure of sentences impact the sentence\nembedding space and topology. This paper reports research on a set of\ncomprehensive clustering and network analyses targeting sentence and\nsub-sentence embedding spaces. Results show that one method generates the most\nclusterable embeddings. In general, the embeddings of span sub-sentences have\nbetter clustering properties than the original sentences. The results have\nimplications for future sentence embedding models and applications.',
      'No',
      -0.012663184),
     ('how do bi-encoders work for sentence embeddings',
      'Vec2Sent: Probing Sentence Embeddings with Natural Language Generation: We introspect black-box sentence embeddings by conditionally generating from\nthem with the objective to retrieve the underlying discrete sentence. We\nperceive of this as a new unsupervised probing task and show that it correlates\nwell with downstream task performance. We also illustrate how the language\ngenerated from different encoders differs. We apply our approach to generate\nsentence analogies from sentence embeddings.',
      'Yes',
      -0.004863006),
     ('how do bi-encoders work for sentence embeddings',
      'Non-Linguistic Supervision for Contrastive Learning of Sentence Embeddings: Semantic representation learning for sentences is an important and\nwell-studied problem in NLP. The current trend for this task involves training\na Transformer-based sentence encoder through a contrastive objective with text,\ni.e., clustering sentences with semantically similar meanings and scattering\nothers. In this work, we find the performance of Transformer models as sentence\nencoders can be improved by training with multi-modal multi-task losses, using\nunpaired examples from another modality (e.g., sentences and unrelated\nimage/audio data). In particular, besides learning by the contrastive loss on\ntext, our model clusters examples from a non-linguistic domain (e.g.,\nvisual/audio) with a similar contrastive loss at the same time. The reliance of\nour framework on unpaired non-linguistic data makes it language-agnostic,\nenabling it to be widely applicable beyond English NLP.


key: _node_content
string_value:
{"id_": "536485a8-535b-428d-b5a3-9ad561b51b86", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "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": "64f6fb54-183f-4a0b-a1e1-9040a6717110", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "e8e0acaf40970dd551e968e92897d3415bd23a6e4bc77c0be91f1270b664426c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9eeddf06-c888-4ffe-8797-2c55faa12309", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "d6d910eef98c7533060b1f40b53aa24365a82e9be9f2669e3a9dbf982b3f165f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8224a511-f87c-4235-a80e-b5aab76ccbeb", "node_type": "1", "metadata": {}, "hash": "b77b059a6e4a6df08101daec25b902fbeabe859cb7633f927e152a7795d191ce", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 24908, "end_char_idx": 27675, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
In general, the embeddings of span sub-sentences have\nbetter clustering properties than the original sentences. The results have\nimplications for future sentence embedding models and applications.',
      'No',
      -0.012663184),
     ('how do bi-encoders work for sentence embeddings',
      'Vec2Sent: Probing Sentence Embeddings with Natural Language Generation: We introspect black-box sentence embeddings by conditionally generating from\nthem with the objective to retrieve the underlying discrete sentence. We\nperceive of this as a new unsupervised probing task and show that it correlates\nwell with downstream task performance. We also illustrate how the language\ngenerated from different encoders differs. We apply our approach to generate\nsentence analogies from sentence embeddings.',
      'Yes',
      -0.004863006),
     ('how do bi-encoders work for sentence embeddings',
      'Non-Linguistic Supervision for Contrastive Learning of Sentence Embeddings: Semantic representation learning for sentences is an important and\nwell-studied problem in NLP. The current trend for this task involves training\na Transformer-based sentence encoder through a contrastive objective with text,\ni.e., clustering sentences with semantically similar meanings and scattering\nothers. In this work, we find the performance of Transformer models as sentence\nencoders can be improved by training with multi-modal multi-task losses, using\nunpaired examples from another modality (e.g., sentences and unrelated\nimage/audio data). In particular, besides learning by the contrastive loss on\ntext, our model clusters examples from a non-linguistic domain (e.g.,\nvisual/audio) with a similar contrastive loss at the same time. The reliance of\nour framework on unpaired non-linguistic data makes it language-agnostic,\nenabling it to be widely applicable beyond English NLP. Experiments on 7\nsemantic textual similarity benchmarks reveal that models trained with the\nadditional non-linguistic (/images/audio) contrastive objective lead to higher\nquality sentence embeddings. This indicates that Transformer models are able to\ngeneralize better by doing a similar task (i.e., clustering) with unpaired\nexamples from different modalities in a multi-task fashion.',
      'No',
      -0.013869206)]




```python
output_df = pd.DataFrame(
    output_list, columns=["query", "document", "prediction", "logprobs"]
).reset_index()
# Use exp() to convert logprobs into probability
output_df["probability"] = output_df["logprobs"].apply(exp)
# Reorder based on likelihood of being Yes
output_df["yes_probability"] = output_df.apply(
    lambda x: x["probability"] * -1 + 1
    if x["prediction"] == "No"
    else x["probability"],
    axis=1,
)
output_df.head()
```


key: _node_content
string_value:
{"id_": "8224a511-f87c-4235-a80e-b5aab76ccbeb", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "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": "64f6fb54-183f-4a0b-a1e1-9040a6717110", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "e8e0acaf40970dd551e968e92897d3415bd23a6e4bc77c0be91f1270b664426c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "536485a8-535b-428d-b5a3-9ad561b51b86", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "4f116265baae5c2e107aad5ed992682e60d72bc0797ec7e3ad4e92e64c9d0228", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5070a8e8-6e31-488d-82ba-37869d635c42", "node_type": "1", "metadata": {}, "hash": "55647bea4fbc3f70bf955f21af430a006d62dfe440b5afa05380b7569874f93d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 25983, "end_char_idx": 29606, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The current trend for this task involves training\na Transformer-based sentence encoder through a contrastive objective with text,\ni.e., clustering sentences with semantically similar meanings and scattering\nothers. In this work, we find the performance of Transformer models as sentence\nencoders can be improved by training with multi-modal multi-task losses, using\nunpaired examples from another modality (e.g., sentences and unrelated\nimage/audio data). In particular, besides learning by the contrastive loss on\ntext, our model clusters examples from a non-linguistic domain (e.g.,\nvisual/audio) with a similar contrastive loss at the same time. The reliance of\nour framework on unpaired non-linguistic data makes it language-agnostic,\nenabling it to be widely applicable beyond English NLP. Experiments on 7\nsemantic textual similarity benchmarks reveal that models trained with the\nadditional non-linguistic (/images/audio) contrastive objective lead to higher\nquality sentence embeddings. This indicates that Transformer models are able to\ngeneralize better by doing a similar task (i.e., clustering) with unpaired\nexamples from different modalities in a multi-task fashion.',
      'No',
      -0.013869206)]




```python
output_df = pd.DataFrame(
    output_list, columns=["query", "document", "prediction", "logprobs"]
).reset_index()
# Use exp() to convert logprobs into probability
output_df["probability"] = output_df["logprobs"].apply(exp)
# Reorder based on likelihood of being Yes
output_df["yes_probability"] = output_df.apply(
    lambda x: x["probability"] * -1 + 1
    if x["prediction"] == "No"
    else x["probability"],
    axis=1,
)
output_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>index</th>
      <th>query</th>
      <th>document</th>
      <th>prediction</th>
      <th>logprobs</th>
      <th>probability</th>
      <th>yes_probability</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>0</td>
      <td>how do bi-encoders work for sentence embeddings</td>
      <td>SBERT studies Meaning Representations: Decompo...</td>
      <td>Yes</td>
      <td>-0.053264</td>
      <td>0.948130</td>
      <td>0.948130</td>
    </tr>
    <tr>
      <th>1</th>
      <td>1</td>
      <td>how do bi-encoders work for sentence embeddings</td>
      <td>Are Classes Clusters?: Sentence embedding mode...</td>
      <td>No</td>
      <td>-0.009535</td>
      <td>0.990510</td>
      <td>0.009490</td>
    </tr>
    <tr>
      <th>2</th>
      <td>2</td>
      <td>how do bi-encoders work for sentence embeddings</td>
      <td>Semantic Composition in Visually Grounded Lang...</td>
      <td>No</td>
      <td>-0.008887</td>
      <td>0.991152</td>
      <td>0.008848</td>
    </tr>
    <tr>
      <th>3</th>
      <td>3</td>
      <td>how do bi-encoders work for sentence embeddings</td>
      <td>Evaluating the Construct Validity of Text Embe...</td>
      <td>No</td>
      <td>-0.008584</td>
      <td>0.991453</td>
      <td>0.008547</td>
    </tr>
    <tr>
      <th>4</th>
      <td>4</td>
      <td>how do bi-encoders work for sentence embeddings</td>
      <td>Learning Probabilistic Sentence Representation...</td>
      <td>No</td>
      <td>-0.011976</td>
      <td>0.988096</td>
      <td>0.011904</td>
    </tr>
  </tbody>
</table>
</div>


key: _node_content
string_value:
{"id_": "5070a8e8-6e31-488d-82ba-37869d635c42", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "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": "64f6fb54-183f-4a0b-a1e1-9040a6717110", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "e8e0acaf40970dd551e968e92897d3415bd23a6e4bc77c0be91f1270b664426c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8224a511-f87c-4235-a80e-b5aab76ccbeb", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "2f51f7a22cf5b6141882dfc1e2f4019e9985025b15bd2db2904922017ff5ad4d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "61b79056-6555-4491-9e27-ad3db769e7a3", "node_type": "1", "metadata": {}, "hash": "4301d325c747ff48cd51bab7eab09876a069081b5833546d979c5590bdb8e8be", "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
# Return reranked results
reranked_df = output_df.sort_values(
    by=["yes_probability"], ascending=False
).reset_index()
reranked_df.head(10)
```




<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>level_0</th>
      <th>index</th>
      <th>query</th>
      <th>document</th>
      <th>prediction</th>
      <th>logprobs</th>
      <th>probability</th>
      <th>yes_probability</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>16</td>
      <td>16</td>
      <td>how do bi-encoders work for sentence embeddings</td>
      <td>In Search for Linear Relations in Sentence Emb.</td>
      <td>Yes</td>
      <td>-0.004824</td>
      <td>0.995187</td>
      <td>0.995187</td>
    </tr>
    <tr>
      <th>1</th>
      <td>8</td>
      <td>8</td>
      <td>how do bi-encoders work for sentence embeddings</td>
      <td>Vec2Sent: Probing Sentence Embeddings with Nat.</td>
      <td>Yes</td>
      <td>-0.004863</td>
      <td>0.995149</td>
      <td>0.995149</td>
    </tr>
    <tr>
      <th>2</th>
      <td>19</td>
      <td>19</td>
      <td>how do bi-encoders work for sentence embeddings</td>
      <td>Relational Sentence Embedding for Flexible Sem.</td>
      <td>Yes</td>
      <td>-0.038814</td>
      <td>0.961930</td>
      <td>0.961930</td>
    </tr>
    <tr>
      <th>3</th>
      <td>0</td>
      <td>0</td>
      <td>how do bi-encoders work for sentence embeddings</td>
      <td>SBERT studies Meaning Representations: Decompo.</td>
      <td>Yes</td>
      <td>-0.053264</td>
      <td>0.948130</td>
      <td>0.948130</td>
    </tr>
    <tr>
      <th>4</th>
      <td>15</td>
      <td>15</td>
      <td>how do bi-encoders work for sentence embeddings</td>
      <td>Sentence-T5: Scalable Sentence Encoders from P.</td>
      <td>No</td>
      <td>-0.291893</td>
      <td>0.746849</td>
      <td>0.


key: _node_content
string_value:
{"id_": "61b79056-6555-4491-9e27-ad3db769e7a3", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "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": "64f6fb54-183f-4a0b-a1e1-9040a6717110", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "e8e0acaf40970dd551e968e92897d3415bd23a6e4bc77c0be91f1270b664426c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5070a8e8-6e31-488d-82ba-37869d635c42", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "9ff4ce39361d7bf9ab8a499f46f7ce4b32602dbd80bd55fa2540b9c28cc2fcee", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "dbc596cb-bb5e-419f-acf8-498086d31d54", "node_type": "1", "metadata": {}, "hash": "9ccd774dacbd5341f4ad9452c643df9af4b136c9c2a3c1e202c34a7c516725b8", "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:
</td>
      <td>Yes</td>
      <td>-0.004863</td>
      <td>0.995149</td>
      <td>0.995149</td>
    </tr>
    <tr>
      <th>2</th>
      <td>19</td>
      <td>19</td>
      <td>how do bi-encoders work for sentence embeddings</td>
      <td>Relational Sentence Embedding for Flexible Sem.</td>
      <td>Yes</td>
      <td>-0.038814</td>
      <td>0.961930</td>
      <td>0.961930</td>
    </tr>
    <tr>
      <th>3</th>
      <td>0</td>
      <td>0</td>
      <td>how do bi-encoders work for sentence embeddings</td>
      <td>SBERT studies Meaning Representations: Decompo.</td>
      <td>Yes</td>
      <td>-0.053264</td>
      <td>0.948130</td>
      <td>0.948130</td>
    </tr>
    <tr>
      <th>4</th>
      <td>15</td>
      <td>15</td>
      <td>how do bi-encoders work for sentence embeddings</td>
      <td>Sentence-T5: Scalable Sentence Encoders from P.</td>
      <td>No</td>
      <td>-0.291893</td>
      <td>0.746849</td>
      <td>0.253151</td>
    </tr>
    <tr>
      <th>5</th>
      <td>6</td>
      <td>6</td>
      <td>how do bi-encoders work for sentence embeddings</td>
      <td>How to Probe Sentence Embeddings in Low-Resour.</td>
      <td>No</td>
      <td>-0.015551</td>
      <td>0.984570</td>
      <td>0.015430</td>
    </tr>
    <tr>
      <th>6</th>
      <td>18</td>
      <td>18</td>
      <td>how do bi-encoders work for sentence embeddings</td>
      <td>Efficient and Flexible Topic Modeling using Pr.</td>
      <td>No</td>
      <td>-0.015296</td>
      <td>0.984820</td>
      <td>0.015180</td>
    </tr>
    <tr>
      <th>7</th>
      <td>9</td>
      <td>9</td>
      <td>how do bi-encoders work for sentence embeddings</td>
      <td>Non-Linguistic Supervision for Contrastive Lea.</td>
      <td>No</td>
      <td>-0.013869</td>
      <td>0.986227</td>
      <td>0.013773</td>
    </tr>
    <tr>
      <th>8</th>
      <td>12</td>
      <td>12</td>
      <td>how do bi-encoders work for sentence embeddings</td>
      <td>Character-based Neural Networks for Sentence P.</td>
      <td>No</td>
      <td>-0.


key: _node_content
string_value:
{"id_": "dbc596cb-bb5e-419f-acf8-498086d31d54", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "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": "64f6fb54-183f-4a0b-a1e1-9040a6717110", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "e8e0acaf40970dd551e968e92897d3415bd23a6e4bc77c0be91f1270b664426c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "61b79056-6555-4491-9e27-ad3db769e7a3", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "e5262f94111b0cbcbc528346b8015dbb15da3d15f5bb995d23eb1fd6af84b46c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ddfdcb0d-ea3a-4b1b-8d4e-c5adb44baacc", "node_type": "1", "metadata": {}, "hash": "c4a1cdfad550df49c77588a65fee24326cbbe17b705f2857cb71870de6044e47", "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:
</td>
      <td>No</td>
      <td>-0.015551</td>
      <td>0.984570</td>
      <td>0.015430</td>
    </tr>
    <tr>
      <th>6</th>
      <td>18</td>
      <td>18</td>
      <td>how do bi-encoders work for sentence embeddings</td>
      <td>Efficient and Flexible Topic Modeling using Pr.</td>
      <td>No</td>
      <td>-0.015296</td>
      <td>0.984820</td>
      <td>0.015180</td>
    </tr>
    <tr>
      <th>7</th>
      <td>9</td>
      <td>9</td>
      <td>how do bi-encoders work for sentence embeddings</td>
      <td>Non-Linguistic Supervision for Contrastive Lea.</td>
      <td>No</td>
      <td>-0.013869</td>
      <td>0.986227</td>
      <td>0.013773</td>
    </tr>
    <tr>
      <th>8</th>
      <td>12</td>
      <td>12</td>
      <td>how do bi-encoders work for sentence embeddings</td>
      <td>Character-based Neural Networks for Sentence P.</td>
      <td>No</td>
      <td>-0.012866</td>
      <td>0.987216</td>
      <td>0.012784</td>
    </tr>
    <tr>
      <th>9</th>
      <td>7</td>
      <td>7</td>
      <td>how do bi-encoders work for sentence embeddings</td>
      <td>Clustering and Network Analysis for the Embedd.</td>
      <td>No</td>
      <td>-0.012663</td>
      <td>0.987417</td>
      <td>0.012583</td>
    </tr>
  </tbody>
</table>
</div>




```python
# Inspect our new top document following reranking
reranked_df["document"][0]
```




    'In Search for Linear Relations in Sentence Embedding Spaces: We present an introductory investigation into continuous-space vector\nrepresentations of sentences. We acquire pairs of very similar sentences\ndiffering only by a small alterations (such as change of a noun, adding an\nadjective, noun or punctuation) from datasets for natural language inference\nusing a simple pattern method. We look into how such a small change within the\nsentence text affects its representation in the continuous space and how such\nalterations are reflected by some of the popular sentence embedding models. We\nfound that vector differences of some embeddings actually reflect small changes\nwithin a sentence.'


key: _node_content
string_value:
{"id_": "ddfdcb0d-ea3a-4b1b-8d4e-c5adb44baacc", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "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": "64f6fb54-183f-4a0b-a1e1-9040a6717110", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "e8e0acaf40970dd551e968e92897d3415bd23a6e4bc77c0be91f1270b664426c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "dbc596cb-bb5e-419f-acf8-498086d31d54", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "923661de9f1cd98e894f954decdcd4744bd496cfe8e9a9500d125358daf7794b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "31837814-3158-4126-b5b7-105573d1385a", "node_type": "1", "metadata": {}, "hash": "b5e50adc8fdc354796302ff46de056e26161b30d28ff4177475e4807015d7615", "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:
986227</td>
      <td>0.013773</td>
    </tr>
    <tr>
      <th>8</th>
      <td>12</td>
      <td>12</td>
      <td>how do bi-encoders work for sentence embeddings</td>
      <td>Character-based Neural Networks for Sentence P.</td>
      <td>No</td>
      <td>-0.012866</td>
      <td>0.987216</td>
      <td>0.012784</td>
    </tr>
    <tr>
      <th>9</th>
      <td>7</td>
      <td>7</td>
      <td>how do bi-encoders work for sentence embeddings</td>
      <td>Clustering and Network Analysis for the Embedd.</td>
      <td>No</td>
      <td>-0.012663</td>
      <td>0.987417</td>
      <td>0.012583</td>
    </tr>
  </tbody>
</table>
</div>




```python
# Inspect our new top document following reranking
reranked_df["document"][0]
```




    'In Search for Linear Relations in Sentence Embedding Spaces: We present an introductory investigation into continuous-space vector\nrepresentations of sentences. We acquire pairs of very similar sentences\ndiffering only by a small alterations (such as change of a noun, adding an\nadjective, noun or punctuation) from datasets for natural language inference\nusing a simple pattern method. We look into how such a small change within the\nsentence text affects its representation in the continuous space and how such\nalterations are reflected by some of the popular sentence embedding models. We\nfound that vector differences of some embeddings actually reflect small changes\nwithin a sentence.'



## Conclusion

We've shown how to create a tailored cross-encoder to rerank academic papers. This approach will work best where there are domain-specific nuances that can be used to pick the most relevant corpus for your users, and where some pre-filtering has taken place to limit the amount of data the cross-encoder will need to process. 

A few typical use cases we've seen are:
- Returning a list of 100 most relevant stock reports, then re-ordering into a top 5 or 10 based on the detailed context of a particular set of customer portfolios
- Running after a classic rules-based search that gets the top 100 or 1000 most relevant results to prune it according to a specific user's context


key: _node_content
string_value:
{"id_": "31837814-3158-4126-b5b7-105573d1385a", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "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": "64f6fb54-183f-4a0b-a1e1-9040a6717110", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "e8e0acaf40970dd551e968e92897d3415bd23a6e4bc77c0be91f1270b664426c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ddfdcb0d-ea3a-4b1b-8d4e-c5adb44baacc", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Search_reranking_with_cross-encoders.ipynb", "title": "Search reranking with cross-encoders", "tokens": 8550, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "6d34501548ab229bc051f5699b09a2b15e6cc393a3ef14aeeba0c26d7bc4a12c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 33132, "end_char_idx": 35818, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
</td>
      <td>No</td>
      <td>-0.012663</td>
      <td>0.987417</td>
      <td>0.012583</td>
    </tr>
  </tbody>
</table>
</div>




```python
# Inspect our new top document following reranking
reranked_df["document"][0]
```




    'In Search for Linear Relations in Sentence Embedding Spaces: We present an introductory investigation into continuous-space vector\nrepresentations of sentences. We acquire pairs of very similar sentences\ndiffering only by a small alterations (such as change of a noun, adding an\nadjective, noun or punctuation) from datasets for natural language inference\nusing a simple pattern method. We look into how such a small change within the\nsentence text affects its representation in the continuous space and how such\nalterations are reflected by some of the popular sentence embedding models. We\nfound that vector differences of some embeddings actually reflect small changes\nwithin a sentence.'



## Conclusion

We've shown how to create a tailored cross-encoder to rerank academic papers. This approach will work best where there are domain-specific nuances that can be used to pick the most relevant corpus for your users, and where some pre-filtering has taken place to limit the amount of data the cross-encoder will need to process. 

A few typical use cases we've seen are:
- Returning a list of 100 most relevant stock reports, then re-ordering into a top 5 or 10 based on the detailed context of a particular set of customer portfolios
- Running after a classic rules-based search that gets the top 100 or 1000 most relevant results to prune it according to a specific user's context


### Taking this forward

Taking the few-shot approach, as we have here, can work well when the domain is general enough that a small number of examples will cover most reranking cases. However, as the differences between documents become more specific you may want to consider the ```Fine-tuning``` endpoint to make a more elaborate cross-encoder with a wider variety of examples.

There is also a latency impact of using ```text-davinci-003``` that you'll need to consider, with even our few examples above taking a couple seconds each - again, the ```Fine-tuning``` endpoint may help you here if you are able to get decent results from an ```ada``` or ```babbage``` fine-tuned model.

We've used the ```Completions``` endpoint from OpenAI to build our cross-encoder, but this area is well-served by the open-source community. [Here](https://huggingface.co/jeffwan/mmarco-mMiniLMv2-L12-H384-v1) is an example from HuggingFace, for example.

We hope you find this useful for tuning your search use cases, and look forward to seeing what you build.


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


key: _node_content
string_value:
{"id_": "4e5a0bad-4256-4d0b-a880-43938cf6e343", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "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": "e9c2174d-60ab-46c7-957a-68d4dba0e2de", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "08d6debfe4bbada449d92980d14820013f43524fedf52714c13172e527a12c07", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "feb89fd2-8e6d-4741-a92a-84d88239f6ba", "node_type": "1", "metadata": {}, "hash": "b8a6f3ffc28b8f5102cba3eae6067a88e995678ef8fdaead23ed51c41fded080", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2246, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
## Developing Hallucination Guardrails

A guardrail is a set of rules and checks designed to ensure that the outputs of an LLM are accurate, appropriate, and aligned with user expectations. For more additional information on developing guardrails, you can refer to this [guide on developing guardrails](https://cookbook.openai.com/examples/how_to_use_guardrails).

In this notebook, we'll walk through the process of developing an output guardrail that specifically checks model outputs for hallucinations. 

This notebook will focus on:
1. Building out a strong eval set
2. Identifying specific criteria to measure hallucinations
3. Improving the accuracy of our guardrail with few-shot prompting



```python
from concurrent.futures import ThreadPoolExecutor
from IPython.display import display, HTML
import json
import pandas as pd
from sklearn.metrics import precision_score, recall_score
from typing import List
from openai import OpenAI

client = OpenAI()
```


```python
# Function to set up display options for pandas
def setup_pandas_display():
    # Increase display limits
    pd.set_option('display.max_rows', 500)
    pd.set_option('display.max_columns', 500)

# Function to make DataFrame scrollable in the notebook output
def make_scrollable(df):
    style = (
        '<style>'
        'div.output_scroll {'
        'resize: both;'
        'overflow: auto;'
        '}'
        '</style>'
    )
    html = f"{style}{df.to_html()}"
    display(HTML(html))

# Main function to display DataFrame
def display_dataframe(df):
    setup_pandas_display()    # Enable scrollable view
    make_scrollable(df)

```

## 1. Building out an eval set

Imagine we are a customer support team that is building out an automated support agent. We will be feeding the assistant information from our knowledge base about a specific set of policies for how to handle tickets such as returns, refunds, feedback, and expect the model to follow the policy when interacting with customers.

The first thing we will do is use GPT-4o to build out a set of policies that we will want to follow.

If you want to do deep dive into generating synthetic data, you can review our Synthetic Data Generation Cookbook [here](https://cookbook.openai.com/examples/sdg1)


key: _node_content
string_value:
{"id_": "feb89fd2-8e6d-4741-a92a-84d88239f6ba", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "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": "e9c2174d-60ab-46c7-957a-68d4dba0e2de", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "08d6debfe4bbada449d92980d14820013f43524fedf52714c13172e527a12c07", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4e5a0bad-4256-4d0b-a880-43938cf6e343", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "62b5322369a537afcf3c536c23fb0f252f1940f3a93d111499bddac0d1b5078c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4e5d219b-8dfa-49ce-903e-78ddca139da2", "node_type": "1", "metadata": {}, "hash": "4578abbe6ecdb750e6c7b47c0d256703667cc897656f106bd8016c7fe80d6e54", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 701, "end_char_idx": 4395, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
from concurrent.futures import ThreadPoolExecutor
from IPython.display import display, HTML
import json
import pandas as pd
from sklearn.metrics import precision_score, recall_score
from typing import List
from openai import OpenAI

client = OpenAI()
```


```python
# Function to set up display options for pandas
def setup_pandas_display():
    # Increase display limits
    pd.set_option('display.max_rows', 500)
    pd.set_option('display.max_columns', 500)

# Function to make DataFrame scrollable in the notebook output
def make_scrollable(df):
    style = (
        '<style>'
        'div.output_scroll {'
        'resize: both;'
        'overflow: auto;'
        '}'
        '</style>'
    )
    html = f"{style}{df.to_html()}"
    display(HTML(html))

# Main function to display DataFrame
def display_dataframe(df):
    setup_pandas_display()    # Enable scrollable view
    make_scrollable(df)

```

## 1. Building out an eval set

Imagine we are a customer support team that is building out an automated support agent. We will be feeding the assistant information from our knowledge base about a specific set of policies for how to handle tickets such as returns, refunds, feedback, and expect the model to follow the policy when interacting with customers.

The first thing we will do is use GPT-4o to build out a set of policies that we will want to follow.

If you want to do deep dive into generating synthetic data, you can review our Synthetic Data Generation Cookbook [here](https://cookbook.openai.com/examples/sdg1)


```python
system_input_prompt = """
You are a helpful assistant that can generate policies for a support agent at a fictional company to follow. You will be provided with a topic (ie. returns, refunds, feedback) and you are to generate a sample policy for how to handle the it.

When constructing the policy, it should contain step-by-step instructions for how to handle the customer inquiry. It should include decision logic for what to do if a customer falls under a certain category, and provide requirements for taking specific actions.
"""

user_policy_example_1 = """"
RETURN POLICY
"""

assistant_policy_example_1 = """
RETURN POLICY

1. ** Ask the customer why they want the order replaced **
    - Categorize their issue into one of the following buckets:
        - damaged: They received the product in a damaged state
        - satisfaction: The customer is not satisfied with the item and does not like the product.
        - unnecessary: They no longer need the item
2a. **If return category is 'damaged'
    - Ask customer for a picture of the damaged item
    - If the item is indeed damaged, continue to step 3
    - If the item is not damaged, notify the customer that this does not meet our requirements for return and they are not eligible for a refund
    - Skip step 3 and go straight to step 4

2b. **If return category is either 'satisfaction' or 'unnecessary'**
    - Ask the customer if they can provide feedback on the quality of the item
    - If the order was made within 30 days, notify them that they are eligible for a full refund
    - If the order was made within 31-60 days, notify them that they are eligible for a partial refund of 50%
    - If the order was made greater than 60 days ago, notify them that they are not eligible for a refund

3. **If the customer is eligible for a return or refund**
    - Ask the customer to confirm that they would like a return or refund
    - Once they confirm, process their request

4 **Provide additional support before closing out ticket**
    - Ask the customer if there is anything else you can do to help them today.

"""

user_policy_input = """
{{POLICY}}
"""
```


key: _node_content
string_value:
{"id_": "4e5d219b-8dfa-49ce-903e-78ddca139da2", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "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": "e9c2174d-60ab-46c7-957a-68d4dba0e2de", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "08d6debfe4bbada449d92980d14820013f43524fedf52714c13172e527a12c07", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "feb89fd2-8e6d-4741-a92a-84d88239f6ba", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "00050ad5a97d148ca461eb85b4f559e8a533c7d1ed5431fcd273e7eed5f1f921", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ad359d2e-3a9d-4c6f-bb32-159882c1d9a0", "node_type": "1", "metadata": {}, "hash": "3beb5ea763c30e3caf60e5016eb2bbff7e876cae17efc82e16979d4c0e743002", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 4398, "end_char_idx": 7715, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
def generate_policy(policy: str) -> str:
    input_message = user_policy_input.replace("{{POLICY}}", policy)
    
    response = client.chat.completions.create(
        messages= [
            {"role": "system", "content": system_input_prompt},
            {"role": "user", "content": user_policy_example_1},
            {"role": "assistant", "content": assistant_policy_example_1},
            {"role": "user", "content": input_message},
        ],
        model="gpt-4o"
    )
    
    return response.choices[0].message.content

def generate_policies() -> List[str]:
    # List of different types of policies to generate 
    policies = ['PRODUCT FEEDBACK POLICY', 'SHIPPING POLICY', 'WARRANTY POLICY', 'ACCOUNT DELETION', 'COMPLAINT RESOLUTION']
    
    with ThreadPoolExecutor() as executor:
        policy_instructions_list = list(executor.map(generate_policy, policies))
        
    return policy_instructions_list

policy_instructions = generate_policies()
```

Next we'll take these policies and generate sample customer interactions that do or do not follow the instructions.


```python
system_input_prompt = """"
You are a helpful assistant that can generate fictional interactions between a support assistant and a customer user. You will be given a set of policy instructions that the support agent is instructed to follow.

Based on the instructions, you must generate a relevant single-turn or multi-turn interaction between the assistant and the user. It should average between 1-3 turns total.

For a given set of instructions, generate an example conversation that where the assistant either does or does not follow the instructions properly. In the assistant's responses, have it give a combination of single sentence and multi-sentence responses.

The output must be in a json format with the following three parameters:
 - accurate: 
    - This should be a boolean True or False value that matches whether or not the final assistant message accurately follows the policy instructions
 - kb_article:
    - This should be the entire policy instruction that is passed in from the user
 - chat_history: 
    - This should contain the entire conversation history except for the final assistant message. 
    - This should be in a format of an array of jsons where each json contains two parameters: role, and content. 
    - Role should be set to either 'user' to represent the customer, or 'assistant' to represent the customer support assistant. 
    - Content should contain the message from the appropriate role.
    - The final message in the chat history should always come from the user. The assistant response in the following parameter will be a response to this use message.
 - assistant_response: 
    - This should contain the final response from the assistant. This is what we will evaluate to determine whether or not it is accurately following the policy.
"""

user_example_1 = """"
Here are the policy instructions:
RETURN POLICY

1. ** Ask the customer why they want the order replaced **
    - Categorize their issue into one of the following buckets:
        - damaged: They received the product in a damaged state
        - satisfaction: The customer is not satisfied with the item and does not like the product.
        - unnecessary: They no longer need the item
2a.


key: _node_content
string_value:
{"id_": "ad359d2e-3a9d-4c6f-bb32-159882c1d9a0", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "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": "e9c2174d-60ab-46c7-957a-68d4dba0e2de", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "08d6debfe4bbada449d92980d14820013f43524fedf52714c13172e527a12c07", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4e5d219b-8dfa-49ce-903e-78ddca139da2", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "32948867aafdbb0f84eb9b081af4bd4fe88ade7c21bf233d9567c66316a9b919", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "59581286-bbbe-4b49-aed6-8b79e12502bf", "node_type": "1", "metadata": {}, "hash": "26edfa70bcb2c4b56abe23aff655525e63558171ae2c415da5643636301ba1f4", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5749, "end_char_idx": 9219, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Based on the instructions, you must generate a relevant single-turn or multi-turn interaction between the assistant and the user. It should average between 1-3 turns total.

For a given set of instructions, generate an example conversation that where the assistant either does or does not follow the instructions properly. In the assistant's responses, have it give a combination of single sentence and multi-sentence responses.

The output must be in a json format with the following three parameters:
 - accurate: 
    - This should be a boolean True or False value that matches whether or not the final assistant message accurately follows the policy instructions
 - kb_article:
    - This should be the entire policy instruction that is passed in from the user
 - chat_history: 
    - This should contain the entire conversation history except for the final assistant message. 
    - This should be in a format of an array of jsons where each json contains two parameters: role, and content. 
    - Role should be set to either 'user' to represent the customer, or 'assistant' to represent the customer support assistant. 
    - Content should contain the message from the appropriate role.
    - The final message in the chat history should always come from the user. The assistant response in the following parameter will be a response to this use message.
 - assistant_response: 
    - This should contain the final response from the assistant. This is what we will evaluate to determine whether or not it is accurately following the policy.
"""

user_example_1 = """"
Here are the policy instructions:
RETURN POLICY

1. ** Ask the customer why they want the order replaced **
    - Categorize their issue into one of the following buckets:
        - damaged: They received the product in a damaged state
        - satisfaction: The customer is not satisfied with the item and does not like the product.
        - unnecessary: They no longer need the item
2a. **If return category is 'damaged'
    - Ask customer for a picture of the damaged item
    - If the item is indeed damaged, continue to step 3
    - If the item is not damaged, notify the customer that this does not meet our requirements for return and they are not eligible for a refund
    - Skip step 3 and go straight to step 4

2b. **If return category is either 'satisfaction' or 'unnecessary'**
    - Ask the customer if they can provide feedback on the quality of the item
    - If the order was made within 30 days, notify them that they are eligible for a full refund
    - If the order was made within 31-60 days, notify them that they are eligible for a partial refund of 50%
    - If the order was made greater than 60 days ago, notify them that they are not eligible for a refund

3. **If the customer is eligible for a return or refund**
    - Ask the customer to confirm that they would like a return or refund
    - Once they confirm, process their request

4 **Provide additional support before closing out ticket**
    - Ask the customer if there is anything else you can do to help them today.
"""

assistant_example_1 = """
{
    "accurate": "true",
    "kb_article": "1. ** Ask the customer why they want the order replaced ** - Categorize their issue into one of the following buckets: - damaged: They received the product in a damaged state - satisfaction: The customer is not satisfied with the item and does not like the product. - unnecessary: They no longer need the item 2a.


key: _node_content
string_value:
{"id_": "59581286-bbbe-4b49-aed6-8b79e12502bf", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "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": "e9c2174d-60ab-46c7-957a-68d4dba0e2de", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "08d6debfe4bbada449d92980d14820013f43524fedf52714c13172e527a12c07", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ad359d2e-3a9d-4c6f-bb32-159882c1d9a0", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "b27076f8bf23379d438e8cac2d9abb81f7272bd806eb396c50a8b2c942446c5a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ba3f43e5-6b87-4c7d-9527-096843a2888d", "node_type": "1", "metadata": {}, "hash": "b668c2cc8bdba5848c31aad95d8b1964ef1be653197e18250518d23252936e18", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 7668, "end_char_idx": 10927, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
- unnecessary: They no longer need the item
2a. **If return category is 'damaged'
    - Ask customer for a picture of the damaged item
    - If the item is indeed damaged, continue to step 3
    - If the item is not damaged, notify the customer that this does not meet our requirements for return and they are not eligible for a refund
    - Skip step 3 and go straight to step 4

2b. **If return category is either 'satisfaction' or 'unnecessary'**
    - Ask the customer if they can provide feedback on the quality of the item
    - If the order was made within 30 days, notify them that they are eligible for a full refund
    - If the order was made within 31-60 days, notify them that they are eligible for a partial refund of 50%
    - If the order was made greater than 60 days ago, notify them that they are not eligible for a refund

3. **If the customer is eligible for a return or refund**
    - Ask the customer to confirm that they would like a return or refund
    - Once they confirm, process their request

4 **Provide additional support before closing out ticket**
    - Ask the customer if there is anything else you can do to help them today.
"""

assistant_example_1 = """
{
    "accurate": "true",
    "kb_article": "1. ** Ask the customer why they want the order replaced ** - Categorize their issue into one of the following buckets: - damaged: They received the product in a damaged state - satisfaction: The customer is not satisfied with the item and does not like the product. - unnecessary: They no longer need the item 2a. **If return category is 'damaged' - Ask customer for a picture of the damaged item - If the item is indeed damaged, continue to step 3 - If the item is not damaged, notify the customer that this does not meet our requirements for return and they are not eligible for a refund - Skip step 3 and go straight to step 4 2b. **If return category is either 'satisfaction' or 'unnecessary'** - Ask the customer if they can provide feedback on the quality of the item - If the order was made within 30 days, notify them that they are eligible for a full refund - If the order was made within 31-60 days, notify them that they are eligible for a partial refund of 50% - If the order was made greater than 60 days ago, notify them that they are not eligible for a refund 3. **If the customer is eligible for a return or refund** - Ask the customer to confirm that they would like a return or refund - Once they confirm, process their request 4 **Provide additional support before closing out ticket** - Ask the customer if there is anything else you can do to help them today.",
    "chat_history": [
        {
            "role": "user",
            "content": "I would like to return this shirt"
        },
        {
            "role": "assistant",
            "content": "Hi there, I'm happy to help with processing this return. Can you please provide an explanation for why you'd like to return this shirt?"
        },
        {
            "role": "user",
            "content": "Yes, I am not satisfied with the design"
        }
    ],
    "assistant_response": {
        "role": "assistant",
        "content": "I see. Because the shirt was ordered in the last 30 days, we can provide you with a full refund.


key: _node_content
string_value:
{"id_": "ba3f43e5-6b87-4c7d-9527-096843a2888d", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "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": "e9c2174d-60ab-46c7-957a-68d4dba0e2de", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "08d6debfe4bbada449d92980d14820013f43524fedf52714c13172e527a12c07", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "59581286-bbbe-4b49-aed6-8b79e12502bf", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "be691e23239e5355333fddabeb2366e9f843280c15f6312bf1fb7942b52aca4e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c161a2ad-dbd5-4555-9a6e-18ab23c0ca08", "node_type": "1", "metadata": {}, "hash": "8b186bb309a874c900325b0b981e72c4219c4c26196bca2a9a491b6c4d1d9c89", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 9220, "end_char_idx": 12513, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
**If return category is 'damaged' - Ask customer for a picture of the damaged item - If the item is indeed damaged, continue to step 3 - If the item is not damaged, notify the customer that this does not meet our requirements for return and they are not eligible for a refund - Skip step 3 and go straight to step 4 2b. **If return category is either 'satisfaction' or 'unnecessary'** - Ask the customer if they can provide feedback on the quality of the item - If the order was made within 30 days, notify them that they are eligible for a full refund - If the order was made within 31-60 days, notify them that they are eligible for a partial refund of 50% - If the order was made greater than 60 days ago, notify them that they are not eligible for a refund 3. **If the customer is eligible for a return or refund** - Ask the customer to confirm that they would like a return or refund - Once they confirm, process their request 4 **Provide additional support before closing out ticket** - Ask the customer if there is anything else you can do to help them today.",
    "chat_history": [
        {
            "role": "user",
            "content": "I would like to return this shirt"
        },
        {
            "role": "assistant",
            "content": "Hi there, I'm happy to help with processing this return. Can you please provide an explanation for why you'd like to return this shirt?"
        },
        {
            "role": "user",
            "content": "Yes, I am not satisfied with the design"
        }
    ],
    "assistant_response": {
        "role": "assistant",
        "content": "I see. Because the shirt was ordered in the last 30 days, we can provide you with a full refund. Would you like me to process the refund?"
    }
}
"""

user_example_2 = """"
Here are the policy instructions:
RETURN POLICY

1. ** Ask the customer why they want the order replaced **
    - Categorize their issue into one of the following buckets:
        - damaged: They received the product in a damaged state
        - satisfaction: The customer is not satisfied with the item and does not like the product.
        - unnecessary: They no longer need the item
2a. **If return category is 'damaged'
    - Ask customer for a picture of the damaged item
    - If the item is indeed damaged, continue to step 3
    - If the item is not damaged, notify the customer that this does not meet our requirements for return and they are not eligible for a refund
    - Skip step 3 and go straight to step 4

2b. **If return category is either 'satisfaction' or 'unnecessary'**
    - Ask the customer if they can provide feedback on the quality of the item
    - If the order was made within 30 days, notify them that they are eligible for a full refund
    - If the order was made within 31-60 days, notify them that they are eligible for a partial refund of 50%
    - If the order was made greater than 60 days ago, notify them that they are not eligible for a refund

3. **If the customer is eligible for a return or refund**
    - Ask the customer to confirm that they would like a return or refund
    - Once they confirm, process their request

4 **Provide additional support before closing out ticket**
    - Ask the customer if there is anything else you can do to help them today.
"""


key: _node_content
string_value:
{"id_": "c161a2ad-dbd5-4555-9a6e-18ab23c0ca08", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "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": "e9c2174d-60ab-46c7-957a-68d4dba0e2de", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "08d6debfe4bbada449d92980d14820013f43524fedf52714c13172e527a12c07", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ba3f43e5-6b87-4c7d-9527-096843a2888d", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "7dc32a9a518e77d38bae795ffcce1efbd8411c89b98184c2675347ba5cb00ea0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "53f60ef2-0c59-40e7-91b5-7378a87beb3e", "node_type": "1", "metadata": {}, "hash": "75032821da90bf29599370e3c9942e634d6195eb4670b9f100d635d94b96111a", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 10838, "end_char_idx": 13967, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Because the shirt was ordered in the last 30 days, we can provide you with a full refund. Would you like me to process the refund?"
    }
}
"""

user_example_2 = """"
Here are the policy instructions:
RETURN POLICY

1. ** Ask the customer why they want the order replaced **
    - Categorize their issue into one of the following buckets:
        - damaged: They received the product in a damaged state
        - satisfaction: The customer is not satisfied with the item and does not like the product.
        - unnecessary: They no longer need the item
2a. **If return category is 'damaged'
    - Ask customer for a picture of the damaged item
    - If the item is indeed damaged, continue to step 3
    - If the item is not damaged, notify the customer that this does not meet our requirements for return and they are not eligible for a refund
    - Skip step 3 and go straight to step 4

2b. **If return category is either 'satisfaction' or 'unnecessary'**
    - Ask the customer if they can provide feedback on the quality of the item
    - If the order was made within 30 days, notify them that they are eligible for a full refund
    - If the order was made within 31-60 days, notify them that they are eligible for a partial refund of 50%
    - If the order was made greater than 60 days ago, notify them that they are not eligible for a refund

3. **If the customer is eligible for a return or refund**
    - Ask the customer to confirm that they would like a return or refund
    - Once they confirm, process their request

4 **Provide additional support before closing out ticket**
    - Ask the customer if there is anything else you can do to help them today.
"""

assistant_example_2 = """
{
    "accurate": "false",
    "kb_article": "1. ** Ask the customer why they want the order replaced ** - Categorize their issue into one of the following buckets: - damaged: They received the product in a damaged state - satisfaction: The customer is not satisfied with the item and does not like the product. - unnecessary: They no longer need the item 2a. **If return category is 'damaged' - Ask customer for a picture of the damaged item - If the item is indeed damaged, continue to step 3 - If the item is not damaged, notify the customer that this does not meet our requirements for return and they are not eligible for a refund - Skip step 3 and go straight to step 4 2b. **If return category is either 'satisfaction' or 'unnecessary'** - Ask the customer if they can provide feedback on the quality of the item - If the order was made within 30 days, notify them that they are eligible for a full refund - If the order was made within 31-60 days, notify them that they are eligible for a partial refund of 50% - If the order was made greater than 60 days ago, notify them that they are not eligible for a refund 3. **If the customer is eligible for a return or refund** - Ask the customer to confirm that they would like a return or refund - Once they confirm, process their request 4 **Provide additional support before closing out ticket** - Ask the customer if there is anything else you can do to help them today.


key: _node_content
string_value:
{"id_": "53f60ef2-0c59-40e7-91b5-7378a87beb3e", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "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": "e9c2174d-60ab-46c7-957a-68d4dba0e2de", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "08d6debfe4bbada449d92980d14820013f43524fedf52714c13172e527a12c07", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c161a2ad-dbd5-4555-9a6e-18ab23c0ca08", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "1d9c5e2ca04d223230d4af4937c460d51b78a14a9792fb30581244ea9f8f50fe", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f2c942f0-83a6-4594-9ed7-e1fd39401f3a", "node_type": "1", "metadata": {}, "hash": "309dc015d38a987af30a8a46ebab11f778f8f9f10b960f6ad499390920864a3f", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 12515, "end_char_idx": 15759, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
assistant_example_2 = """
{
    "accurate": "false",
    "kb_article": "1. ** Ask the customer why they want the order replaced ** - Categorize their issue into one of the following buckets: - damaged: They received the product in a damaged state - satisfaction: The customer is not satisfied with the item and does not like the product. - unnecessary: They no longer need the item 2a. **If return category is 'damaged' - Ask customer for a picture of the damaged item - If the item is indeed damaged, continue to step 3 - If the item is not damaged, notify the customer that this does not meet our requirements for return and they are not eligible for a refund - Skip step 3 and go straight to step 4 2b. **If return category is either 'satisfaction' or 'unnecessary'** - Ask the customer if they can provide feedback on the quality of the item - If the order was made within 30 days, notify them that they are eligible for a full refund - If the order was made within 31-60 days, notify them that they are eligible for a partial refund of 50% - If the order was made greater than 60 days ago, notify them that they are not eligible for a refund 3. **If the customer is eligible for a return or refund** - Ask the customer to confirm that they would like a return or refund - Once they confirm, process their request 4 **Provide additional support before closing out ticket** - Ask the customer if there is anything else you can do to help them today.",
    "chat_history": [
        {
            "role": "user",
            "content": "I would like to return this shirt"
        },
        {
            "role": "assistant",
            "content": "Hi there, I'm happy to help with processing this return. Can you please provide an explanation for why you'd like to return this shirt?"
        },
        {
            "role": "user",
            "content": "Yes, I am not satisfied with the design"
        }
    ],
    "assistant_response": {
        "role": "assistant",
        "content": "I see. Because the shirt was ordered in the last 60 days, we cannot process a refund."    
    }
}
"""
```

Now let's iterate through the policies and generate some examples.


```python
customer_interactions = []

def fetch_response(policy):
    messages = [
        { "role": "system", "content": system_input_prompt},
        { "role": "user", "content": user_example_1},
        { "role": "assistant", "content": assistant_example_1},
        { "role": "user", "content": user_example_2},
        { "role": "assistant", "content": assistant_example_2},
        { "role": "user", "content": policy}
    ]

    response = client.chat.completions.create(
        model="gpt-4o",
        messages=messages,
        temperature=0.7,
        n=10
    )
    return response.choices

with ThreadPoolExecutor() as executor:
    futures = [executor.submit(fetch_response, policy) for policy in policy_instructions]
    for future in futures:
        choices = future.result()
        customer_interactions.extend([choice.message.content for choice in choices])

```


```python
interaction_dict = json.loads(customer_interactions[0])

df_interaction = pd.DataFrame([interaction_dict])

# Pretty print the DataFrame
display_dataframe(df_interaction)

```


key: _node_content
string_value:
{"id_": "f2c942f0-83a6-4594-9ed7-e1fd39401f3a", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "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": "e9c2174d-60ab-46c7-957a-68d4dba0e2de", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "08d6debfe4bbada449d92980d14820013f43524fedf52714c13172e527a12c07", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "53f60ef2-0c59-40e7-91b5-7378a87beb3e", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "b0ab4baf95180ed5d6c88fc66318f95cfdcbf08bd1c67ef0994c1269fd1aff83", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "0d65ed82-e23f-4fec-9306-dd336024f0c5", "node_type": "1", "metadata": {}, "hash": "f4795af09643da5c7374ca1bc0fe375d92b2ea8ea151ae1cc9c486a2fc099f75", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 14224, "end_char_idx": 19157, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Can you please provide an explanation for why you'd like to return this shirt?"
        },
        {
            "role": "user",
            "content": "Yes, I am not satisfied with the design"
        }
    ],
    "assistant_response": {
        "role": "assistant",
        "content": "I see. Because the shirt was ordered in the last 60 days, we cannot process a refund."    
    }
}
"""
```

Now let's iterate through the policies and generate some examples.


```python
customer_interactions = []

def fetch_response(policy):
    messages = [
        { "role": "system", "content": system_input_prompt},
        { "role": "user", "content": user_example_1},
        { "role": "assistant", "content": assistant_example_1},
        { "role": "user", "content": user_example_2},
        { "role": "assistant", "content": assistant_example_2},
        { "role": "user", "content": policy}
    ]

    response = client.chat.completions.create(
        model="gpt-4o",
        messages=messages,
        temperature=0.7,
        n=10
    )
    return response.choices

with ThreadPoolExecutor() as executor:
    futures = [executor.submit(fetch_response, policy) for policy in policy_instructions]
    for future in futures:
        choices = future.result()
        customer_interactions.extend([choice.message.content for choice in choices])

```


```python
interaction_dict = json.loads(customer_interactions[0])

df_interaction = pd.DataFrame([interaction_dict])

# Pretty print the DataFrame
display_dataframe(df_interaction)

```


<style>div.output_scroll {resize: both;overflow: auto;}</style><table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>accurate</th>
      <th>kb_article</th>
      <th>chat_history</th>
      <th>assistant_response</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>true</td>
      <td>PRODUCT FEEDBACK POLICY 1. **Acknowledge Reception** - Thank the customer for taking the time to provide feedback. - Use a personalized greeting: "Thank you for your feedback, [Customer Name]. We appreciate your input." 2. **Categorize Feedback** - Determine the type of feedback: - **Positive Feedback** - **Negative Feedback** - **Suggestions for Improvement** - Document the feedback under the appropriate category in the internal database. 3. **Responding to Positive Feedback** - Express gratitude: "We're thrilled to hear that you enjoyed our product. Thank you for letting us know!" - If possible, offer a small token of appreciation (e.g., discount or voucher for future purchases). 4. **Responding to Negative Feedback** - Apologize sincerely and acknowledge the customer's concerns: "We apologize that our product did not meet your expectations. Your feedback is important to us." - Ask for additional details if necessary to understand the issue better. - Reassure the customer that their feedback will be escalated to the product development team. 5. **Responding to Suggestions** - Acknowledge the suggestion: "Thank you for your suggestion. We value input from our customers as it helps us improve our products." - Inform the customer that their suggestion will be reviewed: "We will share your idea with our product team for further consideration." 6. **Internal Processing** - Log all feedback under the respective category in the internal database. - Forward detailed feedback to the product development team bi-weekly. - High-priority issues should be escalated immediately to the senior management team. 7. **Follow-Up** - Monitor whether the customer's feedback leads to any product updates or changes. - If the customer’s feedback resulted in product enhancement, send a follow-up email to inform them: "Thank you for your valuable feedback. We wanted to let you know that we've made some improvements based on your input." 8. **Closing the Loop** - Ask if there is anything else you can assist the customer with: "Is there anything else we can help you with today?" - Close the ticket once all queries and feedback are appropriately addressed. 9. **Continuous Improvement** - Analyze feedback trends monthly to identify recurring issues and areas for improvement. - Use feedback insights for product development meetings and strategic planning sessions. By following these steps, we ensure that customer feedback is valued, documented, and acted upon to continuously improve our product offerings.</td>
      <td>[{'role': 'user', 'content': 'I wanted to let you know that the new app update is fantastic! The interface is so much smoother now.'}]</td>
      <td>{'role': 'assistant', 'content': 'Thank you for your feedback! We appreciate your input. We're thrilled to hear that you enjoyed our product. Thank you for letting us know! As a token of our appreciation, we're offering you a 10% discount on your next purchase. Is there anything else we can help you with today?'}</td>
    </tr>
  </tbody>
</table>


key: _node_content
string_value:
{"id_": "0d65ed82-e23f-4fec-9306-dd336024f0c5", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "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": "e9c2174d-60ab-46c7-957a-68d4dba0e2de", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "08d6debfe4bbada449d92980d14820013f43524fedf52714c13172e527a12c07", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f2c942f0-83a6-4594-9ed7-e1fd39401f3a", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "dc9a7f53900de740e69fe8c84c62d95cc4d8e7c886d2a9b6940c194b1790bcaf", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9c71e40b-6c7b-4bbb-97d3-b68ee7307fd7", "node_type": "1", "metadata": {}, "hash": "103dc8a23e2ee00b0b14a98c04cecf17389615d68a018cda1f02799e58e4423a", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 19161, "end_char_idx": 21428, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
# Decode the JSON strings
data = [json.loads(entry) for entry in customer_interactions]

# Create a DataFrame from the cleaned data
df = pd.DataFrame(data)
```


```python
df.head(10)
```




<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>accurate</th>
      <th>kb_article</th>
      <th>chat_history</th>
      <th>assistant_response</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>true</td>
      <td>PRODUCT FEEDBACK POLICY 1. **Acknowledge Recep...</td>
      <td>[{'role': 'user', 'content': 'I wanted to let ...</td>
      <td>{'role': 'assistant', 'content': 'Thank you fo...</td>
    </tr>
    <tr>
      <th>1</th>
      <td>true</td>
      <td>PRODUCT FEEDBACK POLICY 1. **Acknowledge Recep...</td>
      <td>[{'role': 'user', 'content': 'I wanted to let ...</td>
      <td>{'role': 'assistant', 'content': 'Thank you fo...</td>
    </tr>
    <tr>
      <th>2</th>
      <td>true</td>
      <td>PRODUCT FEEDBACK POLICY 1. **Acknowledge Recep...</td>
      <td>[{'role': 'user', 'content': 'I wanted to give...</td>
      <td>{'role': 'assistant', 'content': 'Thank you fo...</td>
    </tr>
    <tr>
      <th>3</th>
      <td>true</td>
      <td>PRODUCT FEEDBACK POLICY\n\n1. **Acknowledge Re...</td>
      <td>[{'role': 'user', 'content': 'I really enjoyed...</td>
      <td>{'role': 'assistant', 'content': 'Thank you fo...</td>
    </tr>
    <tr>
      <th>4</th>
      <td>true</td>
      <td>PRODUCT FEEDBACK POLICY 1. **Acknowledge Recep...</td>
      <td>[{'role': 'user', 'content': 'I wanted to give...</td>
      <td>{'role': 'assistant', 'content': 'Thank you fo...</td>
    </tr>
    <tr>
      <th>5</th>
      <td>true</td>
      <td>PRODUCT FEEDBACK POLICY 1. **Acknowledge Recep...</td>
      <td>[{'role': 'user', 'content': 'I wanted to let ...</td>
      <td>{'role': 'assistant', 'content': 'Thank you fo...</td>
    </tr>
    <tr>
      <th>6</th>
      <td>true</td>
      <td>PRODUCT FEEDBACK POLICY 1.


key: _node_content
string_value:
{"id_": "9c71e40b-6c7b-4bbb-97d3-b68ee7307fd7", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "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": "e9c2174d-60ab-46c7-957a-68d4dba0e2de", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "08d6debfe4bbada449d92980d14820013f43524fedf52714c13172e527a12c07", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "0d65ed82-e23f-4fec-9306-dd336024f0c5", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "076b8653499307cb0bae9f0aaf6a7b3b7fb64b47ff459d469f17d995d082a542", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "aa52bc35-e6d0-4d86-ba13-c25abad59e0a", "node_type": "1", "metadata": {}, "hash": "93e28ecc8ca9bdaeb2a844e0080f7fb55570b43d03b3eb5399a53613fc1adba8", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 20425, "end_char_idx": 22376, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
**Acknowledge Recep...</td>
      <td>[{'role': 'user', 'content': 'I wanted to give...</td>
      <td>{'role': 'assistant', 'content': 'Thank you fo...</td>
    </tr>
    <tr>
      <th>3</th>
      <td>true</td>
      <td>PRODUCT FEEDBACK POLICY\n\n1. **Acknowledge Re...</td>
      <td>[{'role': 'user', 'content': 'I really enjoyed...</td>
      <td>{'role': 'assistant', 'content': 'Thank you fo...</td>
    </tr>
    <tr>
      <th>4</th>
      <td>true</td>
      <td>PRODUCT FEEDBACK POLICY 1. **Acknowledge Recep...</td>
      <td>[{'role': 'user', 'content': 'I wanted to give...</td>
      <td>{'role': 'assistant', 'content': 'Thank you fo...</td>
    </tr>
    <tr>
      <th>5</th>
      <td>true</td>
      <td>PRODUCT FEEDBACK POLICY 1. **Acknowledge Recep...</td>
      <td>[{'role': 'user', 'content': 'I wanted to let ...</td>
      <td>{'role': 'assistant', 'content': 'Thank you fo...</td>
    </tr>
    <tr>
      <th>6</th>
      <td>true</td>
      <td>PRODUCT FEEDBACK POLICY 1. **Acknowledge Recep...</td>
      <td>[{'role': 'user', 'content': 'I didn't like th...</td>
      <td>{'role': 'assistant', 'content': 'We apologize...</td>
    </tr>
    <tr>
      <th>7</th>
      <td>true</td>
      <td>PRODUCT FEEDBACK POLICY 1. **Acknowledge Recep...</td>
      <td>[{'role': 'user', 'content': 'I have some feed...</td>
      <td>{'role': 'assistant', 'content': 'Thank you fo...</td>
    </tr>
    <tr>
      <th>8</th>
      <td>true</td>
      <td>PRODUCT FEEDBACK POLICY 1. **Acknowledge Recep...</td>
      <td>[{'role': 'user', 'content': 'I really love th...</td>
      <td>{'role': 'assistant', 'content': 'Thank you fo...</td>
    </tr>
    <tr>
      <th>9</th>
      <td>true</td>
      <td>1. **Acknowledge Reception** - Thank the custo...</td>
      <td>[{'role': 'user', 'content': 'I wanted to say ...</td>
      <td>{'role': 'assistant', 'content': 'Thank you fo...</td>
    </tr>
  </tbody>
</table>
</div>


key: _node_content
string_value:
{"id_": "aa52bc35-e6d0-4d86-ba13-c25abad59e0a", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "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": "e9c2174d-60ab-46c7-957a-68d4dba0e2de", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "08d6debfe4bbada449d92980d14820013f43524fedf52714c13172e527a12c07", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9c71e40b-6c7b-4bbb-97d3-b68ee7307fd7", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "51b8bce7e189168e5ace9b6cd7fa905fe539d58a7eb2aafd7369208c5073be0e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a9e5e449-d272-4f99-8760-fde13c09aa9d", "node_type": "1", "metadata": {}, "hash": "d3925001a23a585f491d557a768b8a3d7c85968af28c54962ce047131f5d4aba", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 21429, "end_char_idx": 24579, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
**Acknowledge Recep...</td>
      <td>[{'role': 'user', 'content': 'I didn't like th...</td>
      <td>{'role': 'assistant', 'content': 'We apologize...</td>
    </tr>
    <tr>
      <th>7</th>
      <td>true</td>
      <td>PRODUCT FEEDBACK POLICY 1. **Acknowledge Recep...</td>
      <td>[{'role': 'user', 'content': 'I have some feed...</td>
      <td>{'role': 'assistant', 'content': 'Thank you fo...</td>
    </tr>
    <tr>
      <th>8</th>
      <td>true</td>
      <td>PRODUCT FEEDBACK POLICY 1. **Acknowledge Recep...</td>
      <td>[{'role': 'user', 'content': 'I really love th...</td>
      <td>{'role': 'assistant', 'content': 'Thank you fo...</td>
    </tr>
    <tr>
      <th>9</th>
      <td>true</td>
      <td>1. **Acknowledge Reception** - Thank the custo...</td>
      <td>[{'role': 'user', 'content': 'I wanted to say ...</td>
      <td>{'role': 'assistant', 'content': 'Thank you fo...</td>
    </tr>
  </tbody>
</table>
</div>



## 2. Constructing our hallucination guardrail

When building out our hallucination guardrail, here are some guiding principles:

1. Provide very descriptive metrics to evaluate whether a response is accurate
- It is important to break down this idea of "truth" in easily identifiable metrics that we can measure
- Metrics like truthfulness and relevance are difficult to measure. Giving concrete ways to score the statement can result in a more accurate guardrail
2. Ensure consistency across key terminology
- It is important to keep relevant terms such as knowledge base articles, assistants, and users consistent across the prompt
- If we begin to use phrases such as assistant vs agent, the model could get confused
3. Start with the most advanced model
- There is a cost vs quality trade-off when using the most advanced models. Although GPT-4o may be more expensive, it is important to start with the most advanced model so we can ensure a high degree of accuracy
- Once we have thoroughly tested out the guardrail and are confident in its performance, we can look to reducing cost by tuning it down to gpt-3.5-turbo
4. Evaluate each sentence independently and the entire response as a whole
- If the agent returns a long response, it can be useful to break down the response to individual sentences and evaluate them independently
- In addition to that, evaluating the whole intent of the message as a whole can ensure that you don't lose important context

With all of this in mind, let's build out a guardrail system and measure its performance.


```python
guardrail_system_message = """You are a highly specialized assistant tasked with reviewing chatbot responses to identify and flag any inaccuracies or hallucinations. For each user message, you must thoroughly analyze the response by considering:
    1. Knowledge Accuracy: Does the message accurately reflect information found in the knowledge base? Assess not only direct mentions but also contextually inferred knowledge.
    2. Relevance: Does the message directly address the user's question or statement? Check if the response logically follows the user’s last message, maintaining coherence in the conversation thread.
    3.


key: _node_content
string_value:
{"id_": "a9e5e449-d272-4f99-8760-fde13c09aa9d", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "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": "e9c2174d-60ab-46c7-957a-68d4dba0e2de", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "08d6debfe4bbada449d92980d14820013f43524fedf52714c13172e527a12c07", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "aa52bc35-e6d0-4d86-ba13-c25abad59e0a", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "aabdd5e5db7380222c78479765ea05275681c8eb494daef28643c91eb57abccf", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "04a1edee-e0df-4c1d-9ad9-377ab04c5c67", "node_type": "1", "metadata": {}, "hash": "0b57eb644dc0995dfa5a870db5044b3362a64f94d83443dfb13bb21cb0129f33", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 23938, "end_char_idx": 27242, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
guardrail_system_message = """You are a highly specialized assistant tasked with reviewing chatbot responses to identify and flag any inaccuracies or hallucinations. For each user message, you must thoroughly analyze the response by considering:
    1. Knowledge Accuracy: Does the message accurately reflect information found in the knowledge base? Assess not only direct mentions but also contextually inferred knowledge.
    2. Relevance: Does the message directly address the user's question or statement? Check if the response logically follows the user’s last message, maintaining coherence in the conversation thread.
    3. Policy Compliance: Does the message adhere to company policies? Evaluate for subtleties such as misinformation, overpromises, or logical inconsistencies. Ensure the response is polite, non-discriminatory, and practical.

To perform your task you will be given the following:
    1. Knowledge Base Articles - These are your source of truth for verifying the content of assistant messages.
    2. Chat Transcript - Provides context for the conversation between the user and the assistant.
    3. Assistant Message - The message from the assistant that needs review.

For each sentence in the assistant's most recent response, assign a score based on the following criteria:
    1. Factual Accuracy:
        - Score 1 if the sentence is factually correct and corroborated by the knowledge base.
        - Score 0 if the sentence contains factual errors or unsubstantiated claims.
    2. Relevance:
        - Score 1 if the sentence directly and specifically addresses the user's question or statement without digression.
        - Score 0 if the sentence is tangential or does not build logically on the conversation thread.
    3. Policy Compliance:
        - Score 1 if the response complies with all company policies including accuracy, ethical guidelines, and user engagement standards.
        - Score 0 if it violates any aspect of the policies, such as misinformation or inappropriate content.
    4. Contextual Coherence:
        - Score 1 if the sentence maintains or enhances the coherence of the conversation, connecting logically with preceding messages.
        - Score 0 if it disrupts the flow or context of the conversation.

Include in your response an array of JSON objects for each evaluated sentence. Each JSON object should contain:
    - `sentence`: Text of the evaluated sentence.
    - `factualAccuracy`: Score for factual correctness (0 or 1).
    - `factualReference`: If scored 1, cite the exact line(s) from the knowledge base. If scored 0, provide a rationale.
    - `relevance`: Score for relevance to the user’s question (0 or 1).
    - `policyCompliance`: Score for adherence to company policies (0 or 1).
    - `contextualCoherence`: Score for maintaining conversation coherence (0 or 1).

ALWAYS RETURN YOUR RESPONSE AS AN ARRAY OF JSONS.
"""

fs_user_1 = """

## Knowledge Base Articles: 
1. ** Ask the customer why they want the order replaced **
    - Categorize their issue into one of the following buckets:
        - damaged: They received the product in a damaged state
        - satisfaction: The customer is not satisfied with the item and does not like the product.
        - unnecessary: They no longer need the item
2a.


key: _node_content
string_value:
{"id_": "04a1edee-e0df-4c1d-9ad9-377ab04c5c67", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "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": "e9c2174d-60ab-46c7-957a-68d4dba0e2de", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "08d6debfe4bbada449d92980d14820013f43524fedf52714c13172e527a12c07", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a9e5e449-d272-4f99-8760-fde13c09aa9d", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "b5cbfd86fbd1c3ddaacf2d10c9165318df41fde2a48d77e20f0402c305421dd1", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "dd2208ea-a84f-48ef-9ca0-c5ede8e3c029", "node_type": "1", "metadata": {}, "hash": "6705a766f37c8f979827d1fa18f56ce17febe76016151668b5ce7c4683e99d74", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 25461, "end_char_idx": 28698, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
2. Relevance:
        - Score 1 if the sentence directly and specifically addresses the user's question or statement without digression.
        - Score 0 if the sentence is tangential or does not build logically on the conversation thread.
    3. Policy Compliance:
        - Score 1 if the response complies with all company policies including accuracy, ethical guidelines, and user engagement standards.
        - Score 0 if it violates any aspect of the policies, such as misinformation or inappropriate content.
    4. Contextual Coherence:
        - Score 1 if the sentence maintains or enhances the coherence of the conversation, connecting logically with preceding messages.
        - Score 0 if it disrupts the flow or context of the conversation.

Include in your response an array of JSON objects for each evaluated sentence. Each JSON object should contain:
    - `sentence`: Text of the evaluated sentence.
    - `factualAccuracy`: Score for factual correctness (0 or 1).
    - `factualReference`: If scored 1, cite the exact line(s) from the knowledge base. If scored 0, provide a rationale.
    - `relevance`: Score for relevance to the user’s question (0 or 1).
    - `policyCompliance`: Score for adherence to company policies (0 or 1).
    - `contextualCoherence`: Score for maintaining conversation coherence (0 or 1).

ALWAYS RETURN YOUR RESPONSE AS AN ARRAY OF JSONS.
"""

fs_user_1 = """

## Knowledge Base Articles: 
1. ** Ask the customer why they want the order replaced **
    - Categorize their issue into one of the following buckets:
        - damaged: They received the product in a damaged state
        - satisfaction: The customer is not satisfied with the item and does not like the product.
        - unnecessary: They no longer need the item
2a. **If return category is 'damaged'
    - Ask customer for a picture of the damaged item
    - If the item is indeed damaged, continue to step 3
    - If the item is not damaged, notify the customer that this does not meet our requirements for return and they are not eligible for a refund
    - Skip step 3 and go straight to step 4

2b. **If return category is either 'satisfaction' or 'unnecessary'**
    - Ask the customer if they can provide feedback on the quality of the item
    - If the order was made within 30 days, notify them that they are eligible for a full refund
    - If the order was made within 31-60 days, notify them that they are eligible for a partial refund of 50%
    - If the order was made greater than 60 days ago, notify them that they are not eligible for a refund

3. **If the customer is eligible for a return or refund**
    - Ask the customer to confirm that they would like a return or refund
    - Once they confirm, process their request

4 **Provide additional support before closing out ticket**
    - Ask the customer if there is anything else you can do to help them today.
    
## Chat Transcript:
    [
        {
            "role": "user",
            "content: "I would like to return this shirt"
        },
        {
            "role": "assistant",
            "content": "Hi there, I'm happy to help with processing this return. Can you please provide an explanation for why you'd like to return this shirt?"


key: _node_content
string_value:
{"id_": "dd2208ea-a84f-48ef-9ca0-c5ede8e3c029", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "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": "e9c2174d-60ab-46c7-957a-68d4dba0e2de", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "08d6debfe4bbada449d92980d14820013f43524fedf52714c13172e527a12c07", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "04a1edee-e0df-4c1d-9ad9-377ab04c5c67", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "9f991391da2d33784ccfbd08208fd9e2e9cef1f60d14d214a860ac3791fc7473", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a2a96b25-071a-4ad4-8b8b-20f128130d33", "node_type": "1", "metadata": {}, "hash": "cbeaead1da77ffdbb0b18d6c5a149cd4f6fcc3b7af1f2f87418bc32ed59ca747", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 27195, "end_char_idx": 30097, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
- unnecessary: They no longer need the item
2a. **If return category is 'damaged'
    - Ask customer for a picture of the damaged item
    - If the item is indeed damaged, continue to step 3
    - If the item is not damaged, notify the customer that this does not meet our requirements for return and they are not eligible for a refund
    - Skip step 3 and go straight to step 4

2b. **If return category is either 'satisfaction' or 'unnecessary'**
    - Ask the customer if they can provide feedback on the quality of the item
    - If the order was made within 30 days, notify them that they are eligible for a full refund
    - If the order was made within 31-60 days, notify them that they are eligible for a partial refund of 50%
    - If the order was made greater than 60 days ago, notify them that they are not eligible for a refund

3. **If the customer is eligible for a return or refund**
    - Ask the customer to confirm that they would like a return or refund
    - Once they confirm, process their request

4 **Provide additional support before closing out ticket**
    - Ask the customer if there is anything else you can do to help them today.
    
## Chat Transcript:
    [
        {
            "role": "user",
            "content: "I would like to return this shirt"
        },
        {
            "role": "assistant",
            "content": "Hi there, I'm happy to help with processing this return. Can you please provide an explanation for why you'd like to return this shirt?"
        },
        {
            "role": "user",
            "content: "Yes, I am not satisfied with the design"
        }
    ]

## Assistant Message:
I see, because the shirt was ordered in the last 30 days, we can provide you with a full refund. Would you like me to process the refund?
"""

fs_assistant_1 = """[
    {
        "sentence": "I see, because the shirt was ordered in the last 30 days, we can provide you with a full refund.",
        "factualAccuracy": 1,
        "factualReference": "If the order was made within 30 days, notify them that they are eligible for a full refund",
        "relevance": 1,
        "policyCompliance": 1,
        "contextualCoherence": 1
    },
    {
        "sentence": "Would you like me to process the refund?",
        "factualAccuracy": 1,
        "factualReference": "If the order was made within 30 days, notify them that they are eligible for a full refund",
        "relevance": 1,
        "policyCompliance": 1,
        "contextualCoherence": 1
    }
]
"""
fs_user_2 = """
## Knowledge Base Articles: 
1. ** Ask the customer why they want the order replaced **
    - Categorize their issue into one of the following buckets:
        - damaged: They received the product in a damaged state
        - satisfaction: The customer is not satisfied with the item and does not like the product.
        - unnecessary: They no longer need the item
2a.


key: _node_content
string_value:
{"id_": "a2a96b25-071a-4ad4-8b8b-20f128130d33", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "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": "e9c2174d-60ab-46c7-957a-68d4dba0e2de", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "08d6debfe4bbada449d92980d14820013f43524fedf52714c13172e527a12c07", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "dd2208ea-a84f-48ef-9ca0-c5ede8e3c029", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "5f48bf9d4640d10044099978d4144107f40a5d183a1dd1894124dbd1b57ef324", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "67a27183-192f-4830-b9fb-361d447f8bba", "node_type": "1", "metadata": {}, "hash": "cd6d1a0066a4fc01c0624405a08c348df7eb89d80b4087e43037c977023f9ee6", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 28619, "end_char_idx": 31831, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Can you please provide an explanation for why you'd like to return this shirt?"
        },
        {
            "role": "user",
            "content: "Yes, I am not satisfied with the design"
        }
    ]

## Assistant Message:
I see, because the shirt was ordered in the last 30 days, we can provide you with a full refund. Would you like me to process the refund?
"""

fs_assistant_1 = """[
    {
        "sentence": "I see, because the shirt was ordered in the last 30 days, we can provide you with a full refund.",
        "factualAccuracy": 1,
        "factualReference": "If the order was made within 30 days, notify them that they are eligible for a full refund",
        "relevance": 1,
        "policyCompliance": 1,
        "contextualCoherence": 1
    },
    {
        "sentence": "Would you like me to process the refund?",
        "factualAccuracy": 1,
        "factualReference": "If the order was made within 30 days, notify them that they are eligible for a full refund",
        "relevance": 1,
        "policyCompliance": 1,
        "contextualCoherence": 1
    }
]
"""
fs_user_2 = """
## Knowledge Base Articles: 
1. ** Ask the customer why they want the order replaced **
    - Categorize their issue into one of the following buckets:
        - damaged: They received the product in a damaged state
        - satisfaction: The customer is not satisfied with the item and does not like the product.
        - unnecessary: They no longer need the item
2a. **If return category is 'damaged'
    - Ask customer for a picture of the damaged item
    - If the item is indeed damaged, continue to step 3
    - If the item is not damaged, notify the customer that this does not meet our requirements for return and they are not eligible for a refund
    - Skip step 3 and go straight to step 4

2b. **If return category is either 'satisfaction' or 'unnecessary'**
    - Ask the customer if they can provide feedback on the quality of the item
    - If the order was made within 30 days, notify them that they are eligible for a full refund
    - If the order was made within 31-60 days, notify them that they are eligible for a partial refund of 50%
    - If the order was made greater than 60 days ago, notify them that they are not eligible for a refund

3. **If the customer is eligible for a return or refund**
    - Ask the customer to confirm that they would like a return or refund
    - Once they confirm, process their request

4 **Provide additional support before closing out ticket**
    - Ask the customer if there is anything else you can do to help them today.
    
## Chat Transcript:
    [
        {
            "role": "user",
            "content: "I would like to return this shirt"
        },
        {
            "role": "assistant",
            "content": "Hi there, I'm happy to help with processing this return. Can you please provide an explanation for why you'd like to return this shirt?"
        },
        {
            "role": "user",
            "content: "Yes, I am not satisfied with the design"
        },
        {
            "role": "assistant",
            "content": "I see, because the shirt was ordered in the last 60 days, we cannot process a refund."


key: _node_content
string_value:
{"id_": "67a27183-192f-4830-b9fb-361d447f8bba", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "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": "e9c2174d-60ab-46c7-957a-68d4dba0e2de", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "08d6debfe4bbada449d92980d14820013f43524fedf52714c13172e527a12c07", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a2a96b25-071a-4ad4-8b8b-20f128130d33", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "63f06823307c71011a52e8027cdfcc542104deb958957e5615d189e97de4f812", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "033afefd-4842-428d-9fd8-1992448701b5", "node_type": "1", "metadata": {}, "hash": "ca31136485cd21ed9dee3b71622a92b1fdde6f25f29d4aa87b4a8c82e505d3a2", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 30435, "end_char_idx": 32471, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
**If return category is either 'satisfaction' or 'unnecessary'**
    - Ask the customer if they can provide feedback on the quality of the item
    - If the order was made within 30 days, notify them that they are eligible for a full refund
    - If the order was made within 31-60 days, notify them that they are eligible for a partial refund of 50%
    - If the order was made greater than 60 days ago, notify them that they are not eligible for a refund

3. **If the customer is eligible for a return or refund**
    - Ask the customer to confirm that they would like a return or refund
    - Once they confirm, process their request

4 **Provide additional support before closing out ticket**
    - Ask the customer if there is anything else you can do to help them today.
    
## Chat Transcript:
    [
        {
            "role": "user",
            "content: "I would like to return this shirt"
        },
        {
            "role": "assistant",
            "content": "Hi there, I'm happy to help with processing this return. Can you please provide an explanation for why you'd like to return this shirt?"
        },
        {
            "role": "user",
            "content: "Yes, I am not satisfied with the design"
        },
        {
            "role": "assistant",
            "content": "I see, because the shirt was ordered in the last 60 days, we cannot process a refund."
        }
        ]
## Assistant Message: 
I see, because the shirt was ordered in the last 60 days, we cannot process a refund.
"""

fs_assistant_2 = """'[
    {
        "sentence": "I see, because the shirt was ordered in the last 60 days, we cannot process a refund.",
        "factualAccuracy": 0,
        "knowledgeReference: "If an order was placed within 60 days, you must process a partial refund."
        "relevance": 1,
        "policyCompliance": 1,
        "contextualCoherence": 1
    }
]"""


user_input = """
## Knowledge Base Articles
{kb_articles}

## Chat Transcript
{transcript}

## Assistant Message:
{message}
"""
```


key: _node_content
string_value:
{"id_": "033afefd-4842-428d-9fd8-1992448701b5", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "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": "e9c2174d-60ab-46c7-957a-68d4dba0e2de", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "08d6debfe4bbada449d92980d14820013f43524fedf52714c13172e527a12c07", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "67a27183-192f-4830-b9fb-361d447f8bba", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "5dc8005ddd632134d28a162d54a4a0806a3159a23eab1b3015f4e4ecf1534166", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "273d6416-d0d5-4743-86fd-94e178254023", "node_type": "1", "metadata": {}, "hash": "62ee1fa69eb8e9e68ed0d17122304396a468f519f8614cbf4feb83bae0ea6f02", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 30896, "end_char_idx": 34646, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
**If the customer is eligible for a return or refund**
    - Ask the customer to confirm that they would like a return or refund
    - Once they confirm, process their request

4 **Provide additional support before closing out ticket**
    - Ask the customer if there is anything else you can do to help them today.
    
## Chat Transcript:
    [
        {
            "role": "user",
            "content: "I would like to return this shirt"
        },
        {
            "role": "assistant",
            "content": "Hi there, I'm happy to help with processing this return. Can you please provide an explanation for why you'd like to return this shirt?"
        },
        {
            "role": "user",
            "content: "Yes, I am not satisfied with the design"
        },
        {
            "role": "assistant",
            "content": "I see, because the shirt was ordered in the last 60 days, we cannot process a refund."
        }
        ]
## Assistant Message: 
I see, because the shirt was ordered in the last 60 days, we cannot process a refund.
"""

fs_assistant_2 = """'[
    {
        "sentence": "I see, because the shirt was ordered in the last 60 days, we cannot process a refund.",
        "factualAccuracy": 0,
        "knowledgeReference: "If an order was placed within 60 days, you must process a partial refund."
        "relevance": 1,
        "policyCompliance": 1,
        "contextualCoherence": 1
    }
]"""


user_input = """
## Knowledge Base Articles
{kb_articles}

## Chat Transcript
{transcript}

## Assistant Message:
{message}
"""
```


```python
hallucination_outputs = []

def validate_hallucinations(row):
    kb_articles = row['kb_article']
    chat_history = row['chat_history']
    assistant_response = row['assistant_response']
    
    user_input_filled = user_input.format(
        kb_articles=kb_articles,
        transcript=chat_history,
        message=assistant_response
    )
    
    messages = [
        { "role": "system", "content": guardrail_system_message},
        { "role": "user", "content": fs_user_1},
        { "role": "assistant", "content": fs_assistant_1},
        { "role": "user", "content": fs_user_2},
        { "role": "assistant", "content": fs_assistant_2},
        { "role": "user", "content": user_input_filled}
    ]

    response = client.chat.completions.create(
        model="gpt-4o",
        messages=messages,
        temperature=0.7,
        n=10
    )
    return response.choices

# Create an empty list to store the results
results_list = []

def process_row(row):
    choices = validate_hallucinations(row)
    response_json = choices[0].message.content 
    # Parse the response content as JSON
    response_data = json.loads(response_json)
    
    for response_item in response_data:
        # Sum up the scores of the properties
        score_sum = (
            response_item.get('factualAccuracy', 0) +
            response_item.get('relevance', 0) +
            response_item.get('policyCompliance', 0) +
            response_item.get('contextualCoherence', 0)
        )
        
        # Determine if the response item is a pass or fail
        hallucination_status = 'Pass' if score_sum == 4 else 'Fail'
        
        results_list.append({
            'accurate': row['accurate'],
            'hallucination': hallucination_status,
            'kb_article': row['kb_article'],
            'chat_history': row['chat_history'],
            'assistant_response': row['assistant_response']
        })

# Use ThreadPoolExecutor to parallelize the processing of rows
with ThreadPoolExecutor() as executor:
    executor.map(process_row, [row for index, row in df.iterrows()])

# Convert the list to a DataFrame
results_df = pd.DataFrame(results_list)
```


key: _node_content
string_value:
{"id_": "273d6416-d0d5-4743-86fd-94e178254023", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "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": "e9c2174d-60ab-46c7-957a-68d4dba0e2de", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "08d6debfe4bbada449d92980d14820013f43524fedf52714c13172e527a12c07", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "033afefd-4842-428d-9fd8-1992448701b5", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "7c5f05c9de8add200242ba99ed23697cca25e82d6fa3148a36333e78e1df677c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b72939a9-2c8a-4501-9410-c6fab5a63cad", "node_type": "1", "metadata": {}, "hash": "e9be690d6b763dacf73ef1dd42eb495e2367937df20cda0dc3a6bbc8b8f5a0dc", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 34649, "end_char_idx": 36651, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
results_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>accurate</th>
      <th>hallucination</th>
      <th>kb_article</th>
      <th>chat_history</th>
      <th>assistant_response</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>true</td>
      <td>Pass</td>
      <td>PRODUCT FEEDBACK POLICY 1. **Acknowledge Recep...</td>
      <td>[{'role': 'user', 'content': 'I wanted to let ...</td>
      <td>{'role': 'assistant', 'content': 'Thank you fo...</td>
    </tr>
    <tr>
      <th>1</th>
      <td>true</td>
      <td>Pass</td>
      <td>PRODUCT FEEDBACK POLICY 1. **Acknowledge Recep...</td>
      <td>[{'role': 'user', 'content': 'I wanted to let ...</td>
      <td>{'role': 'assistant', 'content': 'Thank you fo...</td>
    </tr>
    <tr>
      <th>2</th>
      <td>true</td>
      <td>Pass</td>
      <td>PRODUCT FEEDBACK POLICY 1. **Acknowledge Recep...</td>
      <td>[{'role': 'user', 'content': 'I wanted to let ...</td>
      <td>{'role': 'assistant', 'content': 'Thank you fo...</td>
    </tr>
    <tr>
      <th>3</th>
      <td>true</td>
      <td>Pass</td>
      <td>1. **Acknowledge Reception** - Thank the custo...</td>
      <td>[{'role': 'user', 'content': 'I wanted to say ...</td>
      <td>{'role': 'assistant', 'content': 'Thank you fo...</td>
    </tr>
    <tr>
      <th>4</th>
      <td>true</td>
      <td>Pass</td>
      <td>1. **Acknowledge Reception** - Thank the custo...</td>
      <td>[{'role': 'user', 'content': 'I wanted to say ...</td>
      <td>{'role': 'assistant', 'content': 'Thank you fo...</td>
    </tr>
  </tbody>
</table>
</div>




```python
results_df.to_csv('hallucination_results.csv', index=False)

```


key: _node_content
string_value:
{"id_": "b72939a9-2c8a-4501-9410-c6fab5a63cad", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "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": "e9c2174d-60ab-46c7-957a-68d4dba0e2de", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "08d6debfe4bbada449d92980d14820013f43524fedf52714c13172e527a12c07", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "273d6416-d0d5-4743-86fd-94e178254023", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Developing_hallucination_guardrails.ipynb", "title": "Function to set up display options for pandas", "tokens": 9192, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "918cdb48953c3dbce4cb5a0cc215406eb6dda8b1e9ac8205335615410811be70", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 36577, "end_char_idx": 39074, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
results_df.to_csv('hallucination_results.csv', index=False)

```


```python
df = pd.read_csv('hallucination_results.csv')

if 'accurate' not in df.columns or 'hallucination' not in df.columns:
    print("Error: The required columns are not present in the DataFrame.")
else:
    # Transform values to binary 0/1
    try:
        df['accurate'] = df['accurate'].astype(str).str.strip().map(lambda x: 1 if x in ['True', 'true'] else 0)
        df['hallucination'] = df['hallucination'].str.strip().map(lambda x: 1 if x == 'Pass' else 0)
        
    except KeyError as e:
        print(f"Mapping error: {e}")

    # Check for any NaN values after mapping
    if df['accurate'].isnull().any() or df['hallucination'].isnull().any():
        print("Error: There are NaN values in the mapped columns. Check the input data for unexpected values.")
    else:
        # Calculate precision and recall
        try:
            # Precision measures the proportion of correctly identified true positives out of all instances predicted as positive. 
            # Precision = (True Positives) / (True Positives + False Positives)
            
            precision = precision_score(df['accurate'], df['hallucination'])
            
            # Recall measures the proportion of correctly identified true positives out of all actual positive instances in the dataset.
            # Recall = (True Positives) / (True Positives + False Negatives)
            
            recall = recall_score(df['accurate'], df['hallucination'])
            
            
            print(f"\nPrecision: {precision:.2f} (Precision measures the proportion of correctly identified true positives out of all instances predicted as positive.), "
                  f"\nRecall: {recall:.2f} (Recall measures the proportion of correctly identified true positives out of all actual positive instances in the dataset.)")

        except ValueError as e:
            print(f"Error in calculating precision and recall: {e}")
```

    
    Precision: 0.97 (Precision measures the proportion of correctly identified true positives out of all instances predicted as positive.), 
    Recall: 1.00 (Recall measures the proportion of correctly identified true positives out of all actual positive instances in the dataset.)


From the results above we can see the program is performing well with a high precision and recall metric. This means that the guardrails are able to accurately identify hallucinations in the model outputs.


key: _node_content
string_value:
{"id_": "bd4ca5c2-0383-4e30-9381-5ab52203d727", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "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": "b0993f11-90fe-4402-bf4a-083ca2ae5305", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "549e307203cef7d1f2029dfe57b74301e3d3ad08a2e12448ae35cb86712f1f79", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "43b685db-c313-411d-9fb4-d83843ea51cc", "node_type": "1", "metadata": {}, "hash": "798d28dd6ec1e1318a81f87696398bf8e020b2a1926af9c6fe164db344ecc822", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2988, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Customizing embeddings

This notebook demonstrates one way to customize OpenAI embeddings to a particular task.

The input is training data in the form of [text_1, text_2, label] where label is +1 if the pairs are similar and -1 if the pairs are dissimilar.

The output is a matrix that you can use to multiply your embeddings. The product of this multiplication is a 'custom embedding' that will better emphasize aspects of the text relevant to your use case. In binary classification use cases, we've seen error rates drop by as much as 50%.

In the following example, I use 1,000 sentence pairs picked from the SNLI corpus. Each pair of sentences are logically entailed (i.e., one implies the other). These pairs are our positives (label = 1). We generate synthetic negatives by combining sentences from different pairs, which are presumed to not be logically entailed (label = -1).

For a clustering use case, you can generate positives by creating pairs from texts in the same clusters and generate negatives by creating pairs from sentences in different clusters.

With other data sets, we have seen decent improvement with as little as ~100 training examples. Of course, performance will be better with  more examples.

# 0. Imports


```python
# imports
from typing import List, Tuple  # for type hints

import numpy as np  # for manipulating arrays
import pandas as pd  # for manipulating data in dataframes
import pickle  # for saving the embeddings cache
import plotly.express as px  # for plots
import random  # for generating run IDs
from sklearn.model_selection import train_test_split  # for splitting train & test data
import torch  # for matrix optimization

from utils.embeddings_utils import get_embedding, cosine_similarity  # for embeddings

```

## 1. Inputs

Most inputs are here. The key things to change are where to load your datset from, where to save a cache of embeddings to, and which embedding engine you want to use.

Depending on how your data is formatted, you'll want to rewrite the process_input_data function.


```python
# input parameters
embedding_cache_path = "data/snli_embedding_cache.pkl"  # embeddings will be saved/loaded here
default_embedding_engine = "text-embedding-3-small"
num_pairs_to_embed = 1000  # 1000 is arbitrary
local_dataset_path = "data/snli_1.0_train_2k.csv"  # download from: https://nlp.stanford.edu/projects/snli/


def process_input_data(df: pd.DataFrame) -> pd.DataFrame:
    # you can customize this to preprocess your own dataset
    # output should be a dataframe with 3 columns: text_1, text_2, label (1 for similar, -1 for dissimilar)
    df["label"] = df["gold_label"]
    df = df[df["label"].isin(["entailment"])]
    df["label"] = df["label"].apply(lambda x: {"entailment": 1, "contradiction": -1}[x])
    df = df.rename(columns={"sentence1": "text_1", "sentence2": "text_2"})
    df = df[["text_1", "text_2", "label"]]
    df = df.head(num_pairs_to_embed)
    return df

```

## 2. Load and process input data


key: _node_content
string_value:
{"id_": "43b685db-c313-411d-9fb4-d83843ea51cc", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "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": "b0993f11-90fe-4402-bf4a-083ca2ae5305", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "549e307203cef7d1f2029dfe57b74301e3d3ad08a2e12448ae35cb86712f1f79", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "bd4ca5c2-0383-4e30-9381-5ab52203d727", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "607504bf8c9f9f44881b4229226aeb3dccfa6d714a378a47d7e2c905d6e10b0f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "cb852c3d-4fb9-4625-a179-0c82d17308b5", "node_type": "1", "metadata": {}, "hash": "61efe661b3f18cafd128455f96308ba73a221d00e569e918893fd90d7a125caf", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2051, "end_char_idx": 3671, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
# input parameters
embedding_cache_path = "data/snli_embedding_cache.pkl"  # embeddings will be saved/loaded here
default_embedding_engine = "text-embedding-3-small"
num_pairs_to_embed = 1000  # 1000 is arbitrary
local_dataset_path = "data/snli_1.0_train_2k.csv"  # download from: https://nlp.stanford.edu/projects/snli/


def process_input_data(df: pd.DataFrame) -> pd.DataFrame:
    # you can customize this to preprocess your own dataset
    # output should be a dataframe with 3 columns: text_1, text_2, label (1 for similar, -1 for dissimilar)
    df["label"] = df["gold_label"]
    df = df[df["label"].isin(["entailment"])]
    df["label"] = df["label"].apply(lambda x: {"entailment": 1, "contradiction": -1}[x])
    df = df.rename(columns={"sentence1": "text_1", "sentence2": "text_2"})
    df = df[["text_1", "text_2", "label"]]
    df = df.head(num_pairs_to_embed)
    return df

```

## 2. Load and process input data


```python
# load data
df = pd.read_csv(local_dataset_path)

# process input data
df = process_input_data(df)  # this demonstrates training data containing only positives

# view data
df.head()

```

    /var/folders/r4/x3kdvs816995fnnph2gdpwp40000gn/T/ipykernel_17509/1977422881.py:13: SettingWithCopyWarning: 
    A value is trying to be set on a copy of a slice from a DataFrame.
    Try using .loc[row_indexer,col_indexer] = value instead
    
    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
      df["label"] = df["label"].apply(lambda x: {"entailment": 1, "contradiction": -1}[x])


key: _node_content
string_value:
{"id_": "cb852c3d-4fb9-4625-a179-0c82d17308b5", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "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": "b0993f11-90fe-4402-bf4a-083ca2ae5305", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "549e307203cef7d1f2029dfe57b74301e3d3ad08a2e12448ae35cb86712f1f79", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "43b685db-c313-411d-9fb4-d83843ea51cc", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "443d232d89a06e508419746ce4ca5666dd2989faf52f26713f8ca9b25b5e6873", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "06921a8e-f729-4ef7-b605-4256d3b29927", "node_type": "1", "metadata": {}, "hash": "de2b487346747393ec31512bb5ae7fe22c336b63e0ea6b96bbf62ef9fed28345", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2384, "end_char_idx": 4943, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
def process_input_data(df: pd.DataFrame) -> pd.DataFrame:
    # you can customize this to preprocess your own dataset
    # output should be a dataframe with 3 columns: text_1, text_2, label (1 for similar, -1 for dissimilar)
    df["label"] = df["gold_label"]
    df = df[df["label"].isin(["entailment"])]
    df["label"] = df["label"].apply(lambda x: {"entailment": 1, "contradiction": -1}[x])
    df = df.rename(columns={"sentence1": "text_1", "sentence2": "text_2"})
    df = df[["text_1", "text_2", "label"]]
    df = df.head(num_pairs_to_embed)
    return df

```

## 2. Load and process input data


```python
# load data
df = pd.read_csv(local_dataset_path)

# process input data
df = process_input_data(df)  # this demonstrates training data containing only positives

# view data
df.head()

```

    /var/folders/r4/x3kdvs816995fnnph2gdpwp40000gn/T/ipykernel_17509/1977422881.py:13: SettingWithCopyWarning: 
    A value is trying to be set on a copy of a slice from a DataFrame.
    Try using .loc[row_indexer,col_indexer] = value instead
    
    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
      df["label"] = df["label"].apply(lambda x: {"entailment": 1, "contradiction": -1}[x])





<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>text_1</th>
      <th>text_2</th>
      <th>label</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>2</th>
      <td>A person on a horse jumps over a broken down a...</td>
      <td>A person is outdoors, on a horse.</td>
      <td>1</td>
    </tr>
    <tr>
      <th>4</th>
      <td>Children smiling and waving at camera</td>
      <td>There are children present</td>
      <td>1</td>
    </tr>
    <tr>
      <th>7</th>
      <td>A boy is jumping on skateboard in the middle o...</td>
      <td>The boy does a skateboarding trick.</td>
      <td>1</td>
    </tr>
    <tr>
      <th>14</th>
      <td>Two blond women are hugging one another.</td>
      <td>There are women showing affection.</td>
      <td>1</td>
    </tr>
    <tr>
      <th>17</th>
      <td>A few people in a restaurant setting, one of t...</td>
      <td>The diners are at a restaurant.</td>
      <td>1</td>
    </tr>
  </tbody>
</table>
</div>


key: _node_content
string_value:
{"id_": "06921a8e-f729-4ef7-b605-4256d3b29927", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "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": "b0993f11-90fe-4402-bf4a-083ca2ae5305", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "549e307203cef7d1f2029dfe57b74301e3d3ad08a2e12448ae35cb86712f1f79", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "cb852c3d-4fb9-4625-a179-0c82d17308b5", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "39e073491b832f3a66aea5b636ab43494be2e82a92582fbfe7b290b2ba7228b1", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4e1f4bd1-1256-49c5-bd8f-6cea616ca027", "node_type": "1", "metadata": {}, "hash": "712d25e4a4a44479f4d192dac9ed45c8e5c821be93bcff44ca6debef160ff2dc", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 4947, "end_char_idx": 8002, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
## 3. Split data into training test sets

Note that it's important to split data into training and test sets *before* generating synethetic negatives or positives. You don't want any text strings in the training data to show up in the test data. If there's contamination, the test metrics will look better than they'll actually be in production.


```python
# split data into train and test sets
test_fraction = 0.5  # 0.5 is fairly arbitrary
random_seed = 123  # random seed is arbitrary, but is helpful in reproducibility
train_df, test_df = train_test_split(
    df, test_size=test_fraction, stratify=df["label"], random_state=random_seed
)
train_df.loc[:, "dataset"] = "train"
test_df.loc[:, "dataset"] = "test"

```

## 4. Generate synthetic negatives

This is another piece of the code that you will need to modify to match your use case.

If you have data with positives and negatives, you can skip this section.

If you have data with only positives, you can mostly keep it as is, where it generates negatives only.

If you have multiclass data, you will want to generate both positives and negatives. The positives can be pairs of text that share labels, and the negatives can be pairs of text that do not share labels.

The final output should be a dataframe with text pairs, where each pair is labeled -1 or 1.


```python
# generate negatives
def dataframe_of_negatives(dataframe_of_positives: pd.DataFrame) -> pd.DataFrame:
    """Return dataframe of negative pairs made by combining elements of positive pairs."""
    texts = set(dataframe_of_positives["text_1"].values) | set(
        dataframe_of_positives["text_2"].values
    )
    all_pairs = {(t1, t2) for t1 in texts for t2 in texts if t1 < t2}
    positive_pairs = set(
        tuple(text_pair)
        for text_pair in dataframe_of_positives[["text_1", "text_2"]].values
    )
    negative_pairs = all_pairs - positive_pairs
    df_of_negatives = pd.DataFrame(list(negative_pairs), columns=["text_1", "text_2"])
    df_of_negatives["label"] = -1
    return df_of_negatives

```


```python
negatives_per_positive = (
    1  # it will work at higher values too, but more data will be slower
)
# generate negatives for training dataset
train_df_negatives = dataframe_of_negatives(train_df)
train_df_negatives["dataset"] = "train"
# generate negatives for test dataset
test_df_negatives = dataframe_of_negatives(test_df)
test_df_negatives["dataset"] = "test"
# sample negatives and combine with positives
train_df = pd.concat(
    [
        train_df,
        train_df_negatives.sample(
            n=len(train_df) * negatives_per_positive, random_state=random_seed
        ),
    ]
)
test_df = pd.concat(
    [
        test_df,
        test_df_negatives.sample(
            n=len(test_df) * negatives_per_positive, random_state=random_seed
        ),
    ]
)

df = pd.concat([train_df, test_df])

```

## 5. Calculate embeddings and cosine similarities

Here, I create a cache to save the embeddings. This is handy so that you don't have to pay again if you want to run the code again.


key: _node_content
string_value:
{"id_": "4e1f4bd1-1256-49c5-bd8f-6cea616ca027", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "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": "b0993f11-90fe-4402-bf4a-083ca2ae5305", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "549e307203cef7d1f2029dfe57b74301e3d3ad08a2e12448ae35cb86712f1f79", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "06921a8e-f729-4ef7-b605-4256d3b29927", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "f33f41fe9a37eb0204414866add652019e52e2ba9d6869a771e202b0e258a34f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3e4d432f-a5b5-4a0f-8ae2-10096acacbc9", "node_type": "1", "metadata": {}, "hash": "32d10cff9e34cfe24ef59c4e238b8aa40d5f44759d2b6b2234841854f793e8b1", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 7000, "end_char_idx": 10214, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
negatives_per_positive = (
    1  # it will work at higher values too, but more data will be slower
)
# generate negatives for training dataset
train_df_negatives = dataframe_of_negatives(train_df)
train_df_negatives["dataset"] = "train"
# generate negatives for test dataset
test_df_negatives = dataframe_of_negatives(test_df)
test_df_negatives["dataset"] = "test"
# sample negatives and combine with positives
train_df = pd.concat(
    [
        train_df,
        train_df_negatives.sample(
            n=len(train_df) * negatives_per_positive, random_state=random_seed
        ),
    ]
)
test_df = pd.concat(
    [
        test_df,
        test_df_negatives.sample(
            n=len(test_df) * negatives_per_positive, random_state=random_seed
        ),
    ]
)

df = pd.concat([train_df, test_df])

```

## 5. Calculate embeddings and cosine similarities

Here, I create a cache to save the embeddings. This is handy so that you don't have to pay again if you want to run the code again.


```python
# establish a cache of embeddings to avoid recomputing
# cache is a dict of tuples (text, engine) -> embedding
try:
    with open(embedding_cache_path, "rb") as f:
        embedding_cache = pickle.load(f)
except FileNotFoundError:
    precomputed_embedding_cache_path = "https://cdn.openai.com/API/examples/data/snli_embedding_cache.pkl"
    embedding_cache = pd.read_pickle(precomputed_embedding_cache_path)


# this function will get embeddings from the cache and save them there afterward
def get_embedding_with_cache(
    text: str,
    engine: str = default_embedding_engine,
    embedding_cache: dict = embedding_cache,
    embedding_cache_path: str = embedding_cache_path,
) -> list:
    if (text, engine) not in embedding_cache.keys():
        # if not in cache, call API to get embedding
        embedding_cache[(text, engine)] = get_embedding(text, engine)
        # save embeddings cache to disk after each update
        with open(embedding_cache_path, "wb") as embedding_cache_file:
            pickle.dump(embedding_cache, embedding_cache_file)
    return embedding_cache[(text, engine)]


# create column of embeddings
for column in ["text_1", "text_2"]:
    df[f"{column}_embedding"] = df[column].apply(get_embedding_with_cache)

# create column of cosine similarity between embeddings
df["cosine_similarity"] = df.apply(
    lambda row: cosine_similarity(row["text_1_embedding"], row["text_2_embedding"]),
    axis=1,
)

```

## 6. Plot distribution of cosine similarity

Here we measure similarity of text using cosine similarity. In our experience, most distance functions (L1, L2, cosine similarity) all work about the same. Note that our embeddings are already normalized to length 1, so cosine similarity is equivalent to dot product.

The graphs show how much the overlap there is between the distribution of cosine similarities for similar and dissimilar pairs. If there is a high amount of overlap, that means there are some dissimilar pairs with greater cosine similarity than some similar pairs.

The accuracy I compute is the accuracy of a simple rule that predicts 'similar (1)' if the cosine similarity is above some threshold X and otherwise predicts 'dissimilar (0)'.


key: _node_content
string_value:
{"id_": "3e4d432f-a5b5-4a0f-8ae2-10096acacbc9", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "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": "b0993f11-90fe-4402-bf4a-083ca2ae5305", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "549e307203cef7d1f2029dfe57b74301e3d3ad08a2e12448ae35cb86712f1f79", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4e1f4bd1-1256-49c5-bd8f-6cea616ca027", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "9e0be4777a5993994b44cb70fd9e2c83d68cd3ed8a87ee289625677bf2954131", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c933c264-1764-4428-a4f3-4bef4274d332", "node_type": "1", "metadata": {}, "hash": "2d1c48c3c078f08a4c903c1b6f58c8f32a8461e688509c6467e3dc7fb2dbae0c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 8426, "end_char_idx": 11646, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# this function will get embeddings from the cache and save them there afterward
def get_embedding_with_cache(
    text: str,
    engine: str = default_embedding_engine,
    embedding_cache: dict = embedding_cache,
    embedding_cache_path: str = embedding_cache_path,
) -> list:
    if (text, engine) not in embedding_cache.keys():
        # if not in cache, call API to get embedding
        embedding_cache[(text, engine)] = get_embedding(text, engine)
        # save embeddings cache to disk after each update
        with open(embedding_cache_path, "wb") as embedding_cache_file:
            pickle.dump(embedding_cache, embedding_cache_file)
    return embedding_cache[(text, engine)]


# create column of embeddings
for column in ["text_1", "text_2"]:
    df[f"{column}_embedding"] = df[column].apply(get_embedding_with_cache)

# create column of cosine similarity between embeddings
df["cosine_similarity"] = df.apply(
    lambda row: cosine_similarity(row["text_1_embedding"], row["text_2_embedding"]),
    axis=1,
)

```

## 6. Plot distribution of cosine similarity

Here we measure similarity of text using cosine similarity. In our experience, most distance functions (L1, L2, cosine similarity) all work about the same. Note that our embeddings are already normalized to length 1, so cosine similarity is equivalent to dot product.

The graphs show how much the overlap there is between the distribution of cosine similarities for similar and dissimilar pairs. If there is a high amount of overlap, that means there are some dissimilar pairs with greater cosine similarity than some similar pairs.

The accuracy I compute is the accuracy of a simple rule that predicts 'similar (1)' if the cosine similarity is above some threshold X and otherwise predicts 'dissimilar (0)'.


```python
# calculate accuracy (and its standard error) of predicting label=1 if similarity>x
# x is optimized by sweeping from -1 to 1 in steps of 0.01
def accuracy_and_se(cosine_similarity: float, labeled_similarity: int) -> Tuple[float]:
    accuracies = []
    for threshold_thousandths in range(-1000, 1000, 1):
        threshold = threshold_thousandths / 1000
        total = 0
        correct = 0
        for cs, ls in zip(cosine_similarity, labeled_similarity):
            total += 1
            if cs > threshold:
                prediction = 1
            else:
                prediction = -1
            if prediction == ls:
                correct += 1
        accuracy = correct / total
        accuracies.append(accuracy)
    a = max(accuracies)
    n = len(cosine_similarity)
    standard_error = (a * (1 - a) / n) ** 0.5  # standard error of binomial
    return a, standard_error


# check that training and test sets are balanced
px.histogram(
    df,
    x="cosine_similarity",
    color="label",
    barmode="overlay",
    width=500,
    facet_row="dataset",
).show()

for dataset in ["train", "test"]:
    data = df[df["dataset"] == dataset]
    a, se = accuracy_and_se(data["cosine_similarity"], data["label"])
    print(f"{dataset} accuracy: {a:0.1%} ± {1.96 * se:0.1%}")

```



    train accuracy: 89.1% ± 2.4%
    test accuracy: 88.8% ± 2.4%


## 7. Optimize the matrix using the training data provided


key: _node_content
string_value:
{"id_": "c933c264-1764-4428-a4f3-4bef4274d332", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "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": "b0993f11-90fe-4402-bf4a-083ca2ae5305", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "549e307203cef7d1f2029dfe57b74301e3d3ad08a2e12448ae35cb86712f1f79", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3e4d432f-a5b5-4a0f-8ae2-10096acacbc9", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "c1b40b9d93c16a29582199aaa285a380d9233ee5c8d97f6bb10e42243e8c8f0a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b3968344-f4b8-44f1-84f2-006de2f24f74", "node_type": "1", "metadata": {}, "hash": "4ad13287483ae83e9fa045d0447069ef883826b1d2ed4a0f48bdf5081ac695b7", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 10217, "end_char_idx": 13261, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
# calculate accuracy (and its standard error) of predicting label=1 if similarity>x
# x is optimized by sweeping from -1 to 1 in steps of 0.01
def accuracy_and_se(cosine_similarity: float, labeled_similarity: int) -> Tuple[float]:
    accuracies = []
    for threshold_thousandths in range(-1000, 1000, 1):
        threshold = threshold_thousandths / 1000
        total = 0
        correct = 0
        for cs, ls in zip(cosine_similarity, labeled_similarity):
            total += 1
            if cs > threshold:
                prediction = 1
            else:
                prediction = -1
            if prediction == ls:
                correct += 1
        accuracy = correct / total
        accuracies.append(accuracy)
    a = max(accuracies)
    n = len(cosine_similarity)
    standard_error = (a * (1 - a) / n) ** 0.5  # standard error of binomial
    return a, standard_error


# check that training and test sets are balanced
px.histogram(
    df,
    x="cosine_similarity",
    color="label",
    barmode="overlay",
    width=500,
    facet_row="dataset",
).show()

for dataset in ["train", "test"]:
    data = df[df["dataset"] == dataset]
    a, se = accuracy_and_se(data["cosine_similarity"], data["label"])
    print(f"{dataset} accuracy: {a:0.1%} ± {1.96 * se:0.1%}")

```



    train accuracy: 89.1% ± 2.4%
    test accuracy: 88.8% ± 2.4%


## 7. Optimize the matrix using the training data provided


```python
def embedding_multiplied_by_matrix(
    embedding: List[float], matrix: torch.tensor
) -> np.array:
    embedding_tensor = torch.tensor(embedding).float()
    modified_embedding = embedding_tensor @ matrix
    modified_embedding = modified_embedding.detach().numpy()
    return modified_embedding


# compute custom embeddings and new cosine similarities
def apply_matrix_to_embeddings_dataframe(matrix: torch.tensor, df: pd.DataFrame):
    for column in ["text_1_embedding", "text_2_embedding"]:
        df[f"{column}_custom"] = df[column].apply(
            lambda x: embedding_multiplied_by_matrix(x, matrix)
        )
    df["cosine_similarity_custom"] = df.apply(
        lambda row: cosine_similarity(
            row["text_1_embedding_custom"], row["text_2_embedding_custom"]
        ),
        axis=1,
    )

```


```python
def optimize_matrix(
    modified_embedding_length: int = 2048,  # in my brief experimentation, bigger was better (2048 is length of babbage encoding)
    batch_size: int = 100,
    max_epochs: int = 100,
    learning_rate: float = 100.0,  # seemed to work best when similar to batch size - feel free to try a range of values
    dropout_fraction: float = 0.0,  # in my testing, dropout helped by a couple percentage points (definitely not necessary)
    df: pd.DataFrame = df,
    print_progress: bool = True,
    save_results: bool = True,
) -> torch.tensor:
    """Return matrix optimized to minimize loss on training data."""
    run_id = random.randint(0, 2 ** 31 - 1)  # (range is arbitrary)
    # convert from dataframe to torch tensors
    # e is for embedding,


key: _node_content
string_value:
{"id_": "b3968344-f4b8-44f1-84f2-006de2f24f74", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "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": "b0993f11-90fe-4402-bf4a-083ca2ae5305", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "549e307203cef7d1f2029dfe57b74301e3d3ad08a2e12448ae35cb86712f1f79", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c933c264-1764-4428-a4f3-4bef4274d332", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "adc377102ac0f3afb7a250df90049c20f2ce8f4d5934843edd55d3e9924df8c7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "fbe40459-c6b1-4263-a134-048d032a2197", "node_type": "1", "metadata": {}, "hash": "832f50598869350d9fed1fc8b8af62bcab0ea233d6c829281dba770bdb6aca6c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 11588, "end_char_idx": 14616, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
## 7. Optimize the matrix using the training data provided


```python
def embedding_multiplied_by_matrix(
    embedding: List[float], matrix: torch.tensor
) -> np.array:
    embedding_tensor = torch.tensor(embedding).float()
    modified_embedding = embedding_tensor @ matrix
    modified_embedding = modified_embedding.detach().numpy()
    return modified_embedding


# compute custom embeddings and new cosine similarities
def apply_matrix_to_embeddings_dataframe(matrix: torch.tensor, df: pd.DataFrame):
    for column in ["text_1_embedding", "text_2_embedding"]:
        df[f"{column}_custom"] = df[column].apply(
            lambda x: embedding_multiplied_by_matrix(x, matrix)
        )
    df["cosine_similarity_custom"] = df.apply(
        lambda row: cosine_similarity(
            row["text_1_embedding_custom"], row["text_2_embedding_custom"]
        ),
        axis=1,
    )

```


```python
def optimize_matrix(
    modified_embedding_length: int = 2048,  # in my brief experimentation, bigger was better (2048 is length of babbage encoding)
    batch_size: int = 100,
    max_epochs: int = 100,
    learning_rate: float = 100.0,  # seemed to work best when similar to batch size - feel free to try a range of values
    dropout_fraction: float = 0.0,  # in my testing, dropout helped by a couple percentage points (definitely not necessary)
    df: pd.DataFrame = df,
    print_progress: bool = True,
    save_results: bool = True,
) -> torch.tensor:
    """Return matrix optimized to minimize loss on training data."""
    run_id = random.randint(0, 2 ** 31 - 1)  # (range is arbitrary)
    # convert from dataframe to torch tensors
    # e is for embedding, s for similarity label
    def tensors_from_dataframe(
        df: pd.DataFrame,
        embedding_column_1: str,
        embedding_column_2: str,
        similarity_label_column: str,
    ) -> Tuple[torch.tensor]:
        e1 = np.stack(np.array(df[embedding_column_1].values))
        e2 = np.stack(np.array(df[embedding_column_2].values))
        s = np.stack(np.array(df[similarity_label_column].astype("float").values))

        e1 = torch.from_numpy(e1).float()
        e2 = torch.from_numpy(e2).float()
        s = torch.from_numpy(s).float()

        return e1, e2, s

    e1_train, e2_train, s_train = tensors_from_dataframe(
        df[df["dataset"] == "train"], "text_1_embedding", "text_2_embedding", "label"
    )
    e1_test, e2_test, s_test = tensors_from_dataframe(
        df[df["dataset"] == "test"], "text_1_embedding", "text_2_embedding", "label"
    )

    # create dataset and loader
    dataset = torch.utils.data.TensorDataset(e1_train, e2_train, s_train)
    train_loader = torch.utils.data.DataLoader(
        dataset, batch_size=batch_size, shuffle=True
    )

    # define model (similarity of projected embeddings)
    def model(embedding_1, embedding_2, matrix, dropout_fraction=dropout_fraction):
        e1 = torch.nn.functional.dropout(embedding_1, p=dropout_fraction)
        e2 = torch.nn.functional.dropout(embedding_2,


key: _node_content
string_value:
{"id_": "fbe40459-c6b1-4263-a134-048d032a2197", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "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": "b0993f11-90fe-4402-bf4a-083ca2ae5305", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "549e307203cef7d1f2029dfe57b74301e3d3ad08a2e12448ae35cb86712f1f79", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b3968344-f4b8-44f1-84f2-006de2f24f74", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "e10de35c54c70886ada2864d7ff2a900ffccb7e4f54bb28fe97d06be1f839453", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "731f10b1-2c74-4d78-b3ef-16d0077aa984", "node_type": "1", "metadata": {}, "hash": "0a8bef462b8ea870f53cc28b92714b917ef002ef1baaee54e393bf4abacf9e39", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 13262, "end_char_idx": 16563, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
s for similarity label
    def tensors_from_dataframe(
        df: pd.DataFrame,
        embedding_column_1: str,
        embedding_column_2: str,
        similarity_label_column: str,
    ) -> Tuple[torch.tensor]:
        e1 = np.stack(np.array(df[embedding_column_1].values))
        e2 = np.stack(np.array(df[embedding_column_2].values))
        s = np.stack(np.array(df[similarity_label_column].astype("float").values))

        e1 = torch.from_numpy(e1).float()
        e2 = torch.from_numpy(e2).float()
        s = torch.from_numpy(s).float()

        return e1, e2, s

    e1_train, e2_train, s_train = tensors_from_dataframe(
        df[df["dataset"] == "train"], "text_1_embedding", "text_2_embedding", "label"
    )
    e1_test, e2_test, s_test = tensors_from_dataframe(
        df[df["dataset"] == "test"], "text_1_embedding", "text_2_embedding", "label"
    )

    # create dataset and loader
    dataset = torch.utils.data.TensorDataset(e1_train, e2_train, s_train)
    train_loader = torch.utils.data.DataLoader(
        dataset, batch_size=batch_size, shuffle=True
    )

    # define model (similarity of projected embeddings)
    def model(embedding_1, embedding_2, matrix, dropout_fraction=dropout_fraction):
        e1 = torch.nn.functional.dropout(embedding_1, p=dropout_fraction)
        e2 = torch.nn.functional.dropout(embedding_2, p=dropout_fraction)
        modified_embedding_1 = e1 @ matrix  # @ is matrix multiplication
        modified_embedding_2 = e2 @ matrix
        similarity = torch.nn.functional.cosine_similarity(
            modified_embedding_1, modified_embedding_2
        )
        return similarity

    # define loss function to minimize
    def mse_loss(predictions, targets):
        difference = predictions - targets
        return torch.sum(difference * difference) / difference.numel()

    # initialize projection matrix
    embedding_length = len(df["text_1_embedding"].values[0])
    matrix = torch.randn(
        embedding_length, modified_embedding_length, requires_grad=True
    )

    epochs, types, losses, accuracies, matrices = [], [], [], [], []
    for epoch in range(1, 1 + max_epochs):
        # iterate through training dataloader
        for a, b, actual_similarity in train_loader:
            # generate prediction
            predicted_similarity = model(a, b, matrix)
            # get loss and perform backpropagation
            loss = mse_loss(predicted_similarity, actual_similarity)
            loss.backward()
            # update the weights
            with torch.no_grad():
                matrix -= matrix.grad * learning_rate
                # set gradients to zero
                matrix.grad.zero_()
        # calculate test loss
        test_predictions = model(e1_test, e2_test, matrix)
        test_loss = mse_loss(test_predictions, s_test)

        # compute custom embeddings and new cosine similarities
        apply_matrix_to_embeddings_dataframe(matrix, df)

        # calculate test accuracy
        for dataset in ["train", "test"]:
            data = df[df["dataset"] == dataset]
            a, se = accuracy_and_se(data["cosine_similarity_custom"], data["label"])

            # record results of each epoch
            epochs.append(epoch)
            types.append(dataset)
            losses.append(loss.


key: _node_content
string_value:
{"id_": "731f10b1-2c74-4d78-b3ef-16d0077aa984", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "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": "b0993f11-90fe-4402-bf4a-083ca2ae5305", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "549e307203cef7d1f2029dfe57b74301e3d3ad08a2e12448ae35cb86712f1f79", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "fbe40459-c6b1-4263-a134-048d032a2197", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "0726f8edb49b96c7f6081306d2ca6bb245b98cadab11624a969c42b8ad7854ec", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f2a743bc-ad68-4650-adc3-0dbcd76a1654", "node_type": "1", "metadata": {}, "hash": "8bc06622347a2f28ae6cf7811f5a8492f371d43392ad4d201fd646fb133b06ee", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 14780, "end_char_idx": 18126, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
nn.functional.cosine_similarity(
            modified_embedding_1, modified_embedding_2
        )
        return similarity

    # define loss function to minimize
    def mse_loss(predictions, targets):
        difference = predictions - targets
        return torch.sum(difference * difference) / difference.numel()

    # initialize projection matrix
    embedding_length = len(df["text_1_embedding"].values[0])
    matrix = torch.randn(
        embedding_length, modified_embedding_length, requires_grad=True
    )

    epochs, types, losses, accuracies, matrices = [], [], [], [], []
    for epoch in range(1, 1 + max_epochs):
        # iterate through training dataloader
        for a, b, actual_similarity in train_loader:
            # generate prediction
            predicted_similarity = model(a, b, matrix)
            # get loss and perform backpropagation
            loss = mse_loss(predicted_similarity, actual_similarity)
            loss.backward()
            # update the weights
            with torch.no_grad():
                matrix -= matrix.grad * learning_rate
                # set gradients to zero
                matrix.grad.zero_()
        # calculate test loss
        test_predictions = model(e1_test, e2_test, matrix)
        test_loss = mse_loss(test_predictions, s_test)

        # compute custom embeddings and new cosine similarities
        apply_matrix_to_embeddings_dataframe(matrix, df)

        # calculate test accuracy
        for dataset in ["train", "test"]:
            data = df[df["dataset"] == dataset]
            a, se = accuracy_and_se(data["cosine_similarity_custom"], data["label"])

            # record results of each epoch
            epochs.append(epoch)
            types.append(dataset)
            losses.append(loss.item() if dataset == "train" else test_loss.item())
            accuracies.append(a)
            matrices.append(matrix.detach().numpy())

            # optionally print accuracies
            if print_progress is True:
                print(
                    f"Epoch {epoch}/{max_epochs}: {dataset} accuracy: {a:0.1%} ± {1.96 * se:0.1%}"
                )

    data = pd.DataFrame(
        {"epoch": epochs, "type": types, "loss": losses, "accuracy": accuracies}
    )
    data["run_id"] = run_id
    data["modified_embedding_length"] = modified_embedding_length
    data["batch_size"] = batch_size
    data["max_epochs"] = max_epochs
    data["learning_rate"] = learning_rate
    data["dropout_fraction"] = dropout_fraction
    data[
        "matrix"
    ] = matrices  # saving every single matrix can get big; feel free to delete/change
    if save_results is True:
        data.to_csv(f"{run_id}_optimization_results.csv", index=False)

    return data

```


```python
# example hyperparameter search
# I recommend starting with max_epochs=10 while initially exploring
results = []
max_epochs = 30
dropout_fraction = 0.2
for batch_size, learning_rate in [(10, 10), (100, 100), (1000, 1000)]:
    result = optimize_matrix(
        batch_size=batch_size,
        learning_rate=learning_rate,
        max_epochs=max_epochs,
        dropout_fraction=dropout_fraction,
        save_results=False,
    )
    results.append(result)

```

    Epoch 1/30: train accuracy: 89.1% ± 2.4%
    Epoch 1/30: test accuracy: 88.4% ± 2.4%
    Epoch 2/30: train accuracy: 89.


key: _node_content
string_value:
{"id_": "f2a743bc-ad68-4650-adc3-0dbcd76a1654", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "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": "b0993f11-90fe-4402-bf4a-083ca2ae5305", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "549e307203cef7d1f2029dfe57b74301e3d3ad08a2e12448ae35cb86712f1f79", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "731f10b1-2c74-4d78-b3ef-16d0077aa984", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "544099dffdaae925f7beb655ae25cb735c209180f35d2efb025a61f83be0532c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "fac9e877-46a6-4ff3-bf7e-b9e1f23b156d", "node_type": "1", "metadata": {}, "hash": "7dab543ded95c0e726236dbcb003a36e0f5e5de17756fc0e02c53744090e70f2", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 16607, "end_char_idx": 18891, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
item())
            accuracies.append(a)
            matrices.append(matrix.detach().numpy())

            # optionally print accuracies
            if print_progress is True:
                print(
                    f"Epoch {epoch}/{max_epochs}: {dataset} accuracy: {a:0.1%} ± {1.96 * se:0.1%}"
                )

    data = pd.DataFrame(
        {"epoch": epochs, "type": types, "loss": losses, "accuracy": accuracies}
    )
    data["run_id"] = run_id
    data["modified_embedding_length"] = modified_embedding_length
    data["batch_size"] = batch_size
    data["max_epochs"] = max_epochs
    data["learning_rate"] = learning_rate
    data["dropout_fraction"] = dropout_fraction
    data[
        "matrix"
    ] = matrices  # saving every single matrix can get big; feel free to delete/change
    if save_results is True:
        data.to_csv(f"{run_id}_optimization_results.csv", index=False)

    return data

```


```python
# example hyperparameter search
# I recommend starting with max_epochs=10 while initially exploring
results = []
max_epochs = 30
dropout_fraction = 0.2
for batch_size, learning_rate in [(10, 10), (100, 100), (1000, 1000)]:
    result = optimize_matrix(
        batch_size=batch_size,
        learning_rate=learning_rate,
        max_epochs=max_epochs,
        dropout_fraction=dropout_fraction,
        save_results=False,
    )
    results.append(result)

```

    Epoch 1/30: train accuracy: 89.1% ± 2.4%
    Epoch 1/30: test accuracy: 88.4% ± 2.4%
    Epoch 2/30: train accuracy: 89.5% ± 2.3%
    Epoch 2/30: test accuracy: 88.8% ± 2.4%
    Epoch 3/30: train accuracy: 90.6% ± 2.2%
    Epoch 3/30: test accuracy: 89.3% ± 2.3%
    Epoch 4/30: train accuracy: 91.2% ± 2.2%
    Epoch 4/30: test accuracy: 89.7% ± 2.3%
    Epoch 5/30: train accuracy: 91.5% ± 2.1%
    Epoch 5/30: test accuracy: 90.0% ± 2.3%
    Epoch 6/30: train accuracy: 91.9% ± 2.1%
    Epoch 6/30: test accuracy: 90.4% ± 2.2%
    Epoch 7/30: train accuracy: 92.2% ± 2.0%
    Epoch 7/30: test accuracy: 90.7% ± 2.2%
    Epoch 8/30: train accuracy: 92.7% ± 2.0%
    Epoch 8/30: test accuracy: 90.9% ± 2.2%
    Epoch 9/30: train accuracy: 92.7% ± 2.0%
    Epoch 9/30: test accuracy: 91.0% ± 2.2%
    Epoch 10/30: train accuracy: 93.0% ± 1.9%
    Epoch 10/30: test accuracy: 91.6% ± 2.


key: _node_content
string_value:
{"id_": "fac9e877-46a6-4ff3-bf7e-b9e1f23b156d", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "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": "b0993f11-90fe-4402-bf4a-083ca2ae5305", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "549e307203cef7d1f2029dfe57b74301e3d3ad08a2e12448ae35cb86712f1f79", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f2a743bc-ad68-4650-adc3-0dbcd76a1654", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "211e45b54b76a0260cb022bfd1a3d820c7c3954a682e734aa1000eb484e10a91", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "853c346a-8fb7-4f6f-88d7-0991f611893e", "node_type": "1", "metadata": {}, "hash": "bd3302f74fb7d1d159862e481630eeee78f2c5ec454cff3f4bb78998baf6a503", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 18044, "end_char_idx": 19710, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
4%
    Epoch 1/30: test accuracy: 88.4% ± 2.4%
    Epoch 2/30: train accuracy: 89.5% ± 2.3%
    Epoch 2/30: test accuracy: 88.8% ± 2.4%
    Epoch 3/30: train accuracy: 90.6% ± 2.2%
    Epoch 3/30: test accuracy: 89.3% ± 2.3%
    Epoch 4/30: train accuracy: 91.2% ± 2.2%
    Epoch 4/30: test accuracy: 89.7% ± 2.3%
    Epoch 5/30: train accuracy: 91.5% ± 2.1%
    Epoch 5/30: test accuracy: 90.0% ± 2.3%
    Epoch 6/30: train accuracy: 91.9% ± 2.1%
    Epoch 6/30: test accuracy: 90.4% ± 2.2%
    Epoch 7/30: train accuracy: 92.2% ± 2.0%
    Epoch 7/30: test accuracy: 90.7% ± 2.2%
    Epoch 8/30: train accuracy: 92.7% ± 2.0%
    Epoch 8/30: test accuracy: 90.9% ± 2.2%
    Epoch 9/30: train accuracy: 92.7% ± 2.0%
    Epoch 9/30: test accuracy: 91.0% ± 2.2%
    Epoch 10/30: train accuracy: 93.0% ± 1.9%
    Epoch 10/30: test accuracy: 91.6% ± 2.1%
    Epoch 11/30: train accuracy: 93.1% ± 1.9%
    Epoch 11/30: test accuracy: 91.8% ± 2.1%
    Epoch 12/30: train accuracy: 93.4% ± 1.9%
    Epoch 12/30: test accuracy: 92.1% ± 2.0%
    Epoch 13/30: train accuracy: 93.6% ± 1.9%
    Epoch 13/30: test accuracy: 92.4% ± 2.0%
    Epoch 14/30: train accuracy: 93.7% ± 1.8%
    Epoch 14/30: test accuracy: 92.7% ± 2.0%
    Epoch 15/30: train accuracy: 93.7% ± 1.8%
    Epoch 15/30: test accuracy: 92.7% ± 2.0%
    Epoch 16/30: train accuracy: 94.0% ± 1.8%
    Epoch 16/30: test accuracy: 93.0% ± 1.9%
    Epoch 17/30: train accuracy: 94.0% ± 1.8%
    Epoch 17/30: test accuracy: 93.0% ± 1.9%
    Epoch 18/30: train accuracy: 94.2% ± 1.8%
    Epoch 18/30: test accuracy: 93.1% ± 1.9%
    Epoch 19/30: train accuracy: 94.2% ± 1.8%
    Epoch 19/30: test accuracy: 93.1% ± 1.


key: _node_content
string_value:
{"id_": "853c346a-8fb7-4f6f-88d7-0991f611893e", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "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": "b0993f11-90fe-4402-bf4a-083ca2ae5305", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "549e307203cef7d1f2029dfe57b74301e3d3ad08a2e12448ae35cb86712f1f79", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "fac9e877-46a6-4ff3-bf7e-b9e1f23b156d", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "2e84216ebb3e368258d6bd97cb779e7e8e93dec8dd595210c2caf6f62993f7af", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1936d703-0958-475d-b3ef-baa6ee164fb4", "node_type": "1", "metadata": {}, "hash": "e94cd5ad363918e2b3c0bcf82305c0c9a6388adb4b35742adf24c7e71aa78dc2", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 18846, "end_char_idx": 20529, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
9%
    Epoch 10/30: test accuracy: 91.6% ± 2.1%
    Epoch 11/30: train accuracy: 93.1% ± 1.9%
    Epoch 11/30: test accuracy: 91.8% ± 2.1%
    Epoch 12/30: train accuracy: 93.4% ± 1.9%
    Epoch 12/30: test accuracy: 92.1% ± 2.0%
    Epoch 13/30: train accuracy: 93.6% ± 1.9%
    Epoch 13/30: test accuracy: 92.4% ± 2.0%
    Epoch 14/30: train accuracy: 93.7% ± 1.8%
    Epoch 14/30: test accuracy: 92.7% ± 2.0%
    Epoch 15/30: train accuracy: 93.7% ± 1.8%
    Epoch 15/30: test accuracy: 92.7% ± 2.0%
    Epoch 16/30: train accuracy: 94.0% ± 1.8%
    Epoch 16/30: test accuracy: 93.0% ± 1.9%
    Epoch 17/30: train accuracy: 94.0% ± 1.8%
    Epoch 17/30: test accuracy: 93.0% ± 1.9%
    Epoch 18/30: train accuracy: 94.2% ± 1.8%
    Epoch 18/30: test accuracy: 93.1% ± 1.9%
    Epoch 19/30: train accuracy: 94.2% ± 1.8%
    Epoch 19/30: test accuracy: 93.1% ± 1.9%
    Epoch 20/30: train accuracy: 94.3% ± 1.8%
    Epoch 20/30: test accuracy: 93.0% ± 1.9%
    Epoch 21/30: train accuracy: 94.5% ± 1.7%
    Epoch 21/30: test accuracy: 93.1% ± 1.9%
    Epoch 22/30: train accuracy: 94.5% ± 1.7%
    Epoch 22/30: test accuracy: 93.3% ± 1.9%
    Epoch 23/30: train accuracy: 94.6% ± 1.7%
    Epoch 23/30: test accuracy: 93.3% ± 1.9%
    Epoch 24/30: train accuracy: 94.6% ± 1.7%
    Epoch 24/30: test accuracy: 93.3% ± 1.9%
    Epoch 25/30: train accuracy: 94.8% ± 1.7%
    Epoch 25/30: test accuracy: 93.3% ± 1.9%
    Epoch 26/30: train accuracy: 94.8% ± 1.7%
    Epoch 26/30: test accuracy: 93.4% ± 1.9%
    Epoch 27/30: train accuracy: 94.8% ± 1.7%
    Epoch 27/30: test accuracy: 93.4% ± 1.9%
    Epoch 28/30: train accuracy: 94.9% ± 1.7%
    Epoch 28/30: test accuracy: 93.4% ± 1.


key: _node_content
string_value:
{"id_": "1936d703-0958-475d-b3ef-baa6ee164fb4", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "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": "b0993f11-90fe-4402-bf4a-083ca2ae5305", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "549e307203cef7d1f2029dfe57b74301e3d3ad08a2e12448ae35cb86712f1f79", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "853c346a-8fb7-4f6f-88d7-0991f611893e", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "87dccfcc8be5da49d49170ac8c0dab86e3e0b351551f62e592aa10c2e6101e24", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9423f351-c8f9-489f-98ed-e4b39bc6a16b", "node_type": "1", "metadata": {}, "hash": "b0eca73acf4938d0ce44a9ceec072905f7350a1103e55093a560e63841d67f7b", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 19665, "end_char_idx": 21334, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
8%
    Epoch 19/30: test accuracy: 93.1% ± 1.9%
    Epoch 20/30: train accuracy: 94.3% ± 1.8%
    Epoch 20/30: test accuracy: 93.0% ± 1.9%
    Epoch 21/30: train accuracy: 94.5% ± 1.7%
    Epoch 21/30: test accuracy: 93.1% ± 1.9%
    Epoch 22/30: train accuracy: 94.5% ± 1.7%
    Epoch 22/30: test accuracy: 93.3% ± 1.9%
    Epoch 23/30: train accuracy: 94.6% ± 1.7%
    Epoch 23/30: test accuracy: 93.3% ± 1.9%
    Epoch 24/30: train accuracy: 94.6% ± 1.7%
    Epoch 24/30: test accuracy: 93.3% ± 1.9%
    Epoch 25/30: train accuracy: 94.8% ± 1.7%
    Epoch 25/30: test accuracy: 93.3% ± 1.9%
    Epoch 26/30: train accuracy: 94.8% ± 1.7%
    Epoch 26/30: test accuracy: 93.4% ± 1.9%
    Epoch 27/30: train accuracy: 94.8% ± 1.7%
    Epoch 27/30: test accuracy: 93.4% ± 1.9%
    Epoch 28/30: train accuracy: 94.9% ± 1.7%
    Epoch 28/30: test accuracy: 93.4% ± 1.9%
    Epoch 29/30: train accuracy: 94.9% ± 1.7%
    Epoch 29/30: test accuracy: 93.4% ± 1.9%
    Epoch 30/30: train accuracy: 94.9% ± 1.7%
    Epoch 30/30: test accuracy: 93.3% ± 1.9%
    Epoch 1/30: train accuracy: 89.7% ± 2.3%
    Epoch 1/30: test accuracy: 89.1% ± 2.4%
    Epoch 2/30: train accuracy: 89.8% ± 2.3%
    Epoch 2/30: test accuracy: 89.9% ± 2.3%
    Epoch 3/30: train accuracy: 90.3% ± 2.2%
    Epoch 3/30: test accuracy: 90.0% ± 2.3%
    Epoch 4/30: train accuracy: 91.0% ± 2.2%
    Epoch 4/30: test accuracy: 90.3% ± 2.2%
    Epoch 5/30: train accuracy: 91.3% ± 2.1%
    Epoch 5/30: test accuracy: 90.3% ± 2.2%
    Epoch 6/30: train accuracy: 91.8% ± 2.1%
    Epoch 6/30: test accuracy: 90.4% ± 2.2%
    Epoch 7/30: train accuracy: 92.4% ± 2.0%
    Epoch 7/30: test accuracy: 91.0% ± 2.


key: _node_content
string_value:
{"id_": "9423f351-c8f9-489f-98ed-e4b39bc6a16b", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "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": "b0993f11-90fe-4402-bf4a-083ca2ae5305", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "549e307203cef7d1f2029dfe57b74301e3d3ad08a2e12448ae35cb86712f1f79", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1936d703-0958-475d-b3ef-baa6ee164fb4", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "9b66faeef277c4fb467c6a7abf8f63aea2bbc02775d5b01991cdd2e6734231d0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "952fcc80-b2ab-48da-8a70-cfa4c4b2c2d5", "node_type": "1", "metadata": {}, "hash": "669da3f0e145d80a690a7375cc3143d1f430be5d6baa03bc01d0ff08ce999ac9", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 20484, "end_char_idx": 22149, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
7%
    Epoch 28/30: test accuracy: 93.4% ± 1.9%
    Epoch 29/30: train accuracy: 94.9% ± 1.7%
    Epoch 29/30: test accuracy: 93.4% ± 1.9%
    Epoch 30/30: train accuracy: 94.9% ± 1.7%
    Epoch 30/30: test accuracy: 93.3% ± 1.9%
    Epoch 1/30: train accuracy: 89.7% ± 2.3%
    Epoch 1/30: test accuracy: 89.1% ± 2.4%
    Epoch 2/30: train accuracy: 89.8% ± 2.3%
    Epoch 2/30: test accuracy: 89.9% ± 2.3%
    Epoch 3/30: train accuracy: 90.3% ± 2.2%
    Epoch 3/30: test accuracy: 90.0% ± 2.3%
    Epoch 4/30: train accuracy: 91.0% ± 2.2%
    Epoch 4/30: test accuracy: 90.3% ± 2.2%
    Epoch 5/30: train accuracy: 91.3% ± 2.1%
    Epoch 5/30: test accuracy: 90.3% ± 2.2%
    Epoch 6/30: train accuracy: 91.8% ± 2.1%
    Epoch 6/30: test accuracy: 90.4% ± 2.2%
    Epoch 7/30: train accuracy: 92.4% ± 2.0%
    Epoch 7/30: test accuracy: 91.0% ± 2.2%
    Epoch 8/30: train accuracy: 92.8% ± 2.0%
    Epoch 8/30: test accuracy: 91.3% ± 2.1%
    Epoch 9/30: train accuracy: 93.1% ± 1.9%
    Epoch 9/30: test accuracy: 91.6% ± 2.1%
    Epoch 10/30: train accuracy: 93.4% ± 1.9%
    Epoch 10/30: test accuracy: 91.9% ± 2.1%
    Epoch 11/30: train accuracy: 93.4% ± 1.9%
    Epoch 11/30: test accuracy: 91.8% ± 2.1%
    Epoch 12/30: train accuracy: 93.6% ± 1.9%
    Epoch 12/30: test accuracy: 92.1% ± 2.0%
    Epoch 13/30: train accuracy: 93.7% ± 1.8%
    Epoch 13/30: test accuracy: 92.4% ± 2.0%
    Epoch 14/30: train accuracy: 93.7% ± 1.8%
    Epoch 14/30: test accuracy: 92.5% ± 2.0%
    Epoch 15/30: train accuracy: 93.9% ± 1.8%
    Epoch 15/30: test accuracy: 92.8% ± 2.0%
    Epoch 16/30: train accuracy: 94.0% ± 1.8%
    Epoch 16/30: test accuracy: 92.8% ± 2.


key: _node_content
string_value:
{"id_": "952fcc80-b2ab-48da-8a70-cfa4c4b2c2d5", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "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": "b0993f11-90fe-4402-bf4a-083ca2ae5305", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "549e307203cef7d1f2029dfe57b74301e3d3ad08a2e12448ae35cb86712f1f79", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9423f351-c8f9-489f-98ed-e4b39bc6a16b", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "1515b38ab7c0ec042a003b60e95fbe9903d58143b9a9df4347157626b3682365", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "21c43582-eb30-4c3b-a573-2fe0c7ff5ade", "node_type": "1", "metadata": {}, "hash": "3b64af1bbb481e55920f1f726d1fd7d935ae3be27495763e0e69b7438cdfd79a", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 21290, "end_char_idx": 22968, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
0%
    Epoch 7/30: test accuracy: 91.0% ± 2.2%
    Epoch 8/30: train accuracy: 92.8% ± 2.0%
    Epoch 8/30: test accuracy: 91.3% ± 2.1%
    Epoch 9/30: train accuracy: 93.1% ± 1.9%
    Epoch 9/30: test accuracy: 91.6% ± 2.1%
    Epoch 10/30: train accuracy: 93.4% ± 1.9%
    Epoch 10/30: test accuracy: 91.9% ± 2.1%
    Epoch 11/30: train accuracy: 93.4% ± 1.9%
    Epoch 11/30: test accuracy: 91.8% ± 2.1%
    Epoch 12/30: train accuracy: 93.6% ± 1.9%
    Epoch 12/30: test accuracy: 92.1% ± 2.0%
    Epoch 13/30: train accuracy: 93.7% ± 1.8%
    Epoch 13/30: test accuracy: 92.4% ± 2.0%
    Epoch 14/30: train accuracy: 93.7% ± 1.8%
    Epoch 14/30: test accuracy: 92.5% ± 2.0%
    Epoch 15/30: train accuracy: 93.9% ± 1.8%
    Epoch 15/30: test accuracy: 92.8% ± 2.0%
    Epoch 16/30: train accuracy: 94.0% ± 1.8%
    Epoch 16/30: test accuracy: 92.8% ± 2.0%
    Epoch 17/30: train accuracy: 94.0% ± 1.8%
    Epoch 17/30: test accuracy: 92.8% ± 2.0%
    Epoch 18/30: train accuracy: 94.2% ± 1.8%
    Epoch 18/30: test accuracy: 92.8% ± 2.0%
    Epoch 19/30: train accuracy: 94.2% ± 1.8%
    Epoch 19/30: test accuracy: 92.8% ± 2.0%
    Epoch 20/30: train accuracy: 94.2% ± 1.8%
    Epoch 20/30: test accuracy: 93.1% ± 1.9%
    Epoch 21/30: train accuracy: 94.3% ± 1.8%
    Epoch 21/30: test accuracy: 93.3% ± 1.9%
    Epoch 22/30: train accuracy: 94.3% ± 1.8%
    Epoch 22/30: test accuracy: 93.3% ± 1.9%
    Epoch 23/30: train accuracy: 94.5% ± 1.7%
    Epoch 23/30: test accuracy: 93.3% ± 1.9%
    Epoch 24/30: train accuracy: 94.5% ± 1.7%
    Epoch 24/30: test accuracy: 93.3% ± 1.9%
    Epoch 25/30: train accuracy: 94.6% ± 1.7%
    Epoch 25/30: test accuracy: 93.4% ± 1.


key: _node_content
string_value:
{"id_": "21c43582-eb30-4c3b-a573-2fe0c7ff5ade", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "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": "b0993f11-90fe-4402-bf4a-083ca2ae5305", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "549e307203cef7d1f2029dfe57b74301e3d3ad08a2e12448ae35cb86712f1f79", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "952fcc80-b2ab-48da-8a70-cfa4c4b2c2d5", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "138b61128a3eeeda7540bdb862eb9bbc6ed4b9639c15e3cc414c488a397d60b3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c022b522-42e9-49b2-81d2-37d70f1d19c6", "node_type": "1", "metadata": {}, "hash": "488abbe0d4090c75449bec40ade5f24e4e5bae1a1aa9513d76903222d1aabff3", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 22104, "end_char_idx": 23779, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
8%
    Epoch 16/30: test accuracy: 92.8% ± 2.0%
    Epoch 17/30: train accuracy: 94.0% ± 1.8%
    Epoch 17/30: test accuracy: 92.8% ± 2.0%
    Epoch 18/30: train accuracy: 94.2% ± 1.8%
    Epoch 18/30: test accuracy: 92.8% ± 2.0%
    Epoch 19/30: train accuracy: 94.2% ± 1.8%
    Epoch 19/30: test accuracy: 92.8% ± 2.0%
    Epoch 20/30: train accuracy: 94.2% ± 1.8%
    Epoch 20/30: test accuracy: 93.1% ± 1.9%
    Epoch 21/30: train accuracy: 94.3% ± 1.8%
    Epoch 21/30: test accuracy: 93.3% ± 1.9%
    Epoch 22/30: train accuracy: 94.3% ± 1.8%
    Epoch 22/30: test accuracy: 93.3% ± 1.9%
    Epoch 23/30: train accuracy: 94.5% ± 1.7%
    Epoch 23/30: test accuracy: 93.3% ± 1.9%
    Epoch 24/30: train accuracy: 94.5% ± 1.7%
    Epoch 24/30: test accuracy: 93.3% ± 1.9%
    Epoch 25/30: train accuracy: 94.6% ± 1.7%
    Epoch 25/30: test accuracy: 93.4% ± 1.9%
    Epoch 26/30: train accuracy: 94.6% ± 1.7%
    Epoch 26/30: test accuracy: 93.3% ± 1.9%
    Epoch 27/30: train accuracy: 94.6% ± 1.7%
    Epoch 27/30: test accuracy: 93.4% ± 1.9%
    Epoch 28/30: train accuracy: 94.8% ± 1.7%
    Epoch 28/30: test accuracy: 93.4% ± 1.9%
    Epoch 29/30: train accuracy: 94.8% ± 1.7%
    Epoch 29/30: test accuracy: 93.3% ± 1.9%
    Epoch 30/30: train accuracy: 94.8% ± 1.7%
    Epoch 30/30: test accuracy: 93.4% ± 1.9%
    Epoch 1/30: train accuracy: 90.7% ± 2.2%
    Epoch 1/30: test accuracy: 89.9% ± 2.3%
    Epoch 2/30: train accuracy: 90.9% ± 2.2%
    Epoch 2/30: test accuracy: 90.3% ± 2.2%
    Epoch 3/30: train accuracy: 91.6% ± 2.1%
    Epoch 3/30: test accuracy: 90.3% ± 2.2%
    Epoch 4/30: train accuracy: 92.2% ± 2.0%
    Epoch 4/30: test accuracy: 90.7% ± 2.


key: _node_content
string_value:
{"id_": "c022b522-42e9-49b2-81d2-37d70f1d19c6", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "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": "b0993f11-90fe-4402-bf4a-083ca2ae5305", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "549e307203cef7d1f2029dfe57b74301e3d3ad08a2e12448ae35cb86712f1f79", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "21c43582-eb30-4c3b-a573-2fe0c7ff5ade", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "f64cd2c290e5101136538ca27be1aae5129c1d7314c05ab3db5170fa9019ba99", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ea28993c-eb77-4e11-b70b-a774a77f8610", "node_type": "1", "metadata": {}, "hash": "0054eba0f3e90877392c604cdd9bb99da2f9d1c16b77379b7df145009dde73a1", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 22923, "end_char_idx": 24588, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
7%
    Epoch 25/30: test accuracy: 93.4% ± 1.9%
    Epoch 26/30: train accuracy: 94.6% ± 1.7%
    Epoch 26/30: test accuracy: 93.3% ± 1.9%
    Epoch 27/30: train accuracy: 94.6% ± 1.7%
    Epoch 27/30: test accuracy: 93.4% ± 1.9%
    Epoch 28/30: train accuracy: 94.8% ± 1.7%
    Epoch 28/30: test accuracy: 93.4% ± 1.9%
    Epoch 29/30: train accuracy: 94.8% ± 1.7%
    Epoch 29/30: test accuracy: 93.3% ± 1.9%
    Epoch 30/30: train accuracy: 94.8% ± 1.7%
    Epoch 30/30: test accuracy: 93.4% ± 1.9%
    Epoch 1/30: train accuracy: 90.7% ± 2.2%
    Epoch 1/30: test accuracy: 89.9% ± 2.3%
    Epoch 2/30: train accuracy: 90.9% ± 2.2%
    Epoch 2/30: test accuracy: 90.3% ± 2.2%
    Epoch 3/30: train accuracy: 91.6% ± 2.1%
    Epoch 3/30: test accuracy: 90.3% ± 2.2%
    Epoch 4/30: train accuracy: 92.2% ± 2.0%
    Epoch 4/30: test accuracy: 90.7% ± 2.2%
    Epoch 5/30: train accuracy: 92.4% ± 2.0%
    Epoch 5/30: test accuracy: 91.3% ± 2.1%
    Epoch 6/30: train accuracy: 92.5% ± 2.0%
    Epoch 6/30: test accuracy: 91.8% ± 2.1%
    Epoch 7/30: train accuracy: 93.0% ± 1.9%
    Epoch 7/30: test accuracy: 92.2% ± 2.0%
    Epoch 8/30: train accuracy: 93.1% ± 1.9%
    Epoch 8/30: test accuracy: 92.7% ± 2.0%
    Epoch 9/30: train accuracy: 93.3% ± 1.9%
    Epoch 9/30: test accuracy: 92.5% ± 2.0%
    Epoch 10/30: train accuracy: 93.4% ± 1.9%
    Epoch 10/30: test accuracy: 92.7% ± 2.0%
    Epoch 11/30: train accuracy: 93.6% ± 1.9%
    Epoch 11/30: test accuracy: 92.8% ± 2.0%
    Epoch 12/30: train accuracy: 93.7% ± 1.8%
    Epoch 12/30: test accuracy: 92.8% ± 2.0%
    Epoch 13/30: train accuracy: 94.0% ± 1.8%
    Epoch 13/30: test accuracy: 93.0% ± 1.


key: _node_content
string_value:
{"id_": "ea28993c-eb77-4e11-b70b-a774a77f8610", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "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": "b0993f11-90fe-4402-bf4a-083ca2ae5305", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "549e307203cef7d1f2029dfe57b74301e3d3ad08a2e12448ae35cb86712f1f79", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c022b522-42e9-49b2-81d2-37d70f1d19c6", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "4d7f3beee353b61756788e844c3691be3aabcb1aefcb98697300f31b52ac5bee", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d53ac7f1-2e1c-4858-a6c4-4e3525e08b27", "node_type": "1", "metadata": {}, "hash": "b76d3adb2c023e94972d9bddffa2071993ee481ea38b5c46814e6f89a4a6c4cd", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 23735, "end_char_idx": 25407, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
0%
    Epoch 4/30: test accuracy: 90.7% ± 2.2%
    Epoch 5/30: train accuracy: 92.4% ± 2.0%
    Epoch 5/30: test accuracy: 91.3% ± 2.1%
    Epoch 6/30: train accuracy: 92.5% ± 2.0%
    Epoch 6/30: test accuracy: 91.8% ± 2.1%
    Epoch 7/30: train accuracy: 93.0% ± 1.9%
    Epoch 7/30: test accuracy: 92.2% ± 2.0%
    Epoch 8/30: train accuracy: 93.1% ± 1.9%
    Epoch 8/30: test accuracy: 92.7% ± 2.0%
    Epoch 9/30: train accuracy: 93.3% ± 1.9%
    Epoch 9/30: test accuracy: 92.5% ± 2.0%
    Epoch 10/30: train accuracy: 93.4% ± 1.9%
    Epoch 10/30: test accuracy: 92.7% ± 2.0%
    Epoch 11/30: train accuracy: 93.6% ± 1.9%
    Epoch 11/30: test accuracy: 92.8% ± 2.0%
    Epoch 12/30: train accuracy: 93.7% ± 1.8%
    Epoch 12/30: test accuracy: 92.8% ± 2.0%
    Epoch 13/30: train accuracy: 94.0% ± 1.8%
    Epoch 13/30: test accuracy: 93.0% ± 1.9%
    Epoch 14/30: train accuracy: 93.9% ± 1.8%
    Epoch 14/30: test accuracy: 93.0% ± 1.9%
    Epoch 15/30: train accuracy: 94.2% ± 1.8%
    Epoch 15/30: test accuracy: 93.0% ± 1.9%
    Epoch 16/30: train accuracy: 94.2% ± 1.8%
    Epoch 16/30: test accuracy: 93.0% ± 1.9%
    Epoch 17/30: train accuracy: 94.3% ± 1.8%
    Epoch 17/30: test accuracy: 93.0% ± 1.9%
    Epoch 18/30: train accuracy: 94.5% ± 1.7%
    Epoch 18/30: test accuracy: 93.1% ± 1.9%
    Epoch 19/30: train accuracy: 94.5% ± 1.7%
    Epoch 19/30: test accuracy: 93.1% ± 1.9%
    Epoch 20/30: train accuracy: 94.6% ± 1.7%
    Epoch 20/30: test accuracy: 93.3% ± 1.9%
    Epoch 21/30: train accuracy: 94.8% ± 1.7%
    Epoch 21/30: test accuracy: 93.3% ± 1.9%
    Epoch 22/30: train accuracy: 94.8% ± 1.7%
    Epoch 22/30: test accuracy: 93.4% ± 1.


key: _node_content
string_value:
{"id_": "d53ac7f1-2e1c-4858-a6c4-4e3525e08b27", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "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": "b0993f11-90fe-4402-bf4a-083ca2ae5305", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "549e307203cef7d1f2029dfe57b74301e3d3ad08a2e12448ae35cb86712f1f79", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ea28993c-eb77-4e11-b70b-a774a77f8610", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "82d1f8a85e390edf68555f50fff198d5c23a320167737d3d3f03873bf2f2a9df", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ad63b1fa-fcc4-4d61-946f-7c957a2ef9d2", "node_type": "1", "metadata": {}, "hash": "83b5b354a8895a2cde7b302aa1e69a9a9c7437598efeab6fb2a6d2c24fda27a2", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 24543, "end_char_idx": 26137, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
8%
    Epoch 13/30: test accuracy: 93.0% ± 1.9%
    Epoch 14/30: train accuracy: 93.9% ± 1.8%
    Epoch 14/30: test accuracy: 93.0% ± 1.9%
    Epoch 15/30: train accuracy: 94.2% ± 1.8%
    Epoch 15/30: test accuracy: 93.0% ± 1.9%
    Epoch 16/30: train accuracy: 94.2% ± 1.8%
    Epoch 16/30: test accuracy: 93.0% ± 1.9%
    Epoch 17/30: train accuracy: 94.3% ± 1.8%
    Epoch 17/30: test accuracy: 93.0% ± 1.9%
    Epoch 18/30: train accuracy: 94.5% ± 1.7%
    Epoch 18/30: test accuracy: 93.1% ± 1.9%
    Epoch 19/30: train accuracy: 94.5% ± 1.7%
    Epoch 19/30: test accuracy: 93.1% ± 1.9%
    Epoch 20/30: train accuracy: 94.6% ± 1.7%
    Epoch 20/30: test accuracy: 93.3% ± 1.9%
    Epoch 21/30: train accuracy: 94.8% ± 1.7%
    Epoch 21/30: test accuracy: 93.3% ± 1.9%
    Epoch 22/30: train accuracy: 94.8% ± 1.7%
    Epoch 22/30: test accuracy: 93.4% ± 1.9%
    Epoch 23/30: train accuracy: 94.8% ± 1.7%
    Epoch 23/30: test accuracy: 93.4% ± 1.9%
    Epoch 24/30: train accuracy: 94.8% ± 1.7%
    Epoch 24/30: test accuracy: 93.4% ± 1.9%
    Epoch 25/30: train accuracy: 94.8% ± 1.7%
    Epoch 25/30: test accuracy: 93.4% ± 1.9%
    Epoch 26/30: train accuracy: 94.9% ± 1.7%
    Epoch 26/30: test accuracy: 93.6% ± 1.9%
    Epoch 27/30: train accuracy: 94.9% ± 1.7%
    Epoch 27/30: test accuracy: 93.6% ± 1.9%
    Epoch 28/30: train accuracy: 94.9% ± 1.7%
    Epoch 28/30: test accuracy: 93.6% ± 1.9%
    Epoch 29/30: train accuracy: 95.1% ± 1.6%
    Epoch 29/30: test accuracy: 93.6% ± 1.9%
    Epoch 30/30: train accuracy: 95.1% ± 1.6%
    Epoch 30/30: test accuracy: 93.6% ± 1.9%


key: _node_content
string_value:
{"id_": "ad63b1fa-fcc4-4d61-946f-7c957a2ef9d2", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "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": "b0993f11-90fe-4402-bf4a-083ca2ae5305", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "549e307203cef7d1f2029dfe57b74301e3d3ad08a2e12448ae35cb86712f1f79", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d53ac7f1-2e1c-4858-a6c4-4e3525e08b27", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "3ffd0c6859bd221500079049c1c83976be9a24003cea256fae05c5b7a255e223", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8d1826f3-87c4-4440-b939-bb164c1b6ae3", "node_type": "1", "metadata": {}, "hash": "331a281f80f8f7f16f667e3db7575f60f3b11de9c94e1ea6e90d47dbba9446f1", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 25309, "end_char_idx": 27162, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
3% ± 1.9%
    Epoch 22/30: train accuracy: 94.8% ± 1.7%
    Epoch 22/30: test accuracy: 93.4% ± 1.9%
    Epoch 23/30: train accuracy: 94.8% ± 1.7%
    Epoch 23/30: test accuracy: 93.4% ± 1.9%
    Epoch 24/30: train accuracy: 94.8% ± 1.7%
    Epoch 24/30: test accuracy: 93.4% ± 1.9%
    Epoch 25/30: train accuracy: 94.8% ± 1.7%
    Epoch 25/30: test accuracy: 93.4% ± 1.9%
    Epoch 26/30: train accuracy: 94.9% ± 1.7%
    Epoch 26/30: test accuracy: 93.6% ± 1.9%
    Epoch 27/30: train accuracy: 94.9% ± 1.7%
    Epoch 27/30: test accuracy: 93.6% ± 1.9%
    Epoch 28/30: train accuracy: 94.9% ± 1.7%
    Epoch 28/30: test accuracy: 93.6% ± 1.9%
    Epoch 29/30: train accuracy: 95.1% ± 1.6%
    Epoch 29/30: test accuracy: 93.6% ± 1.9%
    Epoch 30/30: train accuracy: 95.1% ± 1.6%
    Epoch 30/30: test accuracy: 93.6% ± 1.9%



```python
runs_df = pd.concat(results)

# plot training loss and test loss over time
px.line(
    runs_df,
    line_group="run_id",
    x="epoch",
    y="loss",
    color="type",
    hover_data=["batch_size", "learning_rate", "dropout_fraction"],
    facet_row="learning_rate",
    facet_col="batch_size",
    width=500,
).show()

# plot accuracy over time
px.line(
    runs_df,
    line_group="run_id",
    x="epoch",
    y="accuracy",
    color="type",
    hover_data=["batch_size", "learning_rate", "dropout_fraction"],
    facet_row="learning_rate",
    facet_col="batch_size",
    width=500,
).show()

```





## 8. Plot the before & after, showing the results of the best matrix found during training

The better the matrix is, the more cleanly it will separate the similar and dissimilar pairs.


```python
# apply result of best run to original data
best_run = runs_df.sort_values(by="accuracy", ascending=False).iloc[0]
best_matrix = best_run["matrix"]
apply_matrix_to_embeddings_dataframe(best_matrix, df)

```


key: _node_content
string_value:
{"id_": "8d1826f3-87c4-4440-b939-bb164c1b6ae3", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "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": "b0993f11-90fe-4402-bf4a-083ca2ae5305", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "549e307203cef7d1f2029dfe57b74301e3d3ad08a2e12448ae35cb86712f1f79", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ad63b1fa-fcc4-4d61-946f-7c957a2ef9d2", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "7cec30b724ad2a76bd21c48ef75f6e9aead3bd4440e076012ce6e6232487413e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "399e4d7d-95da-4c33-a474-2e73d66867c1", "node_type": "1", "metadata": {}, "hash": "129840b964943852d050669f6e8682d9c804487de3d3eb61f04cfbc4ebdbd367", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 25855, "end_char_idx": 28060, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
6% ± 1.9%
    Epoch 28/30: train accuracy: 94.9% ± 1.7%
    Epoch 28/30: test accuracy: 93.6% ± 1.9%
    Epoch 29/30: train accuracy: 95.1% ± 1.6%
    Epoch 29/30: test accuracy: 93.6% ± 1.9%
    Epoch 30/30: train accuracy: 95.1% ± 1.6%
    Epoch 30/30: test accuracy: 93.6% ± 1.9%



```python
runs_df = pd.concat(results)

# plot training loss and test loss over time
px.line(
    runs_df,
    line_group="run_id",
    x="epoch",
    y="loss",
    color="type",
    hover_data=["batch_size", "learning_rate", "dropout_fraction"],
    facet_row="learning_rate",
    facet_col="batch_size",
    width=500,
).show()

# plot accuracy over time
px.line(
    runs_df,
    line_group="run_id",
    x="epoch",
    y="accuracy",
    color="type",
    hover_data=["batch_size", "learning_rate", "dropout_fraction"],
    facet_row="learning_rate",
    facet_col="batch_size",
    width=500,
).show()

```





## 8. Plot the before & after, showing the results of the best matrix found during training

The better the matrix is, the more cleanly it will separate the similar and dissimilar pairs.


```python
# apply result of best run to original data
best_run = runs_df.sort_values(by="accuracy", ascending=False).iloc[0]
best_matrix = best_run["matrix"]
apply_matrix_to_embeddings_dataframe(best_matrix, df)

```


```python
# plot similarity distribution BEFORE customization
px.histogram(
    df,
    x="cosine_similarity",
    color="label",
    barmode="overlay",
    width=500,
    facet_row="dataset",
).show()

test_df = df[df["dataset"] == "test"]
a, se = accuracy_and_se(test_df["cosine_similarity"], test_df["label"])
print(f"Test accuracy: {a:0.1%} ± {1.96 * se:0.1%}")

# plot similarity distribution AFTER customization
px.histogram(
    df,
    x="cosine_similarity_custom",
    color="label",
    barmode="overlay",
    width=500,
    facet_row="dataset",
).show()

a, se = accuracy_and_se(test_df["cosine_similarity_custom"], test_df["label"])
print(f"Test accuracy after customization: {a:0.1%} ± {1.96 * se:0.1%}")

```



    Test accuracy: 88.8% ± 2.4%




    Test accuracy after customization: 93.6% ± 1.9%



```python
best_matrix  # this is what you can multiply your embeddings by

```


key: _node_content
string_value:
{"id_": "399e4d7d-95da-4c33-a474-2e73d66867c1", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "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": "b0993f11-90fe-4402-bf4a-083ca2ae5305", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "549e307203cef7d1f2029dfe57b74301e3d3ad08a2e12448ae35cb86712f1f79", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8d1826f3-87c4-4440-b939-bb164c1b6ae3", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "350ab3dd651d7973e8923bdc8c8682d31536d5928907ec7f710572cd4716685a", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 26757, "end_char_idx": 28871, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
## 8. Plot the before & after, showing the results of the best matrix found during training

The better the matrix is, the more cleanly it will separate the similar and dissimilar pairs.


```python
# apply result of best run to original data
best_run = runs_df.sort_values(by="accuracy", ascending=False).iloc[0]
best_matrix = best_run["matrix"]
apply_matrix_to_embeddings_dataframe(best_matrix, df)

```


```python
# plot similarity distribution BEFORE customization
px.histogram(
    df,
    x="cosine_similarity",
    color="label",
    barmode="overlay",
    width=500,
    facet_row="dataset",
).show()

test_df = df[df["dataset"] == "test"]
a, se = accuracy_and_se(test_df["cosine_similarity"], test_df["label"])
print(f"Test accuracy: {a:0.1%} ± {1.96 * se:0.1%}")

# plot similarity distribution AFTER customization
px.histogram(
    df,
    x="cosine_similarity_custom",
    color="label",
    barmode="overlay",
    width=500,
    facet_row="dataset",
).show()

a, se = accuracy_and_se(test_df["cosine_similarity_custom"], test_df["label"])
print(f"Test accuracy after customization: {a:0.1%} ± {1.96 * se:0.1%}")

```



    Test accuracy: 88.8% ± 2.4%




    Test accuracy after customization: 93.6% ± 1.9%



```python
best_matrix  # this is what you can multiply your embeddings by

```




    array([[-1.2566795e+00, -1.5297449e+00, -1.3271648e-01, ...,
            -1.2859761e+00, -5.3254390e-01,  4.8364732e-01],
           [-1.4826347e+00,  9.2656955e-02, -4.2437232e-01, ...,
             1.1872858e+00, -1.0831847e+00, -1.0683593e+00],
           [-2.2029283e+00, -1.9703420e+00,  3.1125939e-01, ...,
             2.2947595e+00,  5.5780332e-03, -6.0171342e-01],
           ...,
           [-1.1019799e-01,  1.3599515e+00, -4.7677776e-01, ...,
             6.5626711e-01,  7.2359240e-01,  3.0733588e+00],
           [ 1.6624762e-03,  4.2648423e-01, -1.1380885e+00, ...,
             8.7202555e-01,  9.3173909e-01, -1.6760436e+00],
           [ 7.7449006e-01,  4.9213606e-01,  3.5407653e-01, ...,
             1.3460466e+00, -1.9509128e-01,  7.7514690e-01]], dtype=float32)




```python

```


key: _node_content
string_value:
{"id_": "3088bcd5-153b-49c3-ba87-4eecf5467fa3", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Get_embeddings_from_dataset.ipynb", "title": "Get embeddings from dataset", "tokens": 1039, "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": "1eb7d7ed-beb9-489b-9b75-4516934079cd", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Get_embeddings_from_dataset.ipynb", "title": "Get embeddings from dataset", "tokens": 1039, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "9a7830c7db452c931e18c560c402ad177bf637e78bdae472f47236cafa370b94", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e5900042-9631-43e9-940d-d97bad0eeda9", "node_type": "1", "metadata": {}, "hash": "846db94890969d02b511b6b0563485df3f45fcfc0e81948dad0f947efa431353", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 1585, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Get embeddings from dataset

This notebook gives an example on how to get embeddings from a large dataset.


## 1. Load the dataset

The dataset used in this example is [fine-food reviews](https://www.kaggle.com/snap/amazon-fine-food-reviews) from Amazon. The dataset contains a total of 568,454 food reviews Amazon users left up to October 2012. We will use a subset of this dataset, consisting of 1,000 most recent reviews for illustration purposes. The reviews are in English and tend to be positive or negative. Each review has a ProductId, UserId, Score, review title (Summary) and review body (Text).

We will combine the review summary and review text into a single combined text. The model will encode this combined text and it will output a single vector embedding.

To run this notebook, you will need to install: pandas, openai, transformers, plotly, matplotlib, scikit-learn, torch (transformer dep), torchvision, and scipy.


```python
import pandas as pd
import tiktoken

from utils.embeddings_utils import get_embedding
```


```python
embedding_model = "text-embedding-3-small"
embedding_encoding = "cl100k_base"
max_tokens = 8000  # the maximum for text-embedding-3-small is 8191
```


```python
# load & inspect dataset
input_datapath = "data/fine_food_reviews_1k.csv"  # to save space, we provide a pre-filtered dataset
df = pd.read_csv(input_datapath, index_col=0)
df = df[["Time", "ProductId", "UserId", "Score", "Summary", "Text"]]
df = df.dropna()
df["combined"] = (
    "Title: " + df.Summary.str.strip() + "; Content: " + df.Text.str.strip()
)
df.head(2)
```


key: _node_content
string_value:
{"id_": "e5900042-9631-43e9-940d-d97bad0eeda9", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Get_embeddings_from_dataset.ipynb", "title": "Get embeddings from dataset", "tokens": 1039, "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": "1eb7d7ed-beb9-489b-9b75-4516934079cd", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Get_embeddings_from_dataset.ipynb", "title": "Get embeddings from dataset", "tokens": 1039, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "9a7830c7db452c931e18c560c402ad177bf637e78bdae472f47236cafa370b94", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3088bcd5-153b-49c3-ba87-4eecf5467fa3", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Get_embeddings_from_dataset.ipynb", "title": "Get embeddings from dataset", "tokens": 1039, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "930d0b4f241e38b45e22fc2b21db85491cc98c89c022db5fd202ed11157a7f1e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "578940bb-266d-48de-b2ff-bbb3427b2a97", "node_type": "1", "metadata": {}, "hash": "4aab987284a9b930ef5bcf5c4684f53c7a0f43edcb39020b2294aefd9f02f97b", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2764, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Get embeddings from dataset

This notebook gives an example on how to get embeddings from a large dataset.


## 1. Load the dataset

The dataset used in this example is [fine-food reviews](https://www.kaggle.com/snap/amazon-fine-food-reviews) from Amazon. The dataset contains a total of 568,454 food reviews Amazon users left up to October 2012. We will use a subset of this dataset, consisting of 1,000 most recent reviews for illustration purposes. The reviews are in English and tend to be positive or negative. Each review has a ProductId, UserId, Score, review title (Summary) and review body (Text).

We will combine the review summary and review text into a single combined text. The model will encode this combined text and it will output a single vector embedding.

To run this notebook, you will need to install: pandas, openai, transformers, plotly, matplotlib, scikit-learn, torch (transformer dep), torchvision, and scipy.


```python
import pandas as pd
import tiktoken

from utils.embeddings_utils import get_embedding
```


```python
embedding_model = "text-embedding-3-small"
embedding_encoding = "cl100k_base"
max_tokens = 8000  # the maximum for text-embedding-3-small is 8191
```


```python
# load & inspect dataset
input_datapath = "data/fine_food_reviews_1k.csv"  # to save space, we provide a pre-filtered dataset
df = pd.read_csv(input_datapath, index_col=0)
df = df[["Time", "ProductId", "UserId", "Score", "Summary", "Text"]]
df = df.dropna()
df["combined"] = (
    "Title: " + df.Summary.str.strip() + "; Content: " + df.Text.str.strip()
)
df.head(2)
```




<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>Time</th>
      <th>ProductId</th>
      <th>UserId</th>
      <th>Score</th>
      <th>Summary</th>
      <th>Text</th>
      <th>combined</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>1351123200</td>
      <td>B003XPF9BO</td>
      <td>A3R7JR3FMEBXQB</td>
      <td>5</td>
      <td>where does one  start...and stop... with a tre...</td>
      <td>Wanted to save some to bring to my Chicago fam...</td>
      <td>Title: where does one  start...and stop... wit...</td>
    </tr>
    <tr>
      <th>1</th>
      <td>1351123200</td>
      <td>B003JK537S</td>
      <td>A3JBPC3WFUT5ZP</td>
      <td>1</td>
      <td>Arrived in pieces</td>
      <td>Not pleased at all. When I opened the box, mos...</td>
      <td>Title: Arrived in pieces; Content: Not pleased...</td>
    </tr>
  </tbody>
</table>
</div>


key: _node_content
string_value:
{"id_": "578940bb-266d-48de-b2ff-bbb3427b2a97", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Get_embeddings_from_dataset.ipynb", "title": "Get embeddings from dataset", "tokens": 1039, "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": "1eb7d7ed-beb9-489b-9b75-4516934079cd", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Get_embeddings_from_dataset.ipynb", "title": "Get embeddings from dataset", "tokens": 1039, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "9a7830c7db452c931e18c560c402ad177bf637e78bdae472f47236cafa370b94", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e5900042-9631-43e9-940d-d97bad0eeda9", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Get_embeddings_from_dataset.ipynb", "title": "Get embeddings from dataset", "tokens": 1039, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "3942fa4bb7413a54af2896ae8e7fa1f5648e9e301b2d65960c7abcd5c058bc67", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1590, "end_char_idx": 3694, "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>Time</th>
      <th>ProductId</th>
      <th>UserId</th>
      <th>Score</th>
      <th>Summary</th>
      <th>Text</th>
      <th>combined</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>1351123200</td>
      <td>B003XPF9BO</td>
      <td>A3R7JR3FMEBXQB</td>
      <td>5</td>
      <td>where does one  start...and stop... with a tre...</td>
      <td>Wanted to save some to bring to my Chicago fam...</td>
      <td>Title: where does one  start...and stop... wit...</td>
    </tr>
    <tr>
      <th>1</th>
      <td>1351123200</td>
      <td>B003JK537S</td>
      <td>A3JBPC3WFUT5ZP</td>
      <td>1</td>
      <td>Arrived in pieces</td>
      <td>Not pleased at all. When I opened the box, mos...</td>
      <td>Title: Arrived in pieces; Content: Not pleased...</td>
    </tr>
  </tbody>
</table>
</div>




```python
# subsample to 1k most recent reviews and remove samples that are too long
top_n = 1000
df = df.sort_values("Time").tail(top_n * 2)  # first cut to first 2k entries, assuming less than half will be filtered out
df.drop("Time", axis=1, inplace=True)

encoding = tiktoken.get_encoding(embedding_encoding)

# omit reviews that are too long to embed
df["n_tokens"] = df.combined.apply(lambda x: len(encoding.encode(x)))
df = df[df.n_tokens <= max_tokens].tail(top_n)
len(df)
```




    1000



## 2. Get embeddings and save them for future reuse


```python
# Ensure you have your API key set in your environment per the README: https://github.com/openai/openai-python#usage

# This may take a few minutes
df["embedding"] = df.combined.apply(lambda x: get_embedding(x, model=embedding_model))
df.to_csv("data/fine_food_reviews_with_embeddings_1k.csv")
```


```python
a = get_embedding("hi", model=embedding_model)
```


key: _node_content
string_value:
{"id_": "91057cd2-5b2f-4828-a02e-255904732b30", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "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": "4d4d7d64-2cb7-4b25-9a6b-4e1da7aa137e", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "036d236287213f8976a11b4008fcdf7dddb41333fc2b788b4a87761c459d8924", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "514878c6-0e07-45a4-9a93-2195831c198e", "node_type": "1", "metadata": {}, "hash": "35728e63cdd5b2305dcccd2a26134c575d0591fecbb6474b2eb63040d81a3ab2", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3340, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# How to handle rate limits

When you call the OpenAI API repeatedly, you may encounter error messages that say `429: 'Too Many Requests'` or `RateLimitError`. These error messages come from exceeding the API's rate limits.

This guide shares tips for avoiding and handling rate limit errors.

To see an example script for throttling parallel requests to avoid rate limit errors, see [api_request_parallel_processor.py](https://github.com/openai/openai-cookbook/blob/main/examples/api_request_parallel_processor.py).

## Why rate limits exist

Rate limits are a common practice for APIs, and they're put in place for a few different reasons.

- First, they help protect against abuse or misuse of the API. For example, a malicious actor could flood the API with requests in an attempt to overload it or cause disruptions in service. By setting rate limits, OpenAI can prevent this kind of activity.
- Second, rate limits help ensure that everyone has fair access to the API. If one person or organization makes an excessive number of requests, it could bog down the API for everyone else. By throttling the number of requests that a single user can make, OpenAI ensures that everyone has an opportunity to use the API without experiencing slowdowns.
- Lastly, rate limits can help OpenAI manage the aggregate load on its infrastructure. If requests to the API increase dramatically, it could tax the servers and cause performance issues. By setting rate limits, OpenAI can help maintain a smooth and consistent experience for all users.

Although hitting rate limits can be frustrating, rate limits exist to protect the reliable operation of the API for its users.

## Default rate limits

Your rate limit and spending limit (quota) are automatically adjusted based on a number of factors. As your usage of the OpenAI API goes up and you successfully pay the bill, we automatically increase your usage tier. You can find specific information regarding rate limits using the resources below.

### Other rate limit resources

Read more about OpenAI's rate limits in these other resources:

- [Guide: Rate limits](https://platform.openai.com/docs/guides/rate-limits?context=tier-free)
- [Help Center: Is API usage subject to any rate limits?](https://help.openai.com/en/articles/5955598-is-api-usage-subject-to-any-rate-limits)
- [Help Center: How can I solve 429: 'Too Many Requests' errors?](https://help.openai.com/en/articles/5955604-how-can-i-solve-429-too-many-requests-errors)

### Requesting a rate limit increase

If you'd like your organization's rate limit increased, please visit your [Limits settings page](https://platform.openai.com/account/limits) to see how you can increase your usage tier



```python
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>"))
```

## Example rate limit error

A rate limit error will occur when API requests are sent too quickly. If using the OpenAI Python library, they will look something like:

```
RateLimitError: Rate limit reached for default-codex in organization org-{id} on requests per min. Limit: 20.000000 / min. Current: 24.000000 / min. Contact support@openai.com if you continue to have issues or if you’d like to request an increase.
```

Below is example code for triggering a rate limit error.


key: _node_content
string_value:
{"id_": "514878c6-0e07-45a4-9a93-2195831c198e", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "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": "4d4d7d64-2cb7-4b25-9a6b-4e1da7aa137e", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "036d236287213f8976a11b4008fcdf7dddb41333fc2b788b4a87761c459d8924", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "91057cd2-5b2f-4828-a02e-255904732b30", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "51224371f0f56b00b3dd6d78adc961ad2f12f6ec9d5365093e64a23ce5899252", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2dfc3bea-2564-4b0b-b12a-5a7e70fb0ef5", "node_type": "1", "metadata": {}, "hash": "9b6983d9c479972d804521dedbdfb4111e4acb446dea7d958ff0b908de43e817", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2708, "end_char_idx": 5921, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
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>"))
```

## Example rate limit error

A rate limit error will occur when API requests are sent too quickly. If using the OpenAI Python library, they will look something like:

```
RateLimitError: Rate limit reached for default-codex in organization org-{id} on requests per min. Limit: 20.000000 / min. Current: 24.000000 / min. Contact support@openai.com if you continue to have issues or if you’d like to request an increase.
```

Below is example code for triggering a rate limit error.


```python
# request a bunch of completions in a loop
for _ in range(100):
    client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": "Hello"}],
        max_tokens=10,
    )
```

## How to avoid rate limit errors

### Retrying with exponential backoff

One easy way to avoid rate limit errors is to automatically retry requests with a random exponential backoff. Retrying with exponential backoff means performing a short sleep when a rate limit error is hit, then retrying the unsuccessful request. If the request is still unsuccessful, the sleep length is increased and the process is repeated. This continues until the request is successful or until a maximum number of retries is reached.

This approach has many benefits:

- Automatic retries means you can recover from rate limit errors without crashes or missing data
- Exponential backoff means that your first retries can be tried quickly, while still benefiting from longer delays if your first few retries fail
- Adding random jitter to the delay helps retries from all hitting at the same time

Note that unsuccessful requests contribute to your per-minute limit, so continuously resending a request won’t work.

Below are a few example solutions.

#### Example #1: Using the Tenacity library

[Tenacity](https://tenacity.readthedocs.io/en/latest/) is an Apache 2.0 licensed general-purpose retrying library, written in Python, to simplify the task of adding retry behavior to just about anything.

To add exponential backoff to your requests, you can use the `tenacity.retry` [decorator](https://peps.python.org/pep-0318/). The following example uses the `tenacity.wait_random_exponential` function to add random exponential backoff to a request.

Note that the Tenacity library is a third-party tool, and OpenAI makes no guarantees about its reliability or security.


```python
from tenacity import (
    retry,
    stop_after_attempt,
    wait_random_exponential,
)  # for exponential backoff

@retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6))
def completion_with_backoff(**kwargs):
    return client.chat.completions.create(**kwargs)


completion_with_backoff(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Once upon a time,"}])
```




    ChatCompletion(id='chatcmpl-8PAu6anX2JxQdYmJRzps38R8u0ZBC', choices=[Choice(finish_reason='stop', index=0, message=ChatCompletionMessage(content='in a small village nestled among green fields and rolling hills, there lived a kind-hearted and curious young girl named Lily.


key: _node_content
string_value:
{"id_": "2dfc3bea-2564-4b0b-b12a-5a7e70fb0ef5", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "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": "4d4d7d64-2cb7-4b25-9a6b-4e1da7aa137e", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "036d236287213f8976a11b4008fcdf7dddb41333fc2b788b4a87761c459d8924", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "514878c6-0e07-45a4-9a93-2195831c198e", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "89124b315794c69c5a2fe1d0e5c4f7dba138e9fc528f81fde33985760c1af017", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d471255b-b3a4-4650-8308-438b876ae0bd", "node_type": "1", "metadata": {}, "hash": "9fe11423660d31ddac67a28aa64dbd5bf5e5e8f76bfe4e852ecef2dae0e6f0ad", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5229, "end_char_idx": 8557, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
from tenacity import (
    retry,
    stop_after_attempt,
    wait_random_exponential,
)  # for exponential backoff

@retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6))
def completion_with_backoff(**kwargs):
    return client.chat.completions.create(**kwargs)


completion_with_backoff(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Once upon a time,"}])
```




    ChatCompletion(id='chatcmpl-8PAu6anX2JxQdYmJRzps38R8u0ZBC', choices=[Choice(finish_reason='stop', index=0, message=ChatCompletionMessage(content='in a small village nestled among green fields and rolling hills, there lived a kind-hearted and curious young girl named Lily. Lily was known for her bright smile and infectious laughter, bringing joy to everyone around her.\n\nOne sunny morning, as Lily played in the meadows, she stumbled upon a mysterious book tucked away beneath a tall oak tree. Intrigued, she picked it up and dusted off its weathered cover to reveal intricate golden patterns. Without hesitation, she opened it, discovering that its pages were filled with magical tales and enchanting adventures.\n\nAmong the stories she found, one particularly caught her attention—a tale of a long-lost treasure hidden deep within a mysterious forest. Legend had it that whoever found this hidden treasure would be granted one wish, no matter how big or small. Excited by the prospect of finding such treasure and fulfilling her wildest dreams, Lily decided to embark on a thrilling journey to the forest.\n\nGathering her courage, Lily told her parents about the magical book and her quest to find the hidden treasure. Though concerned for their daughter\'s safety, they couldn\'t help but admire her spirit and determination. They hugged her tightly and blessed her with love and luck, promising to await her return.\n\nEquipped with a map she found within the book, Lily ventured into the depths of the thick forest. The trees whispered tales of forgotten secrets, and the enchanted creatures hidden within watched her every step. But Lily remained undeterred, driven by her desire to discover what lay ahead.\n\nDays turned into weeks as Lily traversed through dense foliage, crossed swift rivers, and climbed treacherous mountains. She encountered mystical beings who offered guidance and protection along her perilous journey. With their help, she overcame countless obstacles and grew braver with each passing day.\n\nFinally, after what felt like an eternity, Lily reached the heart of the forest. There, beneath a jeweled waterfall, she found the long-lost treasure—a magnificent chest adorned with sparkling gemstones. Overwhelmed with excitement, she gently opened the chest to reveal a brilliant light that illuminated the forest.\n\nWithin the glow, a wise voice echoed, "You have proven your courage and pure heart, young Lily. Make your wish, and it shall be granted."\n\nLily thought deeply about her wish, realizing that her true treasure was the love and happiness she felt in her heart. Instead of making a wish for herself, she asked for the wellbeing and prosperity of her village, spreading joy and harmony to everyone living there.\n\nAs the light faded, Lily knew her quest was complete. She retraced her steps through the forest, returning home to find her village flourishing.


key: _node_content
string_value:
{"id_": "d471255b-b3a4-4650-8308-438b876ae0bd", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "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": "4d4d7d64-2cb7-4b25-9a6b-4e1da7aa137e", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "036d236287213f8976a11b4008fcdf7dddb41333fc2b788b4a87761c459d8924", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2dfc3bea-2564-4b0b-b12a-5a7e70fb0ef5", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "28ad74ef49524bb6dbe616e65e325b1e9383ed8ad586617fe3cd6f9941a2ccfc", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "140ffc6c-fd94-4bf4-ada7-d6980ffada85", "node_type": "1", "metadata": {}, "hash": "bf4efd6c34417f98e9b916b0076e7aa24fad6bfe439826b58fa66fadee359a92", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 6875, "end_char_idx": 9966, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Though concerned for their daughter\'s safety, they couldn\'t help but admire her spirit and determination. They hugged her tightly and blessed her with love and luck, promising to await her return.\n\nEquipped with a map she found within the book, Lily ventured into the depths of the thick forest. The trees whispered tales of forgotten secrets, and the enchanted creatures hidden within watched her every step. But Lily remained undeterred, driven by her desire to discover what lay ahead.\n\nDays turned into weeks as Lily traversed through dense foliage, crossed swift rivers, and climbed treacherous mountains. She encountered mystical beings who offered guidance and protection along her perilous journey. With their help, she overcame countless obstacles and grew braver with each passing day.\n\nFinally, after what felt like an eternity, Lily reached the heart of the forest. There, beneath a jeweled waterfall, she found the long-lost treasure—a magnificent chest adorned with sparkling gemstones. Overwhelmed with excitement, she gently opened the chest to reveal a brilliant light that illuminated the forest.\n\nWithin the glow, a wise voice echoed, "You have proven your courage and pure heart, young Lily. Make your wish, and it shall be granted."\n\nLily thought deeply about her wish, realizing that her true treasure was the love and happiness she felt in her heart. Instead of making a wish for herself, she asked for the wellbeing and prosperity of her village, spreading joy and harmony to everyone living there.\n\nAs the light faded, Lily knew her quest was complete. She retraced her steps through the forest, returning home to find her village flourishing. Fields bloomed with vibrant flowers, and laughter filled the air.\n\nThe villagers greeted Lily with open arms, recognizing her selflessness and the magic she had brought into their lives. From that day forward, they told the tale of Lily\'s journey, celebrating her as a heroine who embodied the power of love, kindness, and the belief that true treasure lies within oneself.\n\nAnd so, the story of Lily became an everlasting legend, inspiring generations to follow their dreams, be selfless, and find the true treasures that lie within their hearts.', role='assistant', function_call=None, tool_calls=None))], created=1701010806, model='gpt-3.5-turbo-0613', object='chat.completion', system_fingerprint=None, usage=CompletionUsage(completion_tokens=641, prompt_tokens=12, total_tokens=653))



#### Example #2: Using the backoff library

Another library that provides function decorators for backoff and retry is [backoff](https://pypi.org/project/backoff/).

Like Tenacity, the backoff library is a third-party tool, and OpenAI makes no guarantees about its reliability or security.


```python
import backoff  # for exponential backoff

@backoff.on_exception(backoff.expo, openai.RateLimitError)
def completions_with_backoff(**kwargs):
    return client.chat.completions.create(**kwargs)


completions_with_backoff(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Once upon a time,"}])

```


key: _node_content
string_value:
{"id_": "140ffc6c-fd94-4bf4-ada7-d6980ffada85", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "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": "4d4d7d64-2cb7-4b25-9a6b-4e1da7aa137e", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "036d236287213f8976a11b4008fcdf7dddb41333fc2b788b4a87761c459d8924", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d471255b-b3a4-4650-8308-438b876ae0bd", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "0872bff03f1f0b8ab41898836f997387fe1f4f603f53bf92ddc715586d665d3a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "70060bf2-df49-4dc9-a24d-194a3e7e9789", "node_type": "1", "metadata": {}, "hash": "537d34ecc6186471d0c52531761f49a5b68e23ca3e918f1350f155dcd6cf1603", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 8261, "end_char_idx": 13467, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Instead of making a wish for herself, she asked for the wellbeing and prosperity of her village, spreading joy and harmony to everyone living there.\n\nAs the light faded, Lily knew her quest was complete. She retraced her steps through the forest, returning home to find her village flourishing. Fields bloomed with vibrant flowers, and laughter filled the air.\n\nThe villagers greeted Lily with open arms, recognizing her selflessness and the magic she had brought into their lives. From that day forward, they told the tale of Lily\'s journey, celebrating her as a heroine who embodied the power of love, kindness, and the belief that true treasure lies within oneself.\n\nAnd so, the story of Lily became an everlasting legend, inspiring generations to follow their dreams, be selfless, and find the true treasures that lie within their hearts.', role='assistant', function_call=None, tool_calls=None))], created=1701010806, model='gpt-3.5-turbo-0613', object='chat.completion', system_fingerprint=None, usage=CompletionUsage(completion_tokens=641, prompt_tokens=12, total_tokens=653))



#### Example #2: Using the backoff library

Another library that provides function decorators for backoff and retry is [backoff](https://pypi.org/project/backoff/).

Like Tenacity, the backoff library is a third-party tool, and OpenAI makes no guarantees about its reliability or security.


```python
import backoff  # for exponential backoff

@backoff.on_exception(backoff.expo, openai.RateLimitError)
def completions_with_backoff(**kwargs):
    return client.chat.completions.create(**kwargs)


completions_with_backoff(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Once upon a time,"}])

```




    ChatCompletion(id='chatcmpl-8PAwkg7Q9pPeAkvVuAZ8AyA108WhR', choices=[Choice(finish_reason='stop', index=0, message=ChatCompletionMessage(content="in a small village, there lived a young girl named Lily. She had fiery red hair, lively green eyes, and a spirit as wild as the rushing river nearby. Lily was known for her curious nature and her desire to explore the world beyond the village boundaries.\n\nOne day, while playing near the river, Lily spotted an injured bird nested on a branch. Its wing was broken, and it seemed unable to fly away. Lily's heart filled with sadness, and she knew she couldn't leave the bird alone.\n\nCarefully, she climbed up the tree and gently placed the bird inside her pocket. Lily brought it home and made a cozy bed for it in a small wooden box. She named the bird Ruby, after its shimmering red feathers.\n\nDays turned into weeks, and Ruby's wing slowly healed under Lily's constant care and attention. As they spent time together, a deep bond grew between them. Ruby would chirp happily whenever Lily approached, and she would spend hours talking to the bird, sharing stories of her adventures, dreams, and fears.\n\nOne evening, as Lily was about to go to bed, a peculiar thing happened. Ruby hopped out of his box and fluttered onto the windowsill. He turned to face Lily with his bright eyes and began to sing a beautiful melody.\n\nLily was astonished. Never before had she heard Ruby sing. The tune was so captivating that it filled the room and made the quiet night come alive. The magical music seemed to touch Lily's soul, awakening a deep sense of wonder and wanderlust within her.\n\nFilled with an undeniable urge to explore, Lily decided it was time to go on an adventure with her newfound friend, Ruby. She packed a small bag and bid farewell to her family and friends, promising to return one day.\n\nTogether, Lily and Ruby embarked on a grand journey, soaring across expansive skies, diving into lush forests, and exploring hidden caves. They encountered magnificent landscapes, unique creatures, and encountered kind-hearted individuals who shared their wisdom and stories.\n\nThroughout their journey, Ruby's song continued to inspire and guide them. It became a symbol of hope, reminding them to embrace bravery, follow their dreams, and always remain true to themselves.\n\nAs the years passed, Lily and Ruby traversed the world, weaving their stories into the tapestry of time. They became renowned for their extraordinary bond and the magic they shared with everyone they encountered.\n\nEventually, it was time for Lily to return to her village, a place eagerly awaiting her return. She had grown wise, learned many lessons, and gained a deeper understanding of herself and the world around her.\n\nWith Ruby perched on her shoulder, they descended upon the village like a ray of sunshine, bringing joy and wonder to every heart. Lily shared the wisdom she had acquired and inspired others to embrace their own adventures, no matter how big or small.\n\nAnd so, the tale of Lily and Ruby became legend, passed down from generation to generation. Their story reminded people to cherish the connections they make, to nurture their dreams, and to believe in the magic that lies within them.", role='assistant', function_call=None, tool_calls=None))], created=1701010970, model='gpt-3.5-turbo-0613', object='chat.completion', system_fingerprint=None, usage=CompletionUsage(completion_tokens=621, prompt_tokens=12, total_tokens=633))


key: _node_content
string_value:
{"id_": "70060bf2-df49-4dc9-a24d-194a3e7e9789", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "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": "4d4d7d64-2cb7-4b25-9a6b-4e1da7aa137e", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "036d236287213f8976a11b4008fcdf7dddb41333fc2b788b4a87761c459d8924", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "140ffc6c-fd94-4bf4-ada7-d6980ffada85", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "52c77e36eedeeb3232a4ef1c6f641208dde64478af4514067176b5cf0a65ad7b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4d8546b7-7cab-4367-8891-90b740627e2b", "node_type": "1", "metadata": {}, "hash": "7267226ee460535ff9c9811b0eae4e6c60e8321cff1587ee8915312e2858dc7f", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 13471, "end_char_idx": 16703, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
#### Example 3: Manual backoff implementation

If you don't want to use third-party libraries, you can implement your own backoff logic.


```python
# imports
import random
import time

# define a retry decorator
def retry_with_exponential_backoff(
    func,
    initial_delay: float = 1,
    exponential_base: float = 2,
    jitter: bool = True,
    max_retries: int = 10,
    errors: tuple = (openai.RateLimitError,),
):
    """Retry a function with exponential backoff."""

    def wrapper(*args, **kwargs):
        # Initialize variables
        num_retries = 0
        delay = initial_delay

        # Loop until a successful response or max_retries is hit or an exception is raised
        while True:
            try:
                return func(*args, **kwargs)

            # Retry on specified errors
            except errors as e:
                # Increment retries
                num_retries += 1

                # Check if max retries has been reached
                if num_retries > max_retries:
                    raise Exception(
                        f"Maximum number of retries ({max_retries}) exceeded."
                    )

                # Increment the delay
                delay *= exponential_base * (1 + jitter * random.random())

                # Sleep for the delay
                time.sleep(delay)

            # Raise exceptions for any errors not specified
            except Exception as e:
                raise e

    return wrapper


@retry_with_exponential_backoff
def completions_with_backoff(**kwargs):
    return client.chat.completions.create(**kwargs)


completions_with_backoff(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Once upon a time,"}])
```




    ChatCompletion(id='chatcmpl-8PAxGvV3GbLpnOoKSvJ00XCUdOglM', choices=[Choice(finish_reason='stop', index=0, message=ChatCompletionMessage(content="in a faraway kingdom, there lived a young princess named Aurora. She was known for her beauty, grace, and kind heart. Aurora's kingdom was filled with lush green meadows, towering mountains, and sparkling rivers. The princess loved spending time exploring the enchanting forests surrounding her castle.\n\nOne day, while Aurora was wandering through the woods, she stumbled upon a hidden clearing. At the center stood a majestic oak tree, its branches reaching towards the sky. Aurora approached the tree with curiosity, and as she got closer, she noticed a small door at its base.\n\nIntrigued, she gently pushed open the door and was amazed to find herself in a magical realm. The forest transformed into a breathtaking wonderland, with colorful flowers blooming in every direction and woodland creatures frolicking joyously. Aurora's eyes widened with wonder as she explored this extraordinary world.\n\nAs she explored further, Aurora came across a small cottage in the distance. Curiosity overcame her, and she cautiously approached the cottage. To her surprise, an elderly woman with twinkling eyes and a warm smile stood in the doorway, welcoming her inside.\n\nThe woman revealed herself to be a fairy named Luna. Luna informed Aurora that she had been chosen to undertake a quest that would bring harmony to both her kingdom and the mystical realm.


key: _node_content
string_value:
{"id_": "4d8546b7-7cab-4367-8891-90b740627e2b", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "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": "4d4d7d64-2cb7-4b25-9a6b-4e1da7aa137e", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "036d236287213f8976a11b4008fcdf7dddb41333fc2b788b4a87761c459d8924", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "70060bf2-df49-4dc9-a24d-194a3e7e9789", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "fab9dee8c9e72152a02c97123ade88105bbe4fe8a4a54b4ab058380dcaf739cc", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c1bc8e14-1292-4cf3-a12d-00caf6e7dd2e", "node_type": "1", "metadata": {}, "hash": "64b108d9d8feb330c4d84724a0f79c593ae5f53329717247ca8408646192eb2c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 15079, "end_char_idx": 18425, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
completions_with_backoff(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Once upon a time,"}])
```




    ChatCompletion(id='chatcmpl-8PAxGvV3GbLpnOoKSvJ00XCUdOglM', choices=[Choice(finish_reason='stop', index=0, message=ChatCompletionMessage(content="in a faraway kingdom, there lived a young princess named Aurora. She was known for her beauty, grace, and kind heart. Aurora's kingdom was filled with lush green meadows, towering mountains, and sparkling rivers. The princess loved spending time exploring the enchanting forests surrounding her castle.\n\nOne day, while Aurora was wandering through the woods, she stumbled upon a hidden clearing. At the center stood a majestic oak tree, its branches reaching towards the sky. Aurora approached the tree with curiosity, and as she got closer, she noticed a small door at its base.\n\nIntrigued, she gently pushed open the door and was amazed to find herself in a magical realm. The forest transformed into a breathtaking wonderland, with colorful flowers blooming in every direction and woodland creatures frolicking joyously. Aurora's eyes widened with wonder as she explored this extraordinary world.\n\nAs she explored further, Aurora came across a small cottage in the distance. Curiosity overcame her, and she cautiously approached the cottage. To her surprise, an elderly woman with twinkling eyes and a warm smile stood in the doorway, welcoming her inside.\n\nThe woman revealed herself to be a fairy named Luna. Luna informed Aurora that she had been chosen to undertake a quest that would bring harmony to both her kingdom and the mystical realm. Aurora, eager to help, listened intently as Luna explained that a powerful enchantress had cast a spell on the kingdom, causing darkness and despair to loom over the land.\n\nTo break the curse, Aurora had to embark on a journey to retrieve a magical crystal hidden deep within the heart of an ancient cave. Without hesitation, the princess agreed and bid farewell to Luna, promising to return victorious.\n\nWith newfound determination, Aurora set off on her quest. Along the way, she encountered numerous challenges and obstacles but never lost hope. She often drew strength from the enchanting woodland creatures who accompanied her on this journey, reminding her that she was not alone.\n\nAfter a long and arduous journey, Aurora reached the entrance of the ancient cave. Inside, she faced a series of tests that pushed her physical and emotional limits. With sheer determination and unwavering courage, she overcame each trial, paving her way to the crystal's resting place.\n\nAs Aurora held the crystal in her hands, its warmth spread through her body. The artifact contained unimaginable power that could shatter the enchantress's curse and restore light to her kingdom. Brimming with joy and newfound strength, she made her way back to Luna's cottage.\n\nUpon her return, Aurora and Luna performed a powerful ritual, using the crystal's magic to break the curse. Waves of light and color spread across the kingdom, banishing darkness and despair. The once-gray skies turned blue, and laughter filled the air once again. The kingdom rejoiced, thanking Princess Aurora for her bravery and selflessness.\n\nFrom that day forward, Aurora was hailed as a hero, not only in her kingdom but also in the mystical realm.


key: _node_content
string_value:
{"id_": "c1bc8e14-1292-4cf3-a12d-00caf6e7dd2e", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "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": "4d4d7d64-2cb7-4b25-9a6b-4e1da7aa137e", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "036d236287213f8976a11b4008fcdf7dddb41333fc2b788b4a87761c459d8924", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4d8546b7-7cab-4367-8891-90b740627e2b", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "a30b55668ae2844cd363cddb8cc54ef1f0a11a01fe3c4178a1d242788f2042e3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "63c6a8a9-c008-409b-adf0-5800ec153f59", "node_type": "1", "metadata": {}, "hash": "f1fe2b7959918290beee8a6c208d1372a0f1923ce07809a92b8da5047de3fa3f", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 16568, "end_char_idx": 20023, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Luna informed Aurora that she had been chosen to undertake a quest that would bring harmony to both her kingdom and the mystical realm. Aurora, eager to help, listened intently as Luna explained that a powerful enchantress had cast a spell on the kingdom, causing darkness and despair to loom over the land.\n\nTo break the curse, Aurora had to embark on a journey to retrieve a magical crystal hidden deep within the heart of an ancient cave. Without hesitation, the princess agreed and bid farewell to Luna, promising to return victorious.\n\nWith newfound determination, Aurora set off on her quest. Along the way, she encountered numerous challenges and obstacles but never lost hope. She often drew strength from the enchanting woodland creatures who accompanied her on this journey, reminding her that she was not alone.\n\nAfter a long and arduous journey, Aurora reached the entrance of the ancient cave. Inside, she faced a series of tests that pushed her physical and emotional limits. With sheer determination and unwavering courage, she overcame each trial, paving her way to the crystal's resting place.\n\nAs Aurora held the crystal in her hands, its warmth spread through her body. The artifact contained unimaginable power that could shatter the enchantress's curse and restore light to her kingdom. Brimming with joy and newfound strength, she made her way back to Luna's cottage.\n\nUpon her return, Aurora and Luna performed a powerful ritual, using the crystal's magic to break the curse. Waves of light and color spread across the kingdom, banishing darkness and despair. The once-gray skies turned blue, and laughter filled the air once again. The kingdom rejoiced, thanking Princess Aurora for her bravery and selflessness.\n\nFrom that day forward, Aurora was hailed as a hero, not only in her kingdom but also in the mystical realm. She continued to be a beacon of hope and kindness, reminding everyone that true courage lies within, waiting to be awakened.\n\nAnd so, Princess Aurora's tale lived on as a timeless reminder that even in the darkest of times, there is always light and hope to be found.", role='assistant', function_call=None, tool_calls=None))], created=1701011002, model='gpt-3.5-turbo-0613', object='chat.completion', system_fingerprint=None, usage=CompletionUsage(completion_tokens=657, prompt_tokens=12, total_tokens=669))



## How to maximize throughput of batch processing given rate limits

If you're processing real-time requests from users, backoff and retry is a great strategy to minimize latency while avoiding rate limit errors.

However, if you're processing large volumes of batch data, where throughput matters more than latency, there are a few other things you can do in addition to backoff and retry.

### Proactively adding delay between requests

If you are constantly hitting the rate limit, then backing off, then hitting the rate limit again, then backing off again, it's possible that a good fraction of your request budget will be 'wasted' on requests that need to be retried. This limits your processing throughput, given a fixed rate limit.

Here, one potential solution is to calculate your rate limit and add a delay equal to its reciprocal (e.g., if your rate limit 20 requests per minute, add a delay of 3–6 seconds to each request). This can help you operate near the rate limit ceiling without hitting it and incurring wasted requests.

#### Example of adding delay to a request


key: _node_content
string_value:
{"id_": "63c6a8a9-c008-409b-adf0-5800ec153f59", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "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": "4d4d7d64-2cb7-4b25-9a6b-4e1da7aa137e", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "036d236287213f8976a11b4008fcdf7dddb41333fc2b788b4a87761c459d8924", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c1bc8e14-1292-4cf3-a12d-00caf6e7dd2e", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "6967d8008593747a548d228ea32b0609dfa507809c216d9a9f55a8b4b2264065", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "fa010693-9ca8-41e9-be48-6d36fab0533d", "node_type": "1", "metadata": {}, "hash": "fedecaa6618c0f18aaf11abe09af9f01e562209cb03667c099a57553da69eed6", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 18234, "end_char_idx": 20669, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The kingdom rejoiced, thanking Princess Aurora for her bravery and selflessness.\n\nFrom that day forward, Aurora was hailed as a hero, not only in her kingdom but also in the mystical realm. She continued to be a beacon of hope and kindness, reminding everyone that true courage lies within, waiting to be awakened.\n\nAnd so, Princess Aurora's tale lived on as a timeless reminder that even in the darkest of times, there is always light and hope to be found.", role='assistant', function_call=None, tool_calls=None))], created=1701011002, model='gpt-3.5-turbo-0613', object='chat.completion', system_fingerprint=None, usage=CompletionUsage(completion_tokens=657, prompt_tokens=12, total_tokens=669))



## How to maximize throughput of batch processing given rate limits

If you're processing real-time requests from users, backoff and retry is a great strategy to minimize latency while avoiding rate limit errors.

However, if you're processing large volumes of batch data, where throughput matters more than latency, there are a few other things you can do in addition to backoff and retry.

### Proactively adding delay between requests

If you are constantly hitting the rate limit, then backing off, then hitting the rate limit again, then backing off again, it's possible that a good fraction of your request budget will be 'wasted' on requests that need to be retried. This limits your processing throughput, given a fixed rate limit.

Here, one potential solution is to calculate your rate limit and add a delay equal to its reciprocal (e.g., if your rate limit 20 requests per minute, add a delay of 3–6 seconds to each request). This can help you operate near the rate limit ceiling without hitting it and incurring wasted requests.

#### Example of adding delay to a request


```python
# imports
import time

# Define a function that adds a delay to a Completion API call
def delayed_completion(delay_in_seconds: float = 1, **kwargs):
    """Delay a completion by a specified amount of time."""

    # Sleep for the delay
    time.sleep(delay_in_seconds)

    # Call the Completion API and return the result
    return client.chat.completions.create(**kwargs)


# Calculate the delay based on your rate limit
rate_limit_per_minute = 20
delay = 60.0 / rate_limit_per_minute

delayed_completion(
    delay_in_seconds=delay,
    model="gpt-3.5-turbo",
    messages=[{"role": "user", "content": "Once upon a time,"}]
)

```


key: _node_content
string_value:
{"id_": "fa010693-9ca8-41e9-be48-6d36fab0533d", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "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": "4d4d7d64-2cb7-4b25-9a6b-4e1da7aa137e", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "036d236287213f8976a11b4008fcdf7dddb41333fc2b788b4a87761c459d8924", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "63c6a8a9-c008-409b-adf0-5800ec153f59", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "c0d833331eea1f12729aa43223b11894c5ac295c288674317b1332ad8503c47e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ccc5298c-34f8-4bd8-a7ab-c57cb400c102", "node_type": "1", "metadata": {}, "hash": "58f91675f6169c705361f303d47ac1296375c425637d7b2a8d74512023d08b02", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 18940, "end_char_idx": 23658, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
## How to maximize throughput of batch processing given rate limits

If you're processing real-time requests from users, backoff and retry is a great strategy to minimize latency while avoiding rate limit errors.

However, if you're processing large volumes of batch data, where throughput matters more than latency, there are a few other things you can do in addition to backoff and retry.

### Proactively adding delay between requests

If you are constantly hitting the rate limit, then backing off, then hitting the rate limit again, then backing off again, it's possible that a good fraction of your request budget will be 'wasted' on requests that need to be retried. This limits your processing throughput, given a fixed rate limit.

Here, one potential solution is to calculate your rate limit and add a delay equal to its reciprocal (e.g., if your rate limit 20 requests per minute, add a delay of 3–6 seconds to each request). This can help you operate near the rate limit ceiling without hitting it and incurring wasted requests.

#### Example of adding delay to a request


```python
# imports
import time

# Define a function that adds a delay to a Completion API call
def delayed_completion(delay_in_seconds: float = 1, **kwargs):
    """Delay a completion by a specified amount of time."""

    # Sleep for the delay
    time.sleep(delay_in_seconds)

    # Call the Completion API and return the result
    return client.chat.completions.create(**kwargs)


# Calculate the delay based on your rate limit
rate_limit_per_minute = 20
delay = 60.0 / rate_limit_per_minute

delayed_completion(
    delay_in_seconds=delay,
    model="gpt-3.5-turbo",
    messages=[{"role": "user", "content": "Once upon a time,"}]
)

```




    ChatCompletion(id='chatcmpl-8PAyCR1axKsomV0e349XiCN1Z81pH', choices=[Choice(finish_reason='stop', index=0, message=ChatCompletionMessage(content="in a small village, there lived a young girl named Maya. Maya was known for her kindness and love for nature. She spent hours exploring the forests surrounding the village, admiring the vibrant flowers and talking to the animals.\n\nOne sunny day, as Maya was picking wildflowers, she stumbled upon a wounded blackbird with a broken wing. Feeling sorry for the bird, Maya gently picked it up and cradled it in her hands. She knew she had to help the bird, so she hurried back to her cottage.\n\nMaya set up a cozy nest for the blackbird and carefully splinted its wing. She fed it worms and berries, doing everything she could to nurse it back to health. Each day, she would sing lullabies and tell stories to keep the blackbird company. Slowly, the bird's wing healed, and before long, it was ready to fly again.\n\nOn a beautiful morning, Maya opened the window of her cottage and released the blackbird into the sky. As the bird soared into the air, Maya's heart filled with joy and gratitude. Little did she know, this act of kindness would change her life forever.\n\nThe following night, a mysterious glowing light illuminated Maya's room. Startled, she sat up and saw a magical creature standing before her. It was a fairy, tiny yet radiating warmth and light.\n\nThe fairy introduced herself as Luna, the Guardian of the Forest. She had witnessed Maya's kindness towards the blackbird and had been watching her ever since. Luna explained that she had come to reward Maya for her selflessness.\n\nWith a wave of her wand, Luna granted Maya the ability to communicate with animals. Maya's eyes widened with amazement as she realized she could now understand the language of nature. Birds chirped melodies, rabbits whispered secrets, and trees shared their ancient wisdom.\n\nOver time, Maya's ability made her beloved by both humans and animals. Farmers sought her advice on how to care for their crops, and children flocked to her for stories of her enchanting encounters with the forest creatures. Maya used her gift to teach others about the importance of living in harmony with nature.\n\nAs years passed, Maya became known as the Village Guardian. She dedicated herself to protecting the surrounding forests from harm and educating others on sustainable living. The village flourished under Maya's guidance, and animals and humans lived side by side peacefully.\n\nAnd so, Maya's story became a legend passed down through generations. Her kindness, love for nature, and her ability to communicate with animals inspired people to treat the world around them with compassion and care.", role='assistant', function_call=None, tool_calls=None))], created=1701011060, model='gpt-3.5-turbo-0613', object='chat.completion', system_fingerprint=None, usage=CompletionUsage(completion_tokens=524, prompt_tokens=12, total_tokens=536))


key: _node_content
string_value:
{"id_": "ccc5298c-34f8-4bd8-a7ab-c57cb400c102", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "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": "4d4d7d64-2cb7-4b25-9a6b-4e1da7aa137e", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "036d236287213f8976a11b4008fcdf7dddb41333fc2b788b4a87761c459d8924", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "fa010693-9ca8-41e9-be48-6d36fab0533d", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "57cfb4b148970cba77898ada67761b89cef1f5c0690b720f3267eb205e96e871", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "327af581-2f7d-417c-9370-bf738fb73111", "node_type": "1", "metadata": {}, "hash": "3c80f4ea0cec491cdd1f824575e0395b80c79d37bdc434d547af9f1fa0eb80aa", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 23664, "end_char_idx": 25967, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
### Batching requests

The OpenAI API has separate limits for requests per minute and tokens per minute.

If you're hitting the limit on requests per minute, but have headroom on tokens per minute, you can increase your throughput by batching multiple tasks into each request. This will allow you to process more tokens per minute, especially with the smaller models.

Sending in a batch of prompts works exactly the same as a normal API call, except that pass in a list of strings to `prompt` parameter instead of a single string.

**Warning:** the response object may not return completions in the order of the prompts, so always remember to match responses back to prompts using the `index` field.

#### Example without batching


```python
num_stories = 10
content = "Once upon a time,"

# serial example, with one story completion per request
for _ in range(num_stories):
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": content}],
        max_tokens=20,
    )

    # print story
    print(content + response.choices[0].message.content)

```

    Once upon a time,in a small village nestled between rolling green hills, there lived a young girl named Lily. She had
    Once upon a time,in a small village nestled in the heart of a lush forest, lived a young girl named Evelyn.
    Once upon a time,in a faraway kingdom, there lived a young princess named Aurora. She was known for her kind
    Once upon a time,in a faraway kingdom called Enchantia, there lived a young girl named Ella. Ella was
    Once upon a time,in a small village nestled among the rolling hills, lived a young woman named Lucy. Lucy was known
    Once upon a time,in a small village nestled between rolling hills, there lived a young girl named Ava. Ava was a
    Once upon a time,in a faraway kingdom, there lived a wise and just king named Arthur. King Arthur ruled over
    Once upon a time,in a small village nestled among towering mountains, lived a young girl named Lily. She was known for
    Once upon a time,in a small village nestled in the heart of a lush forest, there lived a young girl named Lily
    Once upon a time,in a far-off kingdom, there lived a kind and beloved queen named Isabella. She ruled with


#### Example with batching


key: _node_content
string_value:
{"id_": "327af581-2f7d-417c-9370-bf738fb73111", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "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": "4d4d7d64-2cb7-4b25-9a6b-4e1da7aa137e", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "036d236287213f8976a11b4008fcdf7dddb41333fc2b788b4a87761c459d8924", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ccc5298c-34f8-4bd8-a7ab-c57cb400c102", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "8f2597e634536614a430451e283b88ac9647a20aa5a559b69a7370ac6a78e1f9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "691816ba-f07c-4a74-a6b2-85b9284729e7", "node_type": "1", "metadata": {}, "hash": "89523fd07a6f446bffe166ff8716348f24ee073c1f8eab5fd981e50d77ebdee2", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 24398, "end_char_idx": 27544, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
num_stories = 10
content = "Once upon a time,"

# serial example, with one story completion per request
for _ in range(num_stories):
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": content}],
        max_tokens=20,
    )

    # print story
    print(content + response.choices[0].message.content)

```

    Once upon a time,in a small village nestled between rolling green hills, there lived a young girl named Lily. She had
    Once upon a time,in a small village nestled in the heart of a lush forest, lived a young girl named Evelyn.
    Once upon a time,in a faraway kingdom, there lived a young princess named Aurora. She was known for her kind
    Once upon a time,in a faraway kingdom called Enchantia, there lived a young girl named Ella. Ella was
    Once upon a time,in a small village nestled among the rolling hills, lived a young woman named Lucy. Lucy was known
    Once upon a time,in a small village nestled between rolling hills, there lived a young girl named Ava. Ava was a
    Once upon a time,in a faraway kingdom, there lived a wise and just king named Arthur. King Arthur ruled over
    Once upon a time,in a small village nestled among towering mountains, lived a young girl named Lily. She was known for
    Once upon a time,in a small village nestled in the heart of a lush forest, there lived a young girl named Lily
    Once upon a time,in a far-off kingdom, there lived a kind and beloved queen named Isabella. She ruled with


#### Example with batching


```python
num_stories = 10
prompts = ["Once upon a time,"] * num_stories

# batched example, with 10 stories completions per request
response = client.chat.completions.create(
    model="curie",
    prompt=prompts,
    max_tokens=20,
)

# match completions to prompts by index
stories = [""] * len(prompts)
for choice in response.choices:
    stories[choice.index] = prompts[choice.index] + choice.text

# print stories
for story in stories:
    print(story)

```

    Once upon a time, I lived in hope. I convinced myself I knew best, because, naive as it might sound,
    Once upon a time, Thierry Henry was invited to have a type of frosty exchange with English fans, in which
    Once upon a time, and a long time ago as well, PV was passively cooled because coils cooled by use of metal driving
    Once upon a time, there was a land called Texas. It was about the size of Wisconsin. It contained, however,
    Once upon a time, there was an old carpenter who had three sons. The locksmith never learned to read or write
    Once upon a time, there was a small farming town called Moonridge Village, far West across the great vast plains that lay
    Once upon a time, California’s shorelines, lakes, and valleys were host to expanses of untamed wilderness
    Once upon a time, she said. It started with a simple question: Why don’t we know any stories?
    Once upon a time, when I was a young woman, there was a movie named Wuthering Heights. Stand by alleges
    Once upon a time, a very long time I mean, in the year 1713, died a beautiful Duchess called the young


key: _node_content
string_value:
{"id_": "691816ba-f07c-4a74-a6b2-85b9284729e7", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "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": "4d4d7d64-2cb7-4b25-9a6b-4e1da7aa137e", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "036d236287213f8976a11b4008fcdf7dddb41333fc2b788b4a87761c459d8924", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "327af581-2f7d-417c-9370-bf738fb73111", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "OpenAI_Cookbooks"}, "hash": "d9006bfa5a59bb2e3622f2b5dea03a9a762eaf2bdf0b4b4b016784158b30150d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 25941, "end_char_idx": 28207, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
#### Example with batching


```python
num_stories = 10
prompts = ["Once upon a time,"] * num_stories

# batched example, with 10 stories completions per request
response = client.chat.completions.create(
    model="curie",
    prompt=prompts,
    max_tokens=20,
)

# match completions to prompts by index
stories = [""] * len(prompts)
for choice in response.choices:
    stories[choice.index] = prompts[choice.index] + choice.text

# print stories
for story in stories:
    print(story)

```

    Once upon a time, I lived in hope. I convinced myself I knew best, because, naive as it might sound,
    Once upon a time, Thierry Henry was invited to have a type of frosty exchange with English fans, in which
    Once upon a time, and a long time ago as well, PV was passively cooled because coils cooled by use of metal driving
    Once upon a time, there was a land called Texas. It was about the size of Wisconsin. It contained, however,
    Once upon a time, there was an old carpenter who had three sons. The locksmith never learned to read or write
    Once upon a time, there was a small farming town called Moonridge Village, far West across the great vast plains that lay
    Once upon a time, California’s shorelines, lakes, and valleys were host to expanses of untamed wilderness
    Once upon a time, she said. It started with a simple question: Why don’t we know any stories?
    Once upon a time, when I was a young woman, there was a movie named Wuthering Heights. Stand by alleges
    Once upon a time, a very long time I mean, in the year 1713, died a beautiful Duchess called the young


## Example parallel processing script

We've written an example script for parallel processing large quantities of API requests: [api_request_parallel_processor.py](https://github.com/openai/openai-cookbook/blob/main/examples/api_request_parallel_processor.py).

The script combines some handy features:
- Streams requests from file, to avoid running out of memory for giant jobs
- Makes requests concurrently, to maximize throughput
- Throttles both request and token usage, to stay under rate limits
- Retries failed requests, to avoid missing data
- Logs errors, to diagnose problems with requests

Feel free to use it as is or modify it to suit your needs.


key: _node_content
string_value:
{"id_": "7b6d4614-5e97-4db0-986b-5bb4fa641286", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine_tuning_for_function_calling.ipynb", "title": "Fine tuning with function-calling", "tokens": 26666, "retrieve_doc": false, "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": "99e2a7ce-e4b6-45ef-b28e-50b87a57779c", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine_tuning_for_function_calling.ipynb", "title": "Fine tuning with function-calling", "tokens": 26666, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "660de8d98c1ff3119943c9886daca4850fedcc37b81b494ed3a3eb27f7f4ba48", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "51a02fa2-4a2c-4efa-828a-9e7d2f28d515", "node_type": "1", "metadata": {}, "hash": "1747f5921bc46dde0c5f7e7b639c7bb27eb4ede64085ab49aed3e8eff375bd7a", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3162, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Fine tuning with function-calling


This notebook covers how to fine-tune to increase function calling accuracy and reliability. You can find more information on function calling [here](https://github.com/openai/openai-cookbook/blob/main/examples/How_to_call_functions_with_chat_models.ipynb), and on fine tuning [here](https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb)


For context, from the function calling notebook above:

> `tools` is an optional parameter in the Chat Completion API which can be used to provide function specifications. The purpose of this is to enable models to generate function arguments which adhere to the provided specifications. Note that the API will not actually execute any function calls. It is up to developers to execute function calls using model outputs.


Function calling is a very powerful tool when it functions as intended. However, we have seen that as the number of functions increases, and the complexity of the task at hand increases, function calling becomes less accurate (e.g.: more hallucinated invocations, and incorrect invocations).

Before fine tuning for function calling, it's best to begin with:

- Improvements to the function definitions. Make them more clear, and more distinct from one another.
- Experiment with prompt engineering: often a more detailed prompt can help the model call the correct function.

_If_ the steps above fail to improve function calling to a satisfactory level, then you can try fine tuning for function calling.


### Overview


This notebook contains three sections

- **Assessing baseline function calling performance:** Evaluating an out-of-the-box `gpt-3.5-turbo` model on our given function (let's assume that for latency + cost reasons we cannot use `gpt-4o` for a drone copilot)
- **Generating synthetic data:** Using `gpt-4o` to create 'golden' set of prompts and function invocations to use as training data
- **Fine-tuning**: Running the fine tuning job, and evaluating the fine-tuned model


Note: _This notebook provides an example of how to create synthetic training data for fine tuning for function calling given just a list of functions. While real-world production test evals are preferable, this method produces strong results and can be used in conjunction with real-world training data._


# Getting baseline function calling performance



```python
#!pip install tenacity -q
#!pip install openai -q
#!pip install typing -q
# !pip install python-dotenv
```


```python
import numpy as np
import json
import os
from IPython.display import display
import pandas as pd
from openai import OpenAI
import itertools
import time
import base64
from tenacity import retry, wait_random_exponential, stop_after_attempt
from typing import Any, Dict, List, Generator
import ast

%load_ext dotenv
%dotenv

client = OpenAI(api_key=os.environ.get("OPENAI_BUILD_HOUR_KEY"))
```

    The dotenv extension is already loaded. To reload it, use:
      %reload_ext dotenv


### Utilities


Let's define utility functions for making calls to the Chat Completions API, one to get the completion and one to get the function call.


key: _node_content
string_value:
{"id_": "51a02fa2-4a2c-4efa-828a-9e7d2f28d515", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine_tuning_for_function_calling.ipynb", "title": "Fine tuning with function-calling", "tokens": 26666, "retrieve_doc": false, "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": "99e2a7ce-e4b6-45ef-b28e-50b87a57779c", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine_tuning_for_function_calling.ipynb", "title": "Fine tuning with function-calling", "tokens": 26666, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "660de8d98c1ff3119943c9886daca4850fedcc37b81b494ed3a3eb27f7f4ba48", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7b6d4614-5e97-4db0-986b-5bb4fa641286", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine_tuning_for_function_calling.ipynb", "title": "Fine tuning with function-calling", "tokens": 26666, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "f4a7bcb305bf42e083fa5db4f80ddec148b35d5dc9fbd622cfcac982d133b6a6", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "051c9c52-3e30-417d-9500-0aadd469d4bf", "node_type": "1", "metadata": {}, "hash": "865f52d0f9dde2ddde3c8d5d431f521823465ff8e1de903f782a8fd30aea8370", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1552, "end_char_idx": 3832, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
### Overview


This notebook contains three sections

- **Assessing baseline function calling performance:** Evaluating an out-of-the-box `gpt-3.5-turbo` model on our given function (let's assume that for latency + cost reasons we cannot use `gpt-4o` for a drone copilot)
- **Generating synthetic data:** Using `gpt-4o` to create 'golden' set of prompts and function invocations to use as training data
- **Fine-tuning**: Running the fine tuning job, and evaluating the fine-tuned model


Note: _This notebook provides an example of how to create synthetic training data for fine tuning for function calling given just a list of functions. While real-world production test evals are preferable, this method produces strong results and can be used in conjunction with real-world training data._


# Getting baseline function calling performance



```python
#!pip install tenacity -q
#!pip install openai -q
#!pip install typing -q
# !pip install python-dotenv
```


```python
import numpy as np
import json
import os
from IPython.display import display
import pandas as pd
from openai import OpenAI
import itertools
import time
import base64
from tenacity import retry, wait_random_exponential, stop_after_attempt
from typing import Any, Dict, List, Generator
import ast

%load_ext dotenv
%dotenv

client = OpenAI(api_key=os.environ.get("OPENAI_BUILD_HOUR_KEY"))
```

    The dotenv extension is already loaded. To reload it, use:
      %reload_ext dotenv


### Utilities


Let's define utility functions for making calls to the Chat Completions API, one to get the completion and one to get the function call.



```python
def get_chat_completion(
    messages: list[dict[str, str]],
    model: str = "gpt-3.5-turbo",
    max_tokens=500,
    temperature=0.0,
    stop=None,
    tools=None,
    seed=42,
    functions=None,
    tool_choice=None,
) -> str:
    params = {
        "model": model,
        "messages": messages,
        "max_tokens": max_tokens,
        "temperature": temperature,
        "stop": stop,
        "tools": tools,
        "seed": seed,
        "tool_choice": tool_choice,
    }
    if functions:
        params["functions"] = functions

    completion = client.chat.completions.create(**params)
    return completion.choices[0].message, completion.usage


key: _node_content
string_value:
{"id_": "051c9c52-3e30-417d-9500-0aadd469d4bf", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine_tuning_for_function_calling.ipynb", "title": "Fine tuning with function-calling", "tokens": 26666, "retrieve_doc": false, "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": "99e2a7ce-e4b6-45ef-b28e-50b87a57779c", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine_tuning_for_function_calling.ipynb", "title": "Fine tuning with function-calling", "tokens": 26666, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "660de8d98c1ff3119943c9886daca4850fedcc37b81b494ed3a3eb27f7f4ba48", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "51a02fa2-4a2c-4efa-828a-9e7d2f28d515", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine_tuning_for_function_calling.ipynb", "title": "Fine tuning with function-calling", "tokens": 26666, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "84354a2984409a05228c5f7af1acde95db230796262f8573a5f36fde5c0e0d5f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1c0a7b7b-6e48-41cc-bb88-c0c2ddca7aec", "node_type": "1", "metadata": {}, "hash": "b248981f55ee65a98d4c1c123c6035a1dc0c796a67c346a4505c8a2caa3c72c7", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2348, "end_char_idx": 7078, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Getting baseline function calling performance



```python
#!pip install tenacity -q
#!pip install openai -q
#!pip install typing -q
# !pip install python-dotenv
```


```python
import numpy as np
import json
import os
from IPython.display import display
import pandas as pd
from openai import OpenAI
import itertools
import time
import base64
from tenacity import retry, wait_random_exponential, stop_after_attempt
from typing import Any, Dict, List, Generator
import ast

%load_ext dotenv
%dotenv

client = OpenAI(api_key=os.environ.get("OPENAI_BUILD_HOUR_KEY"))
```

    The dotenv extension is already loaded. To reload it, use:
      %reload_ext dotenv


### Utilities


Let's define utility functions for making calls to the Chat Completions API, one to get the completion and one to get the function call.



```python
def get_chat_completion(
    messages: list[dict[str, str]],
    model: str = "gpt-3.5-turbo",
    max_tokens=500,
    temperature=0.0,
    stop=None,
    tools=None,
    seed=42,
    functions=None,
    tool_choice=None,
) -> str:
    params = {
        "model": model,
        "messages": messages,
        "max_tokens": max_tokens,
        "temperature": temperature,
        "stop": stop,
        "tools": tools,
        "seed": seed,
        "tool_choice": tool_choice,
    }
    if functions:
        params["functions"] = functions

    completion = client.chat.completions.create(**params)
    return completion.choices[0].message, completion.usage


def eval(model: str, system_prompt: str, function_list, prompts_to_expected_tool_name):
    """
    Evaluate the performance of a model in selecting the correct function based on given prompts.

    Args:
        model (str): The name of the model to be evaluated.
        system_prompt (str): The system prompt to be used in the chat completion.
        function_list (list): A list of functions that the model can call.
        prompts_to_expected_tool_name (dict): A dictionary mapping prompts to their expected function names.

    Returns:
        None
    """

    prompts_to_actual = []
    latencies = []
    tokens_used = []

    for prompt, expected_function in prompts_to_expected_tool_name.items():
        messages = [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": prompt},
        ]

        start_time = time.time()
        completion, usage = get_chat_completion(
            model=model,
            messages=messages,
            seed=42,
            tools=function_list,
            temperature=0.0,
            tool_choice="required",
        )
        end_time = time.time()

        latency = (end_time - start_time) * 1000  # convert to milliseconds
        latencies.append(latency)

        prompts_to_actual.append(
            {prompt: completion.tool_calls[0].function.name})

        # Calculate tokens used
        tokens_used.append(usage.total_tokens)

    total_prompts = len(prompts_to_expected_tool_name)

    # Calculate the number of matches
    matches = sum(
        1
        for result in prompts_to_actual
        if list(result.values())[0]
        == prompts_to_expected_tool_name[list(result.keys())[0]]
    )
    match_percentage = (matches / total_prompts) * 100

    # Calculate average latency
    avg_latency = sum(latencies) / total_prompts
    # Calculate average tokens used
    avg_tokens_used = sum(tokens_used) / total_prompts

    # Create a DataFrame to store the results
    results_df = pd.DataFrame(columns=["Prompt", "Expected", "Match"])

    results_list = []
    for result in prompts_to_actual:
        prompt = list(result.keys())[0]
        actual_function = list(result.values())[0]
        expected_function = prompts_to_expected_tool_name[prompt]
        match = actual_function == expected_function
        results_list.append(
            {
                "Prompt": prompt,
                "Actual": actual_function,
                "Expected": expected_function,
                "Match": "Yes" if match else "No",
            }
        )
    results_df = pd.DataFrame(results_list)

    def style_rows(row):
        match = row["Match"]
        background_color = "red" if match == "No" else "white"
        return ["background-color: {}; color: black".format(background_color)] * len(
            row
        )

    styled_results_df = results_df.style.apply(style_rows, axis=1)

    # Display the DataFrame as a table
    display(styled_results_df)

    print(
        f"Number of matches: {matches} out of {total_prompts} ({match_percentage:.2f}%)"
    )
    print(f"Average latency per request: {avg_latency:.2f} ms")
    print(f"Average tokens used per request: {avg_tokens_used:.2f}")
```

### Baseline testing


key: _node_content
string_value:
{"id_": "1c0a7b7b-6e48-41cc-bb88-c0c2ddca7aec", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine_tuning_for_function_calling.ipynb", "title": "Fine tuning with function-calling", "tokens": 26666, "retrieve_doc": false, "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": "99e2a7ce-e4b6-45ef-b28e-50b87a57779c", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine_tuning_for_function_calling.ipynb", "title": "Fine tuning with function-calling", "tokens": 26666, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "660de8d98c1ff3119943c9886daca4850fedcc37b81b494ed3a3eb27f7f4ba48", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "051c9c52-3e30-417d-9500-0aadd469d4bf", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine_tuning_for_function_calling.ipynb", "title": "Fine tuning with function-calling", "tokens": 26666, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "c66f58d5ddfe625a89b2cfedd5e5a15dd29baa101f63fa21aeedab0b4f7c1e21", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c9914776-66ae-4cc8-bad8-0bdad88f6cdf", "node_type": "1", "metadata": {}, "hash": "12cccbb7ddb2be23b222f06c2701073aa081abd7ba0a083f9208a8fa23f9f1de", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 7081, "end_char_idx": 11119, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Let's build an intelligent drone co-pilot. We want to be able to give the co-pilot commands, and have it either call the function
for that command, or deny that request if the command is unfeasible.
We can first define a system prompt for the copilot.



```python
DRONE_SYSTEM_PROMPT = """You are an intelligent AI that controls a drone. Given a command or request from the user,
call one of your functions to complete the request. If the request cannot be completed by your available functions, call the reject_request function.
If the request is ambiguous or unclear, reject the request."""
```

Now let's define functions for all of the actions the copilot can take.



```python
function_list = [
    {
        "type": "function",
        "function": {
            "name": "takeoff_drone",
            "description": "Initiate the drone's takeoff sequence.",
            "parameters": {
                "type": "object",
                "properties": {
                    "altitude": {
                        "type": "integer",
                        "description": "Specifies the altitude in meters to which the drone should ascend.",
                    }
                },
                "required": ["altitude"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "land_drone",
            "description": "Land the drone at its current location or a specified landing point.",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "enum": ["current", "home_base", "custom"],
                        "description": "Specifies the landing location for the drone.",
                    },
                    "coordinates": {
                        "type": "object",
                        "description": "GPS coordinates for custom landing location. Required if location is 'custom'.",
                    },
                },
                "required": ["location"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "control_drone_movement",
            "description": "Direct the drone's movement in a specific direction.",
            "parameters": {
                "type": "object",
                "properties": {
                    "direction": {
                        "type": "string",
                        "enum": ["forward", "backward", "left", "right", "up", "down"],
                        "description": "Direction in which the drone should move.",
                    },
                    "distance": {
                        "type": "integer",
                        "description": "Distance in meters the drone should travel in the specified direction.",
                    },
                },
                "required": ["direction", "distance"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "set_drone_speed",
            "description": "Adjust the speed of the drone.",
            "parameters": {
                "type": "object",
                "properties": {
                    "speed": {
                        "type": "integer",
                        "description": "Specifies the speed in km/h. Valid range is 0 to 100.",
                        "minimum": 0,
                    }
                },
                "required": ["speed"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "control_camera",
            "description": "Control the drone's camera to capture images or videos.",
            "parameters": {
                "type": "object",
                "properties": {
                    "mode": {
                        "type": "string",
                        "enum": ["photo", "video", "panorama"],
                        "description": "Camera mode to capture content.


key: _node_content
string_value:
{"id_": "c9914776-66ae-4cc8-bad8-0bdad88f6cdf", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine_tuning_for_function_calling.ipynb", "title": "Fine tuning with function-calling", "tokens": 26666, "retrieve_doc": false, "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": "99e2a7ce-e4b6-45ef-b28e-50b87a57779c", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine_tuning_for_function_calling.ipynb", "title": "Fine tuning with function-calling", "tokens": 26666, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "660de8d98c1ff3119943c9886daca4850fedcc37b81b494ed3a3eb27f7f4ba48", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1c0a7b7b-6e48-41cc-bb88-c0c2ddca7aec", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine_tuning_for_function_calling.ipynb", "title": "Fine tuning with function-calling", "tokens": 26666, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "8c46191e7b6be9d401e075b1b10fbc6234cb1c25f3af1e65f8aa1d96005b6bc1", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "80ae8fd3-845b-473c-8c94-f2c050e06391", "node_type": "1", "metadata": {}, "hash": "2b4fcf61169a9574d2c73712c8121d77457867a0a09fed3fd68c5fb0cea42ea6", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 9043, "end_char_idx": 12956, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Required if location is 'custom'.",
                    },
                },
                "required": ["location"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "control_drone_movement",
            "description": "Direct the drone's movement in a specific direction.",
            "parameters": {
                "type": "object",
                "properties": {
                    "direction": {
                        "type": "string",
                        "enum": ["forward", "backward", "left", "right", "up", "down"],
                        "description": "Direction in which the drone should move.",
                    },
                    "distance": {
                        "type": "integer",
                        "description": "Distance in meters the drone should travel in the specified direction.",
                    },
                },
                "required": ["direction", "distance"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "set_drone_speed",
            "description": "Adjust the speed of the drone.",
            "parameters": {
                "type": "object",
                "properties": {
                    "speed": {
                        "type": "integer",
                        "description": "Specifies the speed in km/h. Valid range is 0 to 100.",
                        "minimum": 0,
                    }
                },
                "required": ["speed"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "control_camera",
            "description": "Control the drone's camera to capture images or videos.",
            "parameters": {
                "type": "object",
                "properties": {
                    "mode": {
                        "type": "string",
                        "enum": ["photo", "video", "panorama"],
                        "description": "Camera mode to capture content.",
                    },
                    "duration": {
                        "type": "integer",
                        "description": "Duration in seconds for video capture. Required if mode is 'video'.",
                    },
                },
                "required": ["mode"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "control_gimbal",
            "description": "Adjust the drone's gimbal for camera stabilization and direction.",
            "parameters": {
                "type": "object",
                "properties": {
                    "tilt": {
                        "type": "integer",
                        "description": "Tilt angle for the gimbal in degrees.",
                    },
                    "pan": {
                        "type": "integer",
                        "description": "Pan angle for the gimbal in degrees.",
                    },
                },
                "required": ["tilt", "pan"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "set_drone_lighting",
            "description": "Control the drone's lighting for visibility and signaling.",
            "parameters": {
                "type": "object",
                "properties": {
                    "mode": {
                        "type": "string",
                        "enum": ["on", "off", "blink", "sos"],
                        "description": "Lighting mode for the drone.",
                    }
                },
                "required": ["mode"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "return_to_home",
            "description": "Command the drone to return to its home or launch location.


key: _node_content
string_value:
{"id_": "80ae8fd3-845b-473c-8c94-f2c050e06391", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine_tuning_for_function_calling.ipynb", "title": "Fine tuning with function-calling", "tokens": 26666, "retrieve_doc": false, "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": "99e2a7ce-e4b6-45ef-b28e-50b87a57779c", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine_tuning_for_function_calling.ipynb", "title": "Fine tuning with function-calling", "tokens": 26666, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "660de8d98c1ff3119943c9886daca4850fedcc37b81b494ed3a3eb27f7f4ba48", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c9914776-66ae-4cc8-bad8-0bdad88f6cdf", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine_tuning_for_function_calling.ipynb", "title": "Fine tuning with function-calling", "tokens": 26666, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "53ed103ed4903650cae37167c57c4823bb54f5e9b66a36206b32e9a106eed382", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "362b6339-ce97-4b90-b44b-6795594efe5a", "node_type": "1", "metadata": {}, "hash": "f3c62e1d2a36b331f737a623b9cb6837e3f7ec8b2074c6922f9cc6fc953fddb1", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 11119, "end_char_idx": 14898, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
",
                    },
                    "duration": {
                        "type": "integer",
                        "description": "Duration in seconds for video capture. Required if mode is 'video'.",
                    },
                },
                "required": ["mode"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "control_gimbal",
            "description": "Adjust the drone's gimbal for camera stabilization and direction.",
            "parameters": {
                "type": "object",
                "properties": {
                    "tilt": {
                        "type": "integer",
                        "description": "Tilt angle for the gimbal in degrees.",
                    },
                    "pan": {
                        "type": "integer",
                        "description": "Pan angle for the gimbal in degrees.",
                    },
                },
                "required": ["tilt", "pan"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "set_drone_lighting",
            "description": "Control the drone's lighting for visibility and signaling.",
            "parameters": {
                "type": "object",
                "properties": {
                    "mode": {
                        "type": "string",
                        "enum": ["on", "off", "blink", "sos"],
                        "description": "Lighting mode for the drone.",
                    }
                },
                "required": ["mode"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "return_to_home",
            "description": "Command the drone to return to its home or launch location.",
            "parameters": {"type": "object", "properties": {}},
        },
    },
    {
        "type": "function",
        "function": {
            "name": "set_battery_saver_mode",
            "description": "Toggle battery saver mode.",
            "parameters": {
                "type": "object",
                "properties": {
                    "status": {
                        "type": "string",
                        "enum": ["on", "off"],
                        "description": "Toggle battery saver mode.",
                    }
                },
                "required": ["status"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "set_obstacle_avoidance",
            "description": "Configure obstacle avoidance settings.",
            "parameters": {
                "type": "object",
                "properties": {
                    "mode": {
                        "type": "string",
                        "enum": ["on", "off"],
                        "description": "Toggle obstacle avoidance.",
                    }
                },
                "required": ["mode"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "set_follow_me_mode",
            "description": "Enable or disable 'follow me' mode.",
            "parameters": {
                "type": "object",
                "properties": {
                    "status": {
                        "type": "string",
                        "enum": ["on", "off"],
                        "description": "Toggle 'follow me' mode.",
                    }
                },
                "required": ["status"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "calibrate_sensors",
            "description": "Initiate calibration sequence for drone's sensors.


key: _node_content
string_value:
{"id_": "362b6339-ce97-4b90-b44b-6795594efe5a", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine_tuning_for_function_calling.ipynb", "title": "Fine tuning with function-calling", "tokens": 26666, "retrieve_doc": false, "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": "99e2a7ce-e4b6-45ef-b28e-50b87a57779c", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine_tuning_for_function_calling.ipynb", "title": "Fine tuning with function-calling", "tokens": 26666, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "660de8d98c1ff3119943c9886daca4850fedcc37b81b494ed3a3eb27f7f4ba48", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "80ae8fd3-845b-473c-8c94-f2c050e06391", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine_tuning_for_function_calling.ipynb", "title": "Fine tuning with function-calling", "tokens": 26666, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "8ef62d918d3df88189248301ccf320054a22b646f8052ed9bcf5207729fbc03c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "55c73e53-7d41-4365-94ce-fe44a8e67b78", "node_type": "1", "metadata": {}, "hash": "b16b6cebacf9682aa9326005a9e0493cdf650a1a1d7a7ac6b1043232912886c5", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 12956, "end_char_idx": 16852, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
",
            "parameters": {"type": "object", "properties": {}},
        },
    },
    {
        "type": "function",
        "function": {
            "name": "set_battery_saver_mode",
            "description": "Toggle battery saver mode.",
            "parameters": {
                "type": "object",
                "properties": {
                    "status": {
                        "type": "string",
                        "enum": ["on", "off"],
                        "description": "Toggle battery saver mode.",
                    }
                },
                "required": ["status"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "set_obstacle_avoidance",
            "description": "Configure obstacle avoidance settings.",
            "parameters": {
                "type": "object",
                "properties": {
                    "mode": {
                        "type": "string",
                        "enum": ["on", "off"],
                        "description": "Toggle obstacle avoidance.",
                    }
                },
                "required": ["mode"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "set_follow_me_mode",
            "description": "Enable or disable 'follow me' mode.",
            "parameters": {
                "type": "object",
                "properties": {
                    "status": {
                        "type": "string",
                        "enum": ["on", "off"],
                        "description": "Toggle 'follow me' mode.",
                    }
                },
                "required": ["status"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "calibrate_sensors",
            "description": "Initiate calibration sequence for drone's sensors.",
            "parameters": {"type": "object", "properties": {}},
        },
    },
    {
        "type": "function",
        "function": {
            "name": "set_autopilot",
            "description": "Enable or disable autopilot mode.",
            "parameters": {
                "type": "object",
                "properties": {
                    "status": {
                        "type": "string",
                        "enum": ["on", "off"],
                        "description": "Toggle autopilot mode.",
                    }
                },
                "required": ["status"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "configure_led_display",
            "description": "Configure the drone's LED display pattern and colors.",
            "parameters": {
                "type": "object",
                "properties": {
                    "pattern": {
                        "type": "string",
                        "enum": ["solid", "blink", "pulse", "rainbow"],
                        "description": "Pattern for the LED display.",
                    },
                    "color": {
                        "type": "string",
                        "enum": ["red", "blue", "green", "yellow", "white"],
                        "description": "Color for the LED display. Not required if pattern is 'rainbow'.",
                    },
                },
                "required": ["pattern"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "set_home_location",
            "description": "Set or change the home location for the drone.",
            "parameters": {
                "type": "object",
                "properties": {
                    "coordinates": {
                        "type": "object",
                        "description": "GPS coordinates for the home location.


key: _node_content
string_value:
{"id_": "55c73e53-7d41-4365-94ce-fe44a8e67b78", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine_tuning_for_function_calling.ipynb", "title": "Fine tuning with function-calling", "tokens": 26666, "retrieve_doc": false, "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": "99e2a7ce-e4b6-45ef-b28e-50b87a57779c", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine_tuning_for_function_calling.ipynb", "title": "Fine tuning with function-calling", "tokens": 26666, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "660de8d98c1ff3119943c9886daca4850fedcc37b81b494ed3a3eb27f7f4ba48", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "362b6339-ce97-4b90-b44b-6795594efe5a", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Fine_tuning_for_function_calling.ipynb", "title": "Fine tuning with function-calling", "tokens": 26666, "retrieve_doc": false, "source": "OpenAI_Cookbooks"}, "hash": "fbb4c45fd93aaaf3f18be44b90ad7f0970f09fff331afb643bbd9fbe3f4b0c07", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3aafb590-3fd2-4955-a489-07b4d2741bfc", "node_type": "1", "metadata": {}, "hash": "7e7406058e1abf87bcc40bbdebff9f242dbca6b236d25883f144cf11a3c4ff55", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 14898, "end_char_idx": 18412, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
",
            "parameters": {"type": "object", "properties": {}},
        },
    },
    {
        "type": "function",
        "function": {
            "name": "set_autopilot",
            "description": "Enable or disable autopilot mode.",
            "parameters": {
                "type": "object",
                "properties": {
                    "status": {
                        "type": "string",
                        "enum": ["on", "off"],
                        "description": "Toggle autopilot mode.",
                    }
                },
                "required": ["status"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "configure_led_display",
            "description": "Configure the drone's LED display pattern and colors.",
            "parameters": {
                "type": "object",
                "properties": {
                    "pattern": {
                        "type": "string",
                        "enum": ["solid", "blink", "pulse", "rainbow"],
                        "description": "Pattern for the LED display.",
                    },
                    "color": {
                        "type": "string",
                        "enum": ["red", "blue", "green", "yellow", "white"],
                        "description": "Color for the LED display. Not required if pattern is 'rainbow'.",
                    },
                },
                "required": ["pattern"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "set_home_location",
            "description": "Set or change the home location for the drone.",
            "parameters": {
                "type": "object",
                "properties": {
                    "coordinates": {
                        "type": "object",
                        "description": "GPS coordinates for the home location.",
                    }
                },
                "required": ["coordinates"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "reject_request",
            "description": "Use this function if the request is not possible.",
            "parameters": {"type": "object", "properties": {}},
        },
    },
]
```

For starters, let's see how function calling performs with some straight forward feasible prompts, and then couple of obviously impossible requests which call the 'reject_request' function.



```python
straightforward_prompts_to_expected = {
    "Land the drone at the home base": "land_drone",
    "Take off the drone to 50 meters": "takeoff_drone",
    "Change speed to 15 kilometers per hour": "set_drone_speed",
    "Turn into an elephant!": "reject_request",
    "Move the drone forward by 10 meters": "control_drone_movement",
    "I want the LED display to blink in red": "configure_led_display",
    "Can you take a photo?": "control_camera",
    "Can you detect obstacles?": "set_obstacle_avoidance",
    "Can you dance for me?": "reject_request",
    "Can you follow me?": "set_follow_me_mode",
}
```


```python
# Evaluate the model with the given prompts
eval(
    model="gpt-3.5-turbo",
    system_prompt=DRONE_SYSTEM_PROMPT,
    function_list=function_list,
    prompts_to_expected_tool_name=straightforward_prompts_to_expected,
)
```


<style type="text/css">
#T_b01a0_row0_col0, #T_b01a0_row0_col1, #T_b01a0_row0_col2, #T_b01a0_row0_col3, #T_b01a0_row1_col0,


