# embedding_metadata

key: _node_content
string_value:
{"id_": "3667cbb7-a9a2-4b08-b429-2d26bce5535a", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7d7d92cb-551e-4c41-b916-261267cadd89", "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": "6c122ba9bb203650dedb06cb1beee2a8bdc27f059441d7c80baa2be871402255", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6c6c056d-3604-41b4-af21-0e43ceb6d18c", "node_type": "1", "metadata": {}, "hash": "797aab6d7d11d1d1075087796c844f8ae191289886b6f95d598b867a854e7d66", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 54369, "end_char_idx": 57087, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
{'name': 'return_to_home', 'arguments': '{}'}
    Is it time for the drone to return to base?
    {'name': 'return_to_home', 'arguments': '{}'}
    My phone battery is draining so fast, can you turn on battery saver mode
    {'name': 'set_battery_saver_mode', 'arguments': '{"status": "on"}'}
    I need my laptop battery to last longer, can you switch on battery saver mode
    {'name': 'set_battery_saver_mode', 'arguments': '{"status": "on"}'}
    My phone battery is draining too quickly, can you turn off the battery saver mode
    {'name': 'set_battery_saver_mode', 'arguments': '{"status": "off"}'}
    I feel like my device is slower with battery saver on, can we turn it off?
    {'name': 'set_battery_saver_mode', 'arguments': '{"status": "off"}'}
    I want the car to avoid obstacles, can you turn on that feature?
    {'name': 'set_obstacle_avoidance', 'arguments': '{"mode": "on"}'}
    Can you activate the obstacle avoidance mode for safety purposes?
    {'name': 'set_obstacle_avoidance', 'arguments': '{"mode": "on"}'}
    I'd like to turn off obstacle detection, how do I do that?
    {'name': 'set_obstacle_avoidance', 'arguments': '{"mode": "off"}'}
    Can you disable the obstacle avoidance feature for now?
    {'name': 'set_obstacle_avoidance', 'arguments': '{"mode": "off"}'}
    Can you activate the follow me mode?
    {'name': 'set_follow_me_mode', 'arguments': '{"status": "on"}'}
    I want the car to follow me, can you turn on that feature?
    {'name': 'set_follow_me_mode', 'arguments': '{"status": "on"}'}
    I don't want the drone following me anymore, can you turn that off?
    {'name': 'set_follow_me_mode', 'arguments': '{"status": "off"}'}
    Can you disable the follow-me mode on the drone?
    {'name': 'set_follow_me_mode', 'arguments': '{"status": "off"}'}
    The sensors are acting up, can you recalibrate them
    {'name': 'calibrate_sensors', 'arguments': '{}'}
    My device doesn't seem to be sensing correctly, can you adjust it
    {'name': 'calibrate_sensors', 'arguments': '{}'}
    I'm too tired to drive, can you turn on the autopilot
    {'name': 'set_autopilot', 'arguments': '{"status": "on"}'}
    Let the car drive itself, turn on autopilot
    {'name': 'set_autopilot', 'arguments': '{"status": "on"}'}
    I'm feeling more confident, turn off the autopilot
    {'name': 'set_autopilot', 'arguments': '{"status": "off"}'}
    I think I can handle it, deactivate the automatic pilot
    {'name': 'set_autopilot', 'arguments': '{"status": "off"}'}
    Can you set the display to a steady yellow color?
    {'name': 'configure_led_display', 'arguments': '{"pattern": "solid", "color": "yellow"}'}
    I'd like the LED display to be a solid yellow, please.


key: _node_content
string_value:
{"id_": "6c6c056d-3604-41b4-af21-0e43ceb6d18c", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3667cbb7-a9a2-4b08-b429-2d26bce5535a", "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": "ee64ba8fc290e7dc10a58c4e2c8289762fbb4b227afe16d11550f4907d286d83", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8036964c-1f82-4948-b53e-607019d59736", "node_type": "1", "metadata": {}, "hash": "0e3df9ed3688dbde6e4c977b6bf84579733b0b3c71682a44a843005124c17d1b", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 55716, "end_char_idx": 58453, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
{'name': 'set_follow_me_mode', 'arguments': '{"status": "on"}'}
    I want the car to follow me, can you turn on that feature?
    {'name': 'set_follow_me_mode', 'arguments': '{"status": "on"}'}
    I don't want the drone following me anymore, can you turn that off?
    {'name': 'set_follow_me_mode', 'arguments': '{"status": "off"}'}
    Can you disable the follow-me mode on the drone?
    {'name': 'set_follow_me_mode', 'arguments': '{"status": "off"}'}
    The sensors are acting up, can you recalibrate them
    {'name': 'calibrate_sensors', 'arguments': '{}'}
    My device doesn't seem to be sensing correctly, can you adjust it
    {'name': 'calibrate_sensors', 'arguments': '{}'}
    I'm too tired to drive, can you turn on the autopilot
    {'name': 'set_autopilot', 'arguments': '{"status": "on"}'}
    Let the car drive itself, turn on autopilot
    {'name': 'set_autopilot', 'arguments': '{"status": "on"}'}
    I'm feeling more confident, turn off the autopilot
    {'name': 'set_autopilot', 'arguments': '{"status": "off"}'}
    I think I can handle it, deactivate the automatic pilot
    {'name': 'set_autopilot', 'arguments': '{"status": "off"}'}
    Can you set the display to a steady yellow color?
    {'name': 'configure_led_display', 'arguments': '{"pattern": "solid", "color": "yellow"}'}
    I'd like the LED display to be a solid yellow, please.
    {'name': 'configure_led_display', 'arguments': '{"pattern": "solid", "color": "yellow"}'}
    Can you make the lights flash on and off
    {'name': 'configure_led_display', 'arguments': '{"pattern": "blink"}'}
    I want the LED display to blink, can you set that up
    {'name': 'configure_led_display', 'arguments': '{"pattern": "blink"}'}
    Can you make the lights flash in red?
    {'name': 'configure_led_display', 'arguments': '{"pattern": "blink", "color": "red"}'}
    How do I set the display to blink in red?
    {'name': 'configure_led_display', 'arguments': '{"pattern": "blink", "color": "red"}'}
    Can you make the lights flash in yellow?
    {'name': 'configure_led_display', 'arguments': '{"pattern": "blink", "color": "yellow"}'}
    How do I set the display to blink in yellow?
    {'name': 'configure_led_display', 'arguments': '{"pattern": "blink", "color": "yellow"}'}
    Can you make the lights blink instead of staying steady
    {'name': 'configure_led_display', 'arguments': '{"pattern": "pulse"}'}
    I want the LEDs to flash, not stay solid
    {'name': 'configure_led_display', 'arguments': '{"pattern": "pulse"}'}
    Can you make the LED display pulse in red, please?
    {'name': 'configure_led_display', 'arguments': '{"pattern": "pulse", "color": "red"}'}
    I'd like the LED display to flash in red, can you set that up?


key: _node_content
string_value:
{"id_": "8036964c-1f82-4948-b53e-607019d59736", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6c6c056d-3604-41b4-af21-0e43ceb6d18c", "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": "8d66bfdb35e87fae9aa80e8f90e5881469d82385aab99e364396a4cfb398cdd4", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ab22f63d-6d5a-49d4-8ca3-0940b7b0f09f", "node_type": "1", "metadata": {}, "hash": "37948defa57c3dc413b978b059d8fbc1954583b7a938d988b9dd7ad53131799c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 56939, "end_char_idx": 59865, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
{'name': 'configure_led_display', 'arguments': '{"pattern": "solid", "color": "yellow"}'}
    I'd like the LED display to be a solid yellow, please.
    {'name': 'configure_led_display', 'arguments': '{"pattern": "solid", "color": "yellow"}'}
    Can you make the lights flash on and off
    {'name': 'configure_led_display', 'arguments': '{"pattern": "blink"}'}
    I want the LED display to blink, can you set that up
    {'name': 'configure_led_display', 'arguments': '{"pattern": "blink"}'}
    Can you make the lights flash in red?
    {'name': 'configure_led_display', 'arguments': '{"pattern": "blink", "color": "red"}'}
    How do I set the display to blink in red?
    {'name': 'configure_led_display', 'arguments': '{"pattern": "blink", "color": "red"}'}
    Can you make the lights flash in yellow?
    {'name': 'configure_led_display', 'arguments': '{"pattern": "blink", "color": "yellow"}'}
    How do I set the display to blink in yellow?
    {'name': 'configure_led_display', 'arguments': '{"pattern": "blink", "color": "yellow"}'}
    Can you make the lights blink instead of staying steady
    {'name': 'configure_led_display', 'arguments': '{"pattern": "pulse"}'}
    I want the LEDs to flash, not stay solid
    {'name': 'configure_led_display', 'arguments': '{"pattern": "pulse"}'}
    Can you make the LED display pulse in red, please?
    {'name': 'configure_led_display', 'arguments': '{"pattern": "pulse", "color": "red"}'}
    I'd like the LED display to flash in red, can you set that up?
    {'name': 'configure_led_display', 'arguments': '{"pattern": "pulse", "color": "red"}'}
    I want the LED lights to flash in blue
    {'name': 'configure_led_display', 'arguments': '{"pattern": "pulse", "color": "blue"}'}
    Can you set the display to pulse with a blue color
    {'name': 'configure_led_display', 'arguments': '{"pattern": "pulse", "color": "blue"}'}
    Can you make the lights flash and change to green
    {'name': 'configure_led_display', 'arguments': '{"pattern": "pulse", "color": "green"}'}
    Let's set the LEDs to blink and switch to green
    {'name': 'configure_led_display', 'arguments': '{"pattern": "pulse", "color": "green"}'}
    Can you change the flashy lights to yellow and make them pulse
    {'name': 'configure_led_display', 'arguments': '{"pattern": "pulse", "color": "yellow"}'}
    I want the LED display to blink in yellow, can you do that
    {'name': 'configure_led_display', 'arguments': '{"pattern": "pulse", "color": "yellow"}'}
    Can you change the colors on the display to red and set it to a rainbow pattern?
    {'name': 'configure_led_display', 'arguments': '{"pattern": "rainbow", "color": "red"}'}
    I want the LED display to show a rainbow pattern in red, can you set that up?
    {'name': 'configure_led_display', 'arguments': '{"pattern": "rainbow", "color": "red"}'}
    Can you change the color and pattern of the lights to blue and rainbow?


key: _node_content
string_value:
{"id_": "ab22f63d-6d5a-49d4-8ca3-0940b7b0f09f", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8036964c-1f82-4948-b53e-607019d59736", "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": "449ac00d22ba37f1e4468df2be4027288889d6485bfea981a2e9a8681ad774bc", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ed73dcab-593f-4c09-b2bb-e7c39a3dd20f", "node_type": "1", "metadata": {}, "hash": "544c704c8cfb682d49df0b297cafcfdaea993250985d47f999b0d519e39c011a", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 58458, "end_char_idx": 61305, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
{'name': 'configure_led_display', 'arguments': '{"pattern": "pulse", "color": "red"}'}
    I want the LED lights to flash in blue
    {'name': 'configure_led_display', 'arguments': '{"pattern": "pulse", "color": "blue"}'}
    Can you set the display to pulse with a blue color
    {'name': 'configure_led_display', 'arguments': '{"pattern": "pulse", "color": "blue"}'}
    Can you make the lights flash and change to green
    {'name': 'configure_led_display', 'arguments': '{"pattern": "pulse", "color": "green"}'}
    Let's set the LEDs to blink and switch to green
    {'name': 'configure_led_display', 'arguments': '{"pattern": "pulse", "color": "green"}'}
    Can you change the flashy lights to yellow and make them pulse
    {'name': 'configure_led_display', 'arguments': '{"pattern": "pulse", "color": "yellow"}'}
    I want the LED display to blink in yellow, can you do that
    {'name': 'configure_led_display', 'arguments': '{"pattern": "pulse", "color": "yellow"}'}
    Can you change the colors on the display to red and set it to a rainbow pattern?
    {'name': 'configure_led_display', 'arguments': '{"pattern": "rainbow", "color": "red"}'}
    I want the LED display to show a rainbow pattern in red, can you set that up?
    {'name': 'configure_led_display', 'arguments': '{"pattern": "rainbow", "color": "red"}'}
    Can you change the color and pattern of the lights to blue and rainbow?
    {'name': 'configure_led_display', 'arguments': '{"pattern": "rainbow", "color": "blue"}'}
    I'm feeling like some colorful lights, can you set it to blue and rainbow?
    {'name': 'configure_led_display', 'arguments': '{"pattern": "rainbow", "color": "blue"}'}
    Can you set the LED display to show a rainbow pattern in green color?
    {'name': 'configure_led_display', 'arguments': '{"pattern": "rainbow", "color": "green"}'}
    I'd like the LED display to cycle through colors, starting with green
    {'name': 'configure_led_display', 'arguments': '{"pattern": "rainbow", "color": "green"}'}
    Can you make the lights do a cool rainbow effect
    {'name': 'configure_led_display', 'arguments': '{"pattern": "rainbow", "color": "white"}'}
    Change the color of the lights to white and make them change like a rainbow
    {'name': 'configure_led_display', 'arguments': '{"pattern": "rainbow", "color": "white"}'}
    I changed my mind, can you cancel that request
    {'name': 'reject_request', 'arguments': '{}'}
    I don't want to proceed with the request anymore, can you reject it
    {'name': 'reject_request', 'arguments': '{}'}


Now, back to the rejection function. Let's generate some prompts that are _nearly_ possible, but should result in the `reject_request` function being called. To do so, we queried `gpt-4o` asking for requests that are related to, but not quite possible with, the given list of functions.


key: _node_content
string_value:
{"id_": "ed73dcab-593f-4c09-b2bb-e7c39a3dd20f", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ab22f63d-6d5a-49d4-8ca3-0940b7b0f09f", "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": "da20987caea537602a55c57953a857e66532b5ebf892b7a8a868376b240e9063", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6c58932e-9140-45ab-a012-d5750a5f1d6d", "node_type": "1", "metadata": {}, "hash": "d37fa88715bc67e4b7c7ff0f1153428d21fd61ef017f0faed51973022612a0f0", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 59701, "end_char_idx": 62894, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
{'name': 'configure_led_display', 'arguments': '{"pattern": "rainbow", "color": "red"}'}
    Can you change the color and pattern of the lights to blue and rainbow?
    {'name': 'configure_led_display', 'arguments': '{"pattern": "rainbow", "color": "blue"}'}
    I'm feeling like some colorful lights, can you set it to blue and rainbow?
    {'name': 'configure_led_display', 'arguments': '{"pattern": "rainbow", "color": "blue"}'}
    Can you set the LED display to show a rainbow pattern in green color?
    {'name': 'configure_led_display', 'arguments': '{"pattern": "rainbow", "color": "green"}'}
    I'd like the LED display to cycle through colors, starting with green
    {'name': 'configure_led_display', 'arguments': '{"pattern": "rainbow", "color": "green"}'}
    Can you make the lights do a cool rainbow effect
    {'name': 'configure_led_display', 'arguments': '{"pattern": "rainbow", "color": "white"}'}
    Change the color of the lights to white and make them change like a rainbow
    {'name': 'configure_led_display', 'arguments': '{"pattern": "rainbow", "color": "white"}'}
    I changed my mind, can you cancel that request
    {'name': 'reject_request', 'arguments': '{}'}
    I don't want to proceed with the request anymore, can you reject it
    {'name': 'reject_request', 'arguments': '{}'}


Now, back to the rejection function. Let's generate some prompts that are _nearly_ possible, but should result in the `reject_request` function being called. To do so, we queried `gpt-4o` asking for requests that are related to, but not quite possible with, the given list of functions.



```python
reject_list = [
    "Translate broadcast message to another language",
    "Automatically capture photos when face is detected",
    "Detect nearby drones",
    "Measure wind resistance",
    "Capture slow motion video",
    "Move the drone forward and backward by same distance at the same time.",
    "Adjust drone's altitude to ground level changes",
    "Display custom message on LED display",
    "Sync drone's time with smartphone",
    "Alert when drone travels out of designated area",
    "Calibrate sensors and land simultaneously",
    "Detect moisture levels",
    "Automatically follow GPS tagged object",
    "Toggle night vision mode",
    "Maintain current altitude when battery is low",
    "Decide best landing spot using AI",
    "Program drone's route based on wind direction",
]
```


```python
reject_training_list = []
for prompt in reject_list:
    # Adjust formatting
    tool_calls = [
        {
            "id": "call_id",
            "type": "function",
            "function": {"name": "reject_request", "arguments": "{}"},
        }
    ]
    reject_training_list.append(
        {
            "messages": [
                {"role": "system", "content": DRONE_SYSTEM_PROMPT},
                {"role": "user", "content": prompt},
                {"role": "assistant", "tool_calls": tool_calls},
            ],
            "parallel_tool_calls": False,
            "tools": modified_function_list,
        }
    )
```

Now combine all the training examples together



```python
training_list_total = training_examples + reject_training_list
```


key: _node_content
string_value:
{"id_": "6c58932e-9140-45ab-a012-d5750a5f1d6d", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ed73dcab-593f-4c09-b2bb-e7c39a3dd20f", "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": "2752fca23ff1b0eb6023508e67bc4d4546419193f95a531600393bc72501ef1a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9edf2869-bb12-4660-b689-e8a3653a16bf", "node_type": "1", "metadata": {}, "hash": "8ee4aa8f0781deaadc80c94163088e4a70694cf7d6289efa93755013f883fd6e", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 61019, "end_char_idx": 63158, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Now, back to the rejection function. Let's generate some prompts that are _nearly_ possible, but should result in the `reject_request` function being called. To do so, we queried `gpt-4o` asking for requests that are related to, but not quite possible with, the given list of functions.



```python
reject_list = [
    "Translate broadcast message to another language",
    "Automatically capture photos when face is detected",
    "Detect nearby drones",
    "Measure wind resistance",
    "Capture slow motion video",
    "Move the drone forward and backward by same distance at the same time.",
    "Adjust drone's altitude to ground level changes",
    "Display custom message on LED display",
    "Sync drone's time with smartphone",
    "Alert when drone travels out of designated area",
    "Calibrate sensors and land simultaneously",
    "Detect moisture levels",
    "Automatically follow GPS tagged object",
    "Toggle night vision mode",
    "Maintain current altitude when battery is low",
    "Decide best landing spot using AI",
    "Program drone's route based on wind direction",
]
```


```python
reject_training_list = []
for prompt in reject_list:
    # Adjust formatting
    tool_calls = [
        {
            "id": "call_id",
            "type": "function",
            "function": {"name": "reject_request", "arguments": "{}"},
        }
    ]
    reject_training_list.append(
        {
            "messages": [
                {"role": "system", "content": DRONE_SYSTEM_PROMPT},
                {"role": "user", "content": prompt},
                {"role": "assistant", "tool_calls": tool_calls},
            ],
            "parallel_tool_calls": False,
            "tools": modified_function_list,
        }
    )
```

Now combine all the training examples together



```python
training_list_total = training_examples + reject_training_list
```


```python
training_file = "data/drone_training.jsonl"
with open(training_file, "w") as f:
    for item in training_list_total:
        json_str = json.dumps(item)
        f.write(f"{json_str}\n")
```

# Fine tuning


Finally, we can kick off the fine-tuning job


key: _node_content
string_value:
{"id_": "9edf2869-bb12-4660-b689-e8a3653a16bf", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6c58932e-9140-45ab-a012-d5750a5f1d6d", "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": "0a655fb8d75245d5ebd45b660efa26b488d16bfe4a7f8cd4e26d09f54cec8acc", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6885e9bf-916f-428c-86a8-e40d28ababdf", "node_type": "1", "metadata": {}, "hash": "0e32d6c301c6ed367dd287503dcdf5f16e20361765e7d170c43ff05f9dd8a968", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 62126, "end_char_idx": 64872, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
reject_training_list = []
for prompt in reject_list:
    # Adjust formatting
    tool_calls = [
        {
            "id": "call_id",
            "type": "function",
            "function": {"name": "reject_request", "arguments": "{}"},
        }
    ]
    reject_training_list.append(
        {
            "messages": [
                {"role": "system", "content": DRONE_SYSTEM_PROMPT},
                {"role": "user", "content": prompt},
                {"role": "assistant", "tool_calls": tool_calls},
            ],
            "parallel_tool_calls": False,
            "tools": modified_function_list,
        }
    )
```

Now combine all the training examples together



```python
training_list_total = training_examples + reject_training_list
```


```python
training_file = "data/drone_training.jsonl"
with open(training_file, "w") as f:
    for item in training_list_total:
        json_str = json.dumps(item)
        f.write(f"{json_str}\n")
```

# Fine tuning


Finally, we can kick off the fine-tuning job



```python
# Upload the training file
file = client.files.create(
    file=open("data/drone_training.jsonl", "rb"),
    purpose="fine-tune",
)
file_id = file.id
print(f"FileID: {file_id}")

# Create a fine-tuning job

ft = client.fine_tuning.jobs.create(
    model="gpt-3.5-turbo",
    training_file=file_id,
    suffix="drone",
)

print(f"Fine-tuning job created: {ft}")
```

    FileID: file-blg0IytwIivZQzc9mbfnS8Pm
    Fine-tuning job created: FineTuningJob(id='ftjob-84PQg97hoIAKf21IPnhiNlU1', created_at=1718580285, error=Error(code=None, message=None, param=None), fine_tuned_model=None, finished_at=None, hyperparameters=Hyperparameters(n_epochs='auto', batch_size='auto', learning_rate_multiplier='auto'), model='gpt-3.5-turbo-0125', object='fine_tuning.job', organization_id='org-lb41cclBdkq5pm6BgDhx8DHP', result_files=[], seed=1513865891, status='validating_files', trained_tokens=None, training_file='file-blg0IytwIivZQzc9mbfnS8Pm', validation_file=None, estimated_finish=None, integrations=[], user_provided_suffix='drone')


In addition to creating a fine-tuning job, you can also list existing jobs, retrieve the status of a job, or cancel a job.



```python
ftjob_id = "ftjob-84PQg97hoIAKf21IPnhiNlU1"
# List 10 fine-tuning jobs
# client.fine_tuning.jobs.list(limit=10)

# Retrieve the state of a fine-tune
client.fine_tuning.jobs.retrieve(ftjob_id)

# Cancel a job
# client.fine_tuning.jobs.cancel("ftjob-abc123")

# List up to 10 events from a fine-tuning job
# client.fine_tuning.jobs.list_events(fine_tuning_job_id="ftjob-abc123", limit=10)

# Delete a fine-tuned model (must be an owner of the org the model was created in)
# client.models.delete("ft:gpt-3.5-turbo:abc:suffix:abc123")
```


key: _node_content
string_value:
{"id_": "6885e9bf-916f-428c-86a8-e40d28ababdf", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9edf2869-bb12-4660-b689-e8a3653a16bf", "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": "8ba3739cfafb9214f72506904d6456f1a9112f8d064ad0cfe48a144965dd9058", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4f065ed2-b92a-4fb6-8198-9d896ce67930", "node_type": "1", "metadata": {}, "hash": "ed10c97f446ea5370f11505fba19064dd2f9761643787c41d01f58ea4522fa88", "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:
In addition to creating a fine-tuning job, you can also list existing jobs, retrieve the status of a job, or cancel a job.



```python
ftjob_id = "ftjob-84PQg97hoIAKf21IPnhiNlU1"
# List 10 fine-tuning jobs
# client.fine_tuning.jobs.list(limit=10)

# Retrieve the state of a fine-tune
client.fine_tuning.jobs.retrieve(ftjob_id)

# Cancel a job
# client.fine_tuning.jobs.cancel("ftjob-abc123")

# List up to 10 events from a fine-tuning job
# client.fine_tuning.jobs.list_events(fine_tuning_job_id="ftjob-abc123", limit=10)

# Delete a fine-tuned model (must be an owner of the org the model was created in)
# client.models.delete("ft:gpt-3.5-turbo:abc:suffix:abc123")
```




    FineTuningJob(id='ftjob-84PQg97hoIAKf21IPnhiNlU1', created_at=1718580285, error=Error(code=None, message=None, param=None), fine_tuned_model='ft:gpt-3.5-turbo-0125:openai-gtm:drone:9atiPjeC', finished_at=1718581004, hyperparameters=Hyperparameters(n_epochs=3, batch_size=1, learning_rate_multiplier=2), model='gpt-3.5-turbo-0125', object='fine_tuning.job', organization_id='org-lb41cclBdkq5pm6BgDhx8DHP', result_files=['file-F6XPJFLVG9f3mR04KBmwUI9H'], seed=1513865891, status='succeeded', trained_tokens=145983, training_file='file-blg0IytwIivZQzc9mbfnS8Pm', validation_file=None, estimated_finish=None, integrations=[], user_provided_suffix='drone')



After a fine-tuning job has finished, you can also see metrics around how the training process went by querying a fine-tuning job, extracting a file ID from the result_files, and then retrieving that files content. Each results CSV file has the following columns: step, train_loss, train_accuracy, valid_loss, and valid_mean_token_accuracy. While metrics can he helpful, evaluating samples from the fine-tuned model provides the most relevant sense of model quality.



```python
fine_tune_results = client.fine_tuning.jobs.retrieve(ftjob_id).result_files
result_file_id = client.files.retrieve(fine_tune_results[0]).id

# Retrieve the result file
result_file = client.files.content(file_id=result_file_id)
decoded_content = base64.b64decode(result_file.read()).decode("utf-8")
print(decoded_content)
```

    step,train_loss,train_accuracy,valid_loss,valid_mean_token_accuracy
    1,3.63265,0.5,
    2,2.45992,0.80952,
    3,2.77939,0.80952,
    4,3.53073,0.65,
    5,2.61654,0.8,
    6,2.16,0.85714,
    7,2.73706,0.8,
    8,2.56944,0.625,
    9,2.06096,0.78947,


key: _node_content
string_value:
{"id_": "4f065ed2-b92a-4fb6-8198-9d896ce67930", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6885e9bf-916f-428c-86a8-e40d28ababdf", "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": "096e46b707c84199892128973c1f6bc4df07cef93f43fbbaf0d43c84867b00d8", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b0788c7e-a993-41d0-95df-7413a8610c42", "node_type": "1", "metadata": {}, "hash": "6ff5d6ca3070ea80a38552907819697d6cefb2c5ba678771185038dccbfe2f22", "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:
After a fine-tuning job has finished, you can also see metrics around how the training process went by querying a fine-tuning job, extracting a file ID from the result_files, and then retrieving that files content. Each results CSV file has the following columns: step, train_loss, train_accuracy, valid_loss, and valid_mean_token_accuracy. While metrics can he helpful, evaluating samples from the fine-tuned model provides the most relevant sense of model quality.



```python
fine_tune_results = client.fine_tuning.jobs.retrieve(ftjob_id).result_files
result_file_id = client.files.retrieve(fine_tune_results[0]).id

# Retrieve the result file
result_file = client.files.content(file_id=result_file_id)
decoded_content = base64.b64decode(result_file.read()).decode("utf-8")
print(decoded_content)
```

    step,train_loss,train_accuracy,valid_loss,valid_mean_token_accuracy
    1,3.63265,0.5,
    2,2.45992,0.80952,
    3,2.77939,0.80952,
    4,3.53073,0.65,
    5,2.61654,0.8,
    6,2.16,0.85714,
    7,2.73706,0.8,
    8,2.56944,0.625,
    9,2.06096,0.78947,
    10,1.69598,0.8,
    11,1.94268,0.77778,
    12,1.61752,0.86667,
    13,1.2442,0.8,
    14,0.73411,0.875,
    15,0.34285,0.875,
    16,0.22229,0.95238,
    17,0.04635,0.95,
    18,0.00626,1.0,
    19,0.60888,0.90909,
    20,0.00092,1.0,
    21,0.8001,0.95,
    22,0.04982,1.0,
    23,0.35494,0.92857,
    24,0.00023,1.0,
    25,0.00034,1.0,
    26,0.0029,1.0,
    27,0.58017,0.875,
    28,0.13018,0.9375,
    29,0.00109,1.0,
    30,6e-05,1.0,
    31,0.61665,0.95,
    32,3e-05,1.0,
    33,0.23598,0.95,
    34,3e-05,1.0,
    35,0.03566,1.0,
    36,1e-05,1.0,
    37,1e-05,1.0,
    38,2e-05,1.0,
    39,2e-05,1.0,
    40,0.00034,1.0,


key: _node_content
string_value:
{"id_": "b0788c7e-a993-41d0-95df-7413a8610c42", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4f065ed2-b92a-4fb6-8198-9d896ce67930", "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": "f1a85244a376ae05c10e6749c9c1599e35e583256cb0223440fef3ce5dbd6e84", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f1f38175-2295-432a-920f-99c08a4e5317", "node_type": "1", "metadata": {}, "hash": "ba9e5b58a54751dad74772258f171edc70d5ab149e399d7b60c45916cdb1b08b", "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:
86667,
    13,1.2442,0.8,
    14,0.73411,0.875,
    15,0.34285,0.875,
    16,0.22229,0.95238,
    17,0.04635,0.95,
    18,0.00626,1.0,
    19,0.60888,0.90909,
    20,0.00092,1.0,
    21,0.8001,0.95,
    22,0.04982,1.0,
    23,0.35494,0.92857,
    24,0.00023,1.0,
    25,0.00034,1.0,
    26,0.0029,1.0,
    27,0.58017,0.875,
    28,0.13018,0.9375,
    29,0.00109,1.0,
    30,6e-05,1.0,
    31,0.61665,0.95,
    32,3e-05,1.0,
    33,0.23598,0.95,
    34,3e-05,1.0,
    35,0.03566,1.0,
    36,1e-05,1.0,
    37,1e-05,1.0,
    38,2e-05,1.0,
    39,2e-05,1.0,
    40,0.00034,1.0,
    41,0.0,1.0,
    42,0.0,1.0,
    43,0.0,1.0,
    44,0.0,1.0,
    45,0.0,1.0,
    46,0.91896,0.95,
    47,0.0,1.0,
    48,0.12006,0.95,
    49,0.0,1.0,
    50,3.92872,0.75,
    51,0.0,1.0,
    52,0.98277,0.90476,
    53,0.0,1.0,
    54,0.0,1.0,
    55,1e-05,1.0,
    56,0.00401,1.0,
    57,0.07366,1.0,
    58,0.0,1.0,
    59,0.0,1.0,
    60,0.0,1.0,
    61,0.0,1.0,
    62,0.10347,0.875,
    63,0.0,1.0,
    64,0.0,1.0,
    65,1e-05,1.0,
    66,2.97112,0.85714,
    67,1.12396,0.875,
    68,2e-05,


key: _node_content
string_value:
{"id_": "f1f38175-2295-432a-920f-99c08a4e5317", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b0788c7e-a993-41d0-95df-7413a8610c42", "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": "92a5ae16c405fbf376e3019c7980885160a98c3bbbbe9b96cbedb4f2c902a1ee", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4a2a6c29-8a6d-4eaa-9373-3e302b088b7e", "node_type": "1", "metadata": {}, "hash": "c0c71ec11b527bc840168a4c135b213a458783e152d5ee6931b64ae4c7d40822", "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:
2e-05,1.0,
    40,0.00034,1.0,
    41,0.0,1.0,
    42,0.0,1.0,
    43,0.0,1.0,
    44,0.0,1.0,
    45,0.0,1.0,
    46,0.91896,0.95,
    47,0.0,1.0,
    48,0.12006,0.95,
    49,0.0,1.0,
    50,3.92872,0.75,
    51,0.0,1.0,
    52,0.98277,0.90476,
    53,0.0,1.0,
    54,0.0,1.0,
    55,1e-05,1.0,
    56,0.00401,1.0,
    57,0.07366,1.0,
    58,0.0,1.0,
    59,0.0,1.0,
    60,0.0,1.0,
    61,0.0,1.0,
    62,0.10347,0.875,
    63,0.0,1.0,
    64,0.0,1.0,
    65,1e-05,1.0,
    66,2.97112,0.85714,
    67,1.12396,0.875,
    68,2e-05,1.0,
    69,0.00067,1.0,
    70,0.0,1.0,
    71,0.0,1.0,
    72,0.0,1.0,
    73,0.0,1.0,
    74,0.0,1.0,
    75,0.02064,1.0,
    76,0.5146,0.86667,
    77,0.18756,0.95,
    78,6e-05,1.0,
    79,0.0,1.0,
    80,0.21298,0.93333,
    81,0.0,1.0,
    82,0.0,1.0,
    83,0.0,1.0,
    84,0.00139,1.0,
    85,0.0,1.0,
    86,0.85297,0.875,
    87,0.0,1.0,
    88,0.0,1.0,
    89,1.45164,0.875,
    90,0.0,1.0,
    91,0.05329,0.92857,
    92,0.55506,0.93333,
    93,0.42187,0.92857,
    94,0.0,1.0,
    95,0.0,1.0,


key: _node_content
string_value:
{"id_": "4a2a6c29-8a6d-4eaa-9373-3e302b088b7e", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f1f38175-2295-432a-920f-99c08a4e5317", "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": "562ebd256f0595bfbdfd0fddc08e58e453ebb2c51e08c76e4c5f9159fcd6c0e0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4737d63d-361b-447c-a2f7-67a5159523d4", "node_type": "1", "metadata": {}, "hash": "658db7898fc4f64fa195b9bea209c4f54dceef54d0130a0b1b7654fbbe4f7b1a", "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:
85714,
    67,1.12396,0.875,
    68,2e-05,1.0,
    69,0.00067,1.0,
    70,0.0,1.0,
    71,0.0,1.0,
    72,0.0,1.0,
    73,0.0,1.0,
    74,0.0,1.0,
    75,0.02064,1.0,
    76,0.5146,0.86667,
    77,0.18756,0.95,
    78,6e-05,1.0,
    79,0.0,1.0,
    80,0.21298,0.93333,
    81,0.0,1.0,
    82,0.0,1.0,
    83,0.0,1.0,
    84,0.00139,1.0,
    85,0.0,1.0,
    86,0.85297,0.875,
    87,0.0,1.0,
    88,0.0,1.0,
    89,1.45164,0.875,
    90,0.0,1.0,
    91,0.05329,0.92857,
    92,0.55506,0.93333,
    93,0.42187,0.92857,
    94,0.0,1.0,
    95,0.0,1.0,
    96,0.0,1.0,
    97,0.0,1.0,
    98,0.0,1.0,
    99,0.0,1.0,
    100,0.0,1.0,
    101,0.0,1.0,
    102,0.0,1.0,
    103,0.09194,0.95455,
    104,0.0,1.0,
    105,0.0,1.0,
    106,0.05531,0.95,
    107,0.0,1.0,
    108,0.39621,0.95238,
    109,0.0,1.0,
    110,0.8449,0.95,
    111,0.01258,1.0,
    112,0.0,1.0,
    113,0.0,1.0,
    114,0.0,1.0,
    115,0.00355,1.0,
    116,0.0,1.0,
    117,0.3954,0.94118,
    118,0.00259,1.0,
    119,0.0,1.0,
    120,0.0,1.0,
    121,0.35876,0.95,
    122,0.0,1.0,
    123,0.0,1.


key: _node_content
string_value:
{"id_": "4737d63d-361b-447c-a2f7-67a5159523d4", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4a2a6c29-8a6d-4eaa-9373-3e302b088b7e", "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": "7170e582efe33c5193177555dd8cb6f9301c4af7796ae067997569aaff289217", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "214728b7-785d-418f-92fc-866b0af6b272", "node_type": "1", "metadata": {}, "hash": "7c623d6051c360588130e60d9b3afe240ef4a0588a94f390124282dff50a7767", "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:
94,0.0,1.0,
    95,0.0,1.0,
    96,0.0,1.0,
    97,0.0,1.0,
    98,0.0,1.0,
    99,0.0,1.0,
    100,0.0,1.0,
    101,0.0,1.0,
    102,0.0,1.0,
    103,0.09194,0.95455,
    104,0.0,1.0,
    105,0.0,1.0,
    106,0.05531,0.95,
    107,0.0,1.0,
    108,0.39621,0.95238,
    109,0.0,1.0,
    110,0.8449,0.95,
    111,0.01258,1.0,
    112,0.0,1.0,
    113,0.0,1.0,
    114,0.0,1.0,
    115,0.00355,1.0,
    116,0.0,1.0,
    117,0.3954,0.94118,
    118,0.00259,1.0,
    119,0.0,1.0,
    120,0.0,1.0,
    121,0.35876,0.95,
    122,0.0,1.0,
    123,0.0,1.0,
    124,5e-05,1.0,
    125,0.0,1.0,
    126,0.0,1.0,
    127,0.0,1.0,
    128,0.0,1.0,
    129,0.0,1.0,
    130,0.01336,1.0,
    131,0.0,1.0,
    132,0.23362,0.95,
    133,0.00157,1.0,
    134,0.0,1.0,
    135,0.00031,1.0,
    136,0.0,1.0,
    137,0.08313,0.92857,
    138,0.0,1.0,
    139,0.0,1.0,
    140,0.0,1.0,
    141,0.43608,0.95,
    142,0.0,1.0,
    143,0.0,1.0,
    144,0.0,1.0,
    145,2e-05,1.0,
    146,1.20409,0.85714,
    147,0.0,1.0,
    148,0.0,1.0,
    149,0.0,1.0,
    150,0.0,1.0,
    151,0.0,


key: _node_content
string_value:
{"id_": "214728b7-785d-418f-92fc-866b0af6b272", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4737d63d-361b-447c-a2f7-67a5159523d4", "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": "91237fc3b5512937497e96f17ea5127499b6fe7650bf6470145d90ff8d8ec6ab", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "160079b9-388d-4e80-acce-d74e9213c4b1", "node_type": "1", "metadata": {}, "hash": "850c8cec2b98aabd1fc34852e06648089482fa91fd3693e0f61389434564d9e1", "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:
95,
    122,0.0,1.0,
    123,0.0,1.0,
    124,5e-05,1.0,
    125,0.0,1.0,
    126,0.0,1.0,
    127,0.0,1.0,
    128,0.0,1.0,
    129,0.0,1.0,
    130,0.01336,1.0,
    131,0.0,1.0,
    132,0.23362,0.95,
    133,0.00157,1.0,
    134,0.0,1.0,
    135,0.00031,1.0,
    136,0.0,1.0,
    137,0.08313,0.92857,
    138,0.0,1.0,
    139,0.0,1.0,
    140,0.0,1.0,
    141,0.43608,0.95,
    142,0.0,1.0,
    143,0.0,1.0,
    144,0.0,1.0,
    145,2e-05,1.0,
    146,1.20409,0.85714,
    147,0.0,1.0,
    148,0.0,1.0,
    149,0.0,1.0,
    150,0.0,1.0,
    151,0.0,1.0,
    152,0.0,1.0,
    153,0.0,1.0,
    154,0.00063,1.0,
    155,0.0,1.0,
    156,0.0,1.0,
    157,0.0,1.0,
    158,6e-05,1.0,
    159,0.0,1.0,
    160,0.0,1.0,
    161,0.0,1.0,
    162,0.0,1.0,
    163,0.0,1.0,
    164,0.0,1.0,
    165,0.0,1.0,
    166,0.0,1.0,
    167,0.0,1.0,
    168,0.0,1.0,
    169,0.0,1.0,
    170,0.0,1.0,
    171,0.0,1.0,
    172,0.0,1.0,
    173,0.0,1.0,
    174,0.00783,1.0,
    175,0.0,1.0,
    176,0.0,1.0,
    177,0.0,1.0,
    178,0.0,1.0,
    179,0.0,1.0,


key: _node_content
string_value:
{"id_": "160079b9-388d-4e80-acce-d74e9213c4b1", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "214728b7-785d-418f-92fc-866b0af6b272", "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": "8bf50d041c21e6ff8976854b033cb37a2dc145b6c83c3a0020842ea8a82e3cdd", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2fccd9f4-19a8-4ae3-84b1-694c9ba2c496", "node_type": "1", "metadata": {}, "hash": "3abca7580ccc1db1efdd5ac3ebda231a4ee2ec11aa033ead7cd9e828608435d5", "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:
0,1.0,
    150,0.0,1.0,
    151,0.0,1.0,
    152,0.0,1.0,
    153,0.0,1.0,
    154,0.00063,1.0,
    155,0.0,1.0,
    156,0.0,1.0,
    157,0.0,1.0,
    158,6e-05,1.0,
    159,0.0,1.0,
    160,0.0,1.0,
    161,0.0,1.0,
    162,0.0,1.0,
    163,0.0,1.0,
    164,0.0,1.0,
    165,0.0,1.0,
    166,0.0,1.0,
    167,0.0,1.0,
    168,0.0,1.0,
    169,0.0,1.0,
    170,0.0,1.0,
    171,0.0,1.0,
    172,0.0,1.0,
    173,0.0,1.0,
    174,0.00783,1.0,
    175,0.0,1.0,
    176,0.0,1.0,
    177,0.0,1.0,
    178,0.0,1.0,
    179,0.0,1.0,
    180,0.0,1.0,
    181,0.0,1.0,
    182,0.00028,1.0,
    183,0.0,1.0,
    184,0.0,1.0,
    185,0.0003,1.0,
    186,0.0,1.0,
    187,0.0,1.0,
    188,0.0,1.0,
    189,0.0,1.0,
    190,0.0,1.0,
    191,0.0,1.0,
    192,0.0,1.0,
    193,0.00013,1.0,
    194,0.86198,0.875,
    195,0.0,1.0,
    196,0.0,1.0,
    197,0.0,1.0,
    198,0.0,1.0,
    199,0.0,1.0,
    200,0.0,1.0,
    201,0.0,1.0,
    202,0.0,1.0,
    203,0.0,1.0,
    204,0.09954,0.95455,
    205,0.0,1.0,
    206,0.0,1.0,
    207,0.0,1.0,


key: _node_content
string_value:
{"id_": "2fccd9f4-19a8-4ae3-84b1-694c9ba2c496", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "160079b9-388d-4e80-acce-d74e9213c4b1", "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": "158890e297d2c20ede3cada0c5c926baa40a9774187c0e18a110fec719efecb4", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "cfb9c7ec-4ff9-4125-965a-86bd7bc8b117", "node_type": "1", "metadata": {}, "hash": "eed758f7d00c8064ee0d09f9e8eea3f2b222476ab1baa84fb1c2e482fd6e71a6", "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:
1.0,
    178,0.0,1.0,
    179,0.0,1.0,
    180,0.0,1.0,
    181,0.0,1.0,
    182,0.00028,1.0,
    183,0.0,1.0,
    184,0.0,1.0,
    185,0.0003,1.0,
    186,0.0,1.0,
    187,0.0,1.0,
    188,0.0,1.0,
    189,0.0,1.0,
    190,0.0,1.0,
    191,0.0,1.0,
    192,0.0,1.0,
    193,0.00013,1.0,
    194,0.86198,0.875,
    195,0.0,1.0,
    196,0.0,1.0,
    197,0.0,1.0,
    198,0.0,1.0,
    199,0.0,1.0,
    200,0.0,1.0,
    201,0.0,1.0,
    202,0.0,1.0,
    203,0.0,1.0,
    204,0.09954,0.95455,
    205,0.0,1.0,
    206,0.0,1.0,
    207,0.0,1.0,
    208,1.9616,0.9375,
    209,0.0,1.0,
    210,0.0,1.0,
    211,0.0,1.0,
    212,0.0,1.0,
    213,0.0,1.0,
    214,0.0,1.0,
    215,0.0,1.0,
    216,0.0,1.0,
    217,0.0,1.0,
    218,0.0,1.0,
    219,0.0,1.0,
    220,0.0,1.0,
    221,0.0,1.0,
    222,0.0,1.0,
    223,0.0,1.0,
    224,0.0,1.0,
    225,0.0,1.0,
    226,0.00174,1.0,
    227,0.0,1.0,
    228,2e-05,1.0,
    229,0.0,1.0,
    230,0.0,1.0,
    231,0.0,1.0,
    232,0.0,1.0,
    233,0.0,1.0,
    234,0.61895,0.95,
    235,0.0,1.0,


key: _node_content
string_value:
{"id_": "cfb9c7ec-4ff9-4125-965a-86bd7bc8b117", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2fccd9f4-19a8-4ae3-84b1-694c9ba2c496", "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": "713fca42d23a81dff1e04d764d370c7d77a3499aa2ce345982d4652cbbcc682b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d8676b52-c9fe-485b-a11b-24dc7a353c33", "node_type": "1", "metadata": {}, "hash": "d1c0e9b66d12512ea9ad4956bb60afcd06739c51d3b46970889de6e8ba986e3b", "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:
1.0,
    206,0.0,1.0,
    207,0.0,1.0,
    208,1.9616,0.9375,
    209,0.0,1.0,
    210,0.0,1.0,
    211,0.0,1.0,
    212,0.0,1.0,
    213,0.0,1.0,
    214,0.0,1.0,
    215,0.0,1.0,
    216,0.0,1.0,
    217,0.0,1.0,
    218,0.0,1.0,
    219,0.0,1.0,
    220,0.0,1.0,
    221,0.0,1.0,
    222,0.0,1.0,
    223,0.0,1.0,
    224,0.0,1.0,
    225,0.0,1.0,
    226,0.00174,1.0,
    227,0.0,1.0,
    228,2e-05,1.0,
    229,0.0,1.0,
    230,0.0,1.0,
    231,0.0,1.0,
    232,0.0,1.0,
    233,0.0,1.0,
    234,0.61895,0.95,
    235,0.0,1.0,
    236,0.0,1.0,
    237,0.0,1.0,
    238,0.0,1.0,
    239,0.54945,0.95,
    240,0.0,1.0,
    241,0.0,1.0,
    242,1.52953,0.9375,
    243,1.19938,0.85714,
    244,0.0,1.0,
    245,0.0,1.0,
    246,0.0,1.0,
    247,0.0,1.0,
    248,8e-05,1.0,
    249,0.0,1.0,
    250,0.0,1.0,
    251,0.0,1.0,
    252,0.0,1.0,
    253,0.0,1.0,
    254,0.0,1.0,
    255,0.0,1.0,
    256,0.0,1.0,
    257,0.0,1.0,
    258,0.0,1.0,
    259,0.0,1.0,
    260,0.0,1.0,
    261,0.0,1.0,
    262,0.0,1.0,
    263,0.0,1.0,


key: _node_content
string_value:
{"id_": "d8676b52-c9fe-485b-a11b-24dc7a353c33", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "cfb9c7ec-4ff9-4125-965a-86bd7bc8b117", "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": "a7144847d4ad78b9279c95ec5555d90da9f56214e41120848d83e1d293e8cb1d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c8fd4047-d692-4477-bd13-1d6cf69115b2", "node_type": "1", "metadata": {}, "hash": "58254f10e49445051b507beea5527e779dce00a0c4271dab712663a523086c9d", "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:
0,
    234,0.61895,0.95,
    235,0.0,1.0,
    236,0.0,1.0,
    237,0.0,1.0,
    238,0.0,1.0,
    239,0.54945,0.95,
    240,0.0,1.0,
    241,0.0,1.0,
    242,1.52953,0.9375,
    243,1.19938,0.85714,
    244,0.0,1.0,
    245,0.0,1.0,
    246,0.0,1.0,
    247,0.0,1.0,
    248,8e-05,1.0,
    249,0.0,1.0,
    250,0.0,1.0,
    251,0.0,1.0,
    252,0.0,1.0,
    253,0.0,1.0,
    254,0.0,1.0,
    255,0.0,1.0,
    256,0.0,1.0,
    257,0.0,1.0,
    258,0.0,1.0,
    259,0.0,1.0,
    260,0.0,1.0,
    261,0.0,1.0,
    262,0.0,1.0,
    263,0.0,1.0,
    264,0.0,1.0,
    265,0.0,1.0,
    266,0.0,1.0,
    267,0.88984,0.95,
    268,0.0,1.0,
    269,0.0,1.0,
    270,0.0,1.0,
    271,0.0,1.0,
    272,0.0,1.0,
    273,0.0,1.0,
    274,0.0,1.0,
    275,0.00013,1.0,
    276,0.0,1.0,
    277,0.89825,0.92857,
    278,0.0,1.0,
    279,0.00017,1.0,
    280,0.0,1.0,
    281,0.0,1.0,
    282,0.0,1.0,
    283,0.65667,0.95,
    284,0.0,1.0,
    285,0.0,1.0,
    286,0.0,1.0,
    287,0.0,1.0,
    288,0.0,1.0,
    289,0.0,1.0,
    290,0.0,1.0,
    291,0.0,1.0,


key: _node_content
string_value:
{"id_": "c8fd4047-d692-4477-bd13-1d6cf69115b2", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d8676b52-c9fe-485b-a11b-24dc7a353c33", "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": "a2bd3c9ea50e2a1d85dfe12958e32a54d07fb22ea62108b3d01d11f9aceb01b7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ea83e154-b210-4317-9071-7c2bee0c0348", "node_type": "1", "metadata": {}, "hash": "c5001b785b733e56ad0bd8015dd80728df1aab6e65fdf650cbbd9d562fc1b2a0", "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:
1.0,
    262,0.0,1.0,
    263,0.0,1.0,
    264,0.0,1.0,
    265,0.0,1.0,
    266,0.0,1.0,
    267,0.88984,0.95,
    268,0.0,1.0,
    269,0.0,1.0,
    270,0.0,1.0,
    271,0.0,1.0,
    272,0.0,1.0,
    273,0.0,1.0,
    274,0.0,1.0,
    275,0.00013,1.0,
    276,0.0,1.0,
    277,0.89825,0.92857,
    278,0.0,1.0,
    279,0.00017,1.0,
    280,0.0,1.0,
    281,0.0,1.0,
    282,0.0,1.0,
    283,0.65667,0.95,
    284,0.0,1.0,
    285,0.0,1.0,
    286,0.0,1.0,
    287,0.0,1.0,
    288,0.0,1.0,
    289,0.0,1.0,
    290,0.0,1.0,
    291,0.0,1.0,
    292,0.28626,0.95238,
    293,0.0,1.0,
    294,0.0,1.0,
    295,0.0,1.0,
    296,0.0,1.0,
    297,0.0,1.0,
    298,0.0,1.0,
    299,0.0,1.0,
    300,0.0,1.0,
    301,0.0,1.0,
    302,0.0,1.0,
    303,0.0,1.0,
    304,0.0,1.0,
    305,0.0,1.0,
    306,0.0,1.0,
    307,0.0,1.0,
    308,0.0,1.0,
    309,0.0,1.0,
    


# Evaluations


Great! We trained a fine-tuned model for function calling. Let's see how it does on our evaluation set for prompts that the drone assistant
should automatically reject.


key: _node_content
string_value:
{"id_": "ea83e154-b210-4317-9071-7c2bee0c0348", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c8fd4047-d692-4477-bd13-1d6cf69115b2", "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": "c34b7a78a29c78dbfa6dcfef5b73409f0e113b978387eb47330645f19f867aa0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "09c270b8-5cbb-4e01-946c-0f9e03af43c8", "node_type": "1", "metadata": {}, "hash": "4572b15d11d6be83b84cf49475beadd57f41321143bd73586a91d431e80be08a", "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:
1.0,
    283,0.65667,0.95,
    284,0.0,1.0,
    285,0.0,1.0,
    286,0.0,1.0,
    287,0.0,1.0,
    288,0.0,1.0,
    289,0.0,1.0,
    290,0.0,1.0,
    291,0.0,1.0,
    292,0.28626,0.95238,
    293,0.0,1.0,
    294,0.0,1.0,
    295,0.0,1.0,
    296,0.0,1.0,
    297,0.0,1.0,
    298,0.0,1.0,
    299,0.0,1.0,
    300,0.0,1.0,
    301,0.0,1.0,
    302,0.0,1.0,
    303,0.0,1.0,
    304,0.0,1.0,
    305,0.0,1.0,
    306,0.0,1.0,
    307,0.0,1.0,
    308,0.0,1.0,
    309,0.0,1.0,
    


# Evaluations


Great! We trained a fine-tuned model for function calling. Let's see how it does on our evaluation set for prompts that the drone assistant
should automatically reject.



```python
ft_model = "ft:gpt-3.5-turbo-0125:openai-gtm:drone:9atiPjeC"
base_model = "gpt-3.5-turbo"

print(f"\nEvaluating fine-tuned model with challenging prompts: {ft_model}")
eval(
    model=ft_model,
    function_list=modified_function_list,
    system_prompt=DRONE_SYSTEM_PROMPT,
    prompts_to_expected_tool_name=challenging_prompts_to_expected,
)

print(f"\nEvaluating base model with challenging prompts: {base_model}")
eval(
    model="gpt-3.5-turbo",
    function_list=function_list,
    system_prompt=DRONE_SYSTEM_PROMPT,
    prompts_to_expected_tool_name=challenging_prompts_to_expected,
)
```

    
    Evaluating fine-tuned model with challenging prompts: ft:gpt-3.5-turbo-0125:openai-gtm:drone:9atiPjeC



<style type="text/css">
#T_9f4fa_row0_col0, #T_9f4fa_row0_col1, #T_9f4fa_row0_col2, #T_9f4fa_row0_col3, #T_9f4fa_row1_col0, #T_9f4fa_row1_col1, #T_9f4fa_row1_col2, #T_9f4fa_row1_col3, #T_9f4fa_row2_col0, #T_9f4fa_row2_col1, #T_9f4fa_row2_col2, #T_9f4fa_row2_col3,


key: _node_content
string_value:
{"id_": "09c270b8-5cbb-4e01-946c-0f9e03af43c8", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ea83e154-b210-4317-9071-7c2bee0c0348", "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": "7f591e582d1addab371cced07e32269a0b42af1ff49b9d848bc4f51a7c135c2c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "cfdf203a-69d5-4b06-ab55-75b342ab5be2", "node_type": "1", "metadata": {}, "hash": "8ea7dea9e11f1650c6359a76e4a4d12d28e31739f73514d40d2b6bf2d9bb84ee", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 72581, "end_char_idx": 74299, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
ft_model = "ft:gpt-3.5-turbo-0125:openai-gtm:drone:9atiPjeC"
base_model = "gpt-3.5-turbo"

print(f"\nEvaluating fine-tuned model with challenging prompts: {ft_model}")
eval(
    model=ft_model,
    function_list=modified_function_list,
    system_prompt=DRONE_SYSTEM_PROMPT,
    prompts_to_expected_tool_name=challenging_prompts_to_expected,
)

print(f"\nEvaluating base model with challenging prompts: {base_model}")
eval(
    model="gpt-3.5-turbo",
    function_list=function_list,
    system_prompt=DRONE_SYSTEM_PROMPT,
    prompts_to_expected_tool_name=challenging_prompts_to_expected,
)
```

    
    Evaluating fine-tuned model with challenging prompts: ft:gpt-3.5-turbo-0125:openai-gtm:drone:9atiPjeC



<style type="text/css">
#T_9f4fa_row0_col0, #T_9f4fa_row0_col1, #T_9f4fa_row0_col2, #T_9f4fa_row0_col3, #T_9f4fa_row1_col0, #T_9f4fa_row1_col1, #T_9f4fa_row1_col2, #T_9f4fa_row1_col3, #T_9f4fa_row2_col0, #T_9f4fa_row2_col1, #T_9f4fa_row2_col2, #T_9f4fa_row2_col3, #T_9f4fa_row3_col0, #T_9f4fa_row3_col1, #T_9f4fa_row3_col2, #T_9f4fa_row3_col3, #T_9f4fa_row4_col0, #T_9f4fa_row4_col1, #T_9f4fa_row4_col2, #T_9f4fa_row4_col3, #T_9f4fa_row5_col0, #T_9f4fa_row5_col1, #T_9f4fa_row5_col2, #T_9f4fa_row5_col3, #T_9f4fa_row6_col0, #T_9f4fa_row6_col1, #T_9f4fa_row6_col2, #T_9f4fa_row6_col3, #T_9f4fa_row7_col0, #T_9f4fa_row7_col1, #T_9f4fa_row7_col2, #T_9f4fa_row7_col3, #T_9f4fa_row8_col0, #T_9f4fa_row8_col1, #T_9f4fa_row8_col2, #T_9f4fa_row8_col3, #T_9f4fa_row9_col0, #T_9f4fa_row9_col1, #T_9f4fa_row9_col2, #T_9f4fa_row9_col3 {
  background-color: white;
  color: black;
}
</style>
<table id="T_9f4fa">
  <thead>
    <tr>
      <th class="blank level0" >&nbsp;</th>
      <th id="T_9f4fa_level0_col0"


key: _node_content
string_value:
{"id_": "cfdf203a-69d5-4b06-ab55-75b342ab5be2", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "09c270b8-5cbb-4e01-946c-0f9e03af43c8", "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": "bba396b5733c691a6d9dbc227dbffc16f74aecc48e073d9851e6999894c80395", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "54449675-7ff9-48cc-ba38-02edf5b8a342", "node_type": "1", "metadata": {}, "hash": "c6334e47a75453334883245f69b5919fa19459a156cfdd35a5ccb8bde0160d83", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 73586, "end_char_idx": 75153, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
#T_9f4fa_row3_col1, #T_9f4fa_row3_col2, #T_9f4fa_row3_col3, #T_9f4fa_row4_col0, #T_9f4fa_row4_col1, #T_9f4fa_row4_col2, #T_9f4fa_row4_col3, #T_9f4fa_row5_col0, #T_9f4fa_row5_col1, #T_9f4fa_row5_col2, #T_9f4fa_row5_col3, #T_9f4fa_row6_col0, #T_9f4fa_row6_col1, #T_9f4fa_row6_col2, #T_9f4fa_row6_col3, #T_9f4fa_row7_col0, #T_9f4fa_row7_col1, #T_9f4fa_row7_col2, #T_9f4fa_row7_col3, #T_9f4fa_row8_col0, #T_9f4fa_row8_col1, #T_9f4fa_row8_col2, #T_9f4fa_row8_col3, #T_9f4fa_row9_col0, #T_9f4fa_row9_col1, #T_9f4fa_row9_col2, #T_9f4fa_row9_col3 {
  background-color: white;
  color: black;
}
</style>
<table id="T_9f4fa">
  <thead>
    <tr>
      <th class="blank level0" >&nbsp;</th>
      <th id="T_9f4fa_level0_col0" class="col_heading level0 col0" >Prompt</th>
      <th id="T_9f4fa_level0_col1" class="col_heading level0 col1" >Actual</th>
      <th id="T_9f4fa_level0_col2" class="col_heading level0 col2" >Expected</th>
      <th id="T_9f4fa_level0_col3" class="col_heading level0 col3" >Match</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th id="T_9f4fa_level0_row0" class="row_heading level0 row0" >0</th>
      <td id="T_9f4fa_row0_col0" class="data row0 col0" >Play pre-recorded audio message</td>
      <td id="T_9f4fa_row0_col1" class="data row0 col1" >reject_request</td>
      <td id="T_9f4fa_row0_col2" class="data row0 col2" >reject_request</td>
      <td id="T_9f4fa_row0_col3" class="data row0 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_9f4fa_level0_row1" class="row_heading level0 row1" >1</th>
      <td id="T_9f4fa_row1_col0" class="data


key: _node_content
string_value:
{"id_": "54449675-7ff9-48cc-ba38-02edf5b8a342", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "cfdf203a-69d5-4b06-ab55-75b342ab5be2", "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": "9bd282a2da36549cc1e29127bbb9c3aacbeb127090d3023adadac1ed8e671375", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b33d82b4-43dd-467d-b48e-582bbc0593f6", "node_type": "1", "metadata": {}, "hash": "163b6b3083ebebefe8687a37fd5bc4408a3af6638730fb1f5dac4deb21acd8a0", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 74271, "end_char_idx": 75988, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
<th id="T_9f4fa_level0_col0" class="col_heading level0 col0" >Prompt</th>
      <th id="T_9f4fa_level0_col1" class="col_heading level0 col1" >Actual</th>
      <th id="T_9f4fa_level0_col2" class="col_heading level0 col2" >Expected</th>
      <th id="T_9f4fa_level0_col3" class="col_heading level0 col3" >Match</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th id="T_9f4fa_level0_row0" class="row_heading level0 row0" >0</th>
      <td id="T_9f4fa_row0_col0" class="data row0 col0" >Play pre-recorded audio message</td>
      <td id="T_9f4fa_row0_col1" class="data row0 col1" >reject_request</td>
      <td id="T_9f4fa_row0_col2" class="data row0 col2" >reject_request</td>
      <td id="T_9f4fa_row0_col3" class="data row0 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_9f4fa_level0_row1" class="row_heading level0 row1" >1</th>
      <td id="T_9f4fa_row1_col0" class="data row1 col0" >Initiate following on social media</td>
      <td id="T_9f4fa_row1_col1" class="data row1 col1" >reject_request</td>
      <td id="T_9f4fa_row1_col2" class="data row1 col2" >reject_request</td>
      <td id="T_9f4fa_row1_col3" class="data row1 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_9f4fa_level0_row2" class="row_heading level0 row2" >2</th>
      <td id="T_9f4fa_row2_col0" class="data row2 col0" >Scan environment for heat signatures</td>
      <td id="T_9f4fa_row2_col1" class="data row2 col1" >reject_request</td>
      <td id="T_9f4fa_row2_col2" class="data row2 col2" >reject_request</td>
      <td id="T_9f4fa_row2_col3" class="data row2 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_9f4fa_level0_row3" class="row_heading level0 row3" >3</th>
      <td id="T_9f4fa_row3_col0" class="data row3 col0"


key: _node_content
string_value:
{"id_": "b33d82b4-43dd-467d-b48e-582bbc0593f6", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "54449675-7ff9-48cc-ba38-02edf5b8a342", "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": "1412ce3a3ddf99c491310e79287baa50540124b25df3982ac70346c1cd48fdd3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "68146dc7-aab3-4463-8c8c-70368e010289", "node_type": "1", "metadata": {}, "hash": "3efd044562dbd2831d3bc288df22c5d428314b8bb8ef2f5e1610b69427a9c0f2", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 75115, "end_char_idx": 76827, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
<td id="T_9f4fa_row1_col0" class="data row1 col0" >Initiate following on social media</td>
      <td id="T_9f4fa_row1_col1" class="data row1 col1" >reject_request</td>
      <td id="T_9f4fa_row1_col2" class="data row1 col2" >reject_request</td>
      <td id="T_9f4fa_row1_col3" class="data row1 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_9f4fa_level0_row2" class="row_heading level0 row2" >2</th>
      <td id="T_9f4fa_row2_col0" class="data row2 col0" >Scan environment for heat signatures</td>
      <td id="T_9f4fa_row2_col1" class="data row2 col1" >reject_request</td>
      <td id="T_9f4fa_row2_col2" class="data row2 col2" >reject_request</td>
      <td id="T_9f4fa_row2_col3" class="data row2 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_9f4fa_level0_row3" class="row_heading level0 row3" >3</th>
      <td id="T_9f4fa_row3_col0" class="data row3 col0" >Bump into obstacles</td>
      <td id="T_9f4fa_row3_col1" class="data row3 col1" >reject_request</td>
      <td id="T_9f4fa_row3_col2" class="data row3 col2" >reject_request</td>
      <td id="T_9f4fa_row3_col3" class="data row3 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_9f4fa_level0_row4" class="row_heading level0 row4" >4</th>
      <td id="T_9f4fa_row4_col0" class="data row4 col0" >Change drone's paint job color</td>
      <td id="T_9f4fa_row4_col1" class="data row4 col1" >reject_request</td>
      <td id="T_9f4fa_row4_col2" class="data row4 col2" >reject_request</td>
      <td id="T_9f4fa_row4_col3" class="data row4 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_9f4fa_level0_row5" class="row_heading level0 row5" >5</th>
      <td id="T_9f4fa_row5_col0" class="data row5 col0" >Coordinate with nearby drones</td>


key: _node_content
string_value:
{"id_": "68146dc7-aab3-4463-8c8c-70368e010289", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b33d82b4-43dd-467d-b48e-582bbc0593f6", "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": "0c700248770dcc85b31ccb725e352ebfced3faece339fb945df91520e8463ce7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "911e52b2-293f-4b9e-8c8d-b1f8ad5afc5f", "node_type": "1", "metadata": {}, "hash": "7002d689ade60da703eaa5fe4ce57c97ceb5790db94612ee4565dfdf2a02bb36", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 75939, "end_char_idx": 77629, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
<td id="T_9f4fa_row3_col0" class="data row3 col0" >Bump into obstacles</td>
      <td id="T_9f4fa_row3_col1" class="data row3 col1" >reject_request</td>
      <td id="T_9f4fa_row3_col2" class="data row3 col2" >reject_request</td>
      <td id="T_9f4fa_row3_col3" class="data row3 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_9f4fa_level0_row4" class="row_heading level0 row4" >4</th>
      <td id="T_9f4fa_row4_col0" class="data row4 col0" >Change drone's paint job color</td>
      <td id="T_9f4fa_row4_col1" class="data row4 col1" >reject_request</td>
      <td id="T_9f4fa_row4_col2" class="data row4 col2" >reject_request</td>
      <td id="T_9f4fa_row4_col3" class="data row4 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_9f4fa_level0_row5" class="row_heading level0 row5" >5</th>
      <td id="T_9f4fa_row5_col0" class="data row5 col0" >Coordinate with nearby drones</td>
      <td id="T_9f4fa_row5_col1" class="data row5 col1" >reject_request</td>
      <td id="T_9f4fa_row5_col2" class="data row5 col2" >reject_request</td>
      <td id="T_9f4fa_row5_col3" class="data row5 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_9f4fa_level0_row6" class="row_heading level0 row6" >6</th>
      <td id="T_9f4fa_row6_col0" class="data row6 col0" >Change speed to negative 120 km/h</td>
      <td id="T_9f4fa_row6_col1" class="data row6 col1" >reject_request</td>
      <td id="T_9f4fa_row6_col2" class="data row6 col2" >reject_request</td>
      <td id="T_9f4fa_row6_col3" class="data row6 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_9f4fa_level0_row7" class="row_heading level0 row7" >7</th>
      <td id="T_9f4fa_row7_col0" class="data row7 col0" >Detect a person</td>


key: _node_content
string_value:
{"id_": "911e52b2-293f-4b9e-8c8d-b1f8ad5afc5f", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "68146dc7-aab3-4463-8c8c-70368e010289", "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": "f08bbfe3287fed4f99beeb2b744f6d70fef9e3fbb808c3791c8a7ed73b7b635a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "fbc5457d-76db-4ca4-94b8-3534b880084f", "node_type": "1", "metadata": {}, "hash": "591d777939cb095f9eadc19389fba03b34a86902bdab92250f087f00a51261f0", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 76769, "end_char_idx": 78478, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
class="data row5 col0" >Coordinate with nearby drones</td>
      <td id="T_9f4fa_row5_col1" class="data row5 col1" >reject_request</td>
      <td id="T_9f4fa_row5_col2" class="data row5 col2" >reject_request</td>
      <td id="T_9f4fa_row5_col3" class="data row5 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_9f4fa_level0_row6" class="row_heading level0 row6" >6</th>
      <td id="T_9f4fa_row6_col0" class="data row6 col0" >Change speed to negative 120 km/h</td>
      <td id="T_9f4fa_row6_col1" class="data row6 col1" >reject_request</td>
      <td id="T_9f4fa_row6_col2" class="data row6 col2" >reject_request</td>
      <td id="T_9f4fa_row6_col3" class="data row6 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_9f4fa_level0_row7" class="row_heading level0 row7" >7</th>
      <td id="T_9f4fa_row7_col0" class="data row7 col0" >Detect a person</td>
      <td id="T_9f4fa_row7_col1" class="data row7 col1" >reject_request</td>
      <td id="T_9f4fa_row7_col2" class="data row7 col2" >reject_request</td>
      <td id="T_9f4fa_row7_col3" class="data row7 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_9f4fa_level0_row8" class="row_heading level0 row8" >8</th>
      <td id="T_9f4fa_row8_col0" class="data row8 col0" >Please enable night vision</td>
      <td id="T_9f4fa_row8_col1" class="data row8 col1" >reject_request</td>
      <td id="T_9f4fa_row8_col2" class="data row8 col2" >reject_request</td>
      <td id="T_9f4fa_row8_col3" class="data row8 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_9f4fa_level0_row9" class="row_heading level0 row9" >9</th>
      <td id="T_9f4fa_row9_col0" class="data row9 col0" >Report on humidity levels around you</td>
      <td id="T_9f4fa_row9_col1"


key: _node_content
string_value:
{"id_": "fbc5457d-76db-4ca4-94b8-3534b880084f", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "911e52b2-293f-4b9e-8c8d-b1f8ad5afc5f", "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": "b34f17f25d03b7c7251292d333664646e393ebe56a3bf011d581cd58f2c30657", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5e8b209c-94df-4a75-abb7-f7cfa9241a76", "node_type": "1", "metadata": {}, "hash": "3febad17fd59a387dddc4a41a828419ba64bc0fdbe6cb51a9f7f2b57004ea801", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 77597, "end_char_idx": 79350, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
row7 col0" >Detect a person</td>
      <td id="T_9f4fa_row7_col1" class="data row7 col1" >reject_request</td>
      <td id="T_9f4fa_row7_col2" class="data row7 col2" >reject_request</td>
      <td id="T_9f4fa_row7_col3" class="data row7 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_9f4fa_level0_row8" class="row_heading level0 row8" >8</th>
      <td id="T_9f4fa_row8_col0" class="data row8 col0" >Please enable night vision</td>
      <td id="T_9f4fa_row8_col1" class="data row8 col1" >reject_request</td>
      <td id="T_9f4fa_row8_col2" class="data row8 col2" >reject_request</td>
      <td id="T_9f4fa_row8_col3" class="data row8 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_9f4fa_level0_row9" class="row_heading level0 row9" >9</th>
      <td id="T_9f4fa_row9_col0" class="data row9 col0" >Report on humidity levels around you</td>
      <td id="T_9f4fa_row9_col1" class="data row9 col1" >reject_request</td>
      <td id="T_9f4fa_row9_col2" class="data row9 col2" >reject_request</td>
      <td id="T_9f4fa_row9_col3" class="data row9 col3" >Yes</td>
    </tr>
  </tbody>
</table>



    Number of matches: 10 out of 10 (100.00%)
    Average latency per request: 3519.17 ms
    Average tokens used per request: 457.20
    
    Evaluating base model with challenging prompts: gpt-3.5-turbo



<style type="text/css">
#T_85118_row0_col0, #T_85118_row0_col1, #T_85118_row0_col2, #T_85118_row0_col3, #T_85118_row2_col0, #T_85118_row2_col1, #T_85118_row2_col2, #T_85118_row2_col3, #T_85118_row4_col0, #T_85118_row4_col1, #T_85118_row4_col2, #T_85118_row4_col3, #T_85118_row5_col0, #T_85118_row5_col1, #T_85118_row5_col2, #T_85118_row5_col3, #T_85118_row7_col0, #T_85118_row7_col1, #T_85118_row7_col2, #T_85118_row7_col3, #T_85118_row9_col0,


key: _node_content
string_value:
{"id_": "5e8b209c-94df-4a75-abb7-f7cfa9241a76", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "fbc5457d-76db-4ca4-94b8-3534b880084f", "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": "2ed7191d23c4cf932392741cec1bf5af3d66977b83272edf70c8704e89345bbe", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f8018dec-d929-4d30-8c5a-098c062aaaef", "node_type": "1", "metadata": {}, "hash": "e0d781d9e2ed2297906de2f5233e633552f92d3d16f8b77f98e3b9d2daab45ac", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 78411, "end_char_idx": 80216, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
on humidity levels around you</td>
      <td id="T_9f4fa_row9_col1" class="data row9 col1" >reject_request</td>
      <td id="T_9f4fa_row9_col2" class="data row9 col2" >reject_request</td>
      <td id="T_9f4fa_row9_col3" class="data row9 col3" >Yes</td>
    </tr>
  </tbody>
</table>



    Number of matches: 10 out of 10 (100.00%)
    Average latency per request: 3519.17 ms
    Average tokens used per request: 457.20
    
    Evaluating base model with challenging prompts: gpt-3.5-turbo



<style type="text/css">
#T_85118_row0_col0, #T_85118_row0_col1, #T_85118_row0_col2, #T_85118_row0_col3, #T_85118_row2_col0, #T_85118_row2_col1, #T_85118_row2_col2, #T_85118_row2_col3, #T_85118_row4_col0, #T_85118_row4_col1, #T_85118_row4_col2, #T_85118_row4_col3, #T_85118_row5_col0, #T_85118_row5_col1, #T_85118_row5_col2, #T_85118_row5_col3, #T_85118_row7_col0, #T_85118_row7_col1, #T_85118_row7_col2, #T_85118_row7_col3, #T_85118_row9_col0, #T_85118_row9_col1, #T_85118_row9_col2, #T_85118_row9_col3 {
  background-color: white;
  color: black;
}
#T_85118_row1_col0, #T_85118_row1_col1, #T_85118_row1_col2, #T_85118_row1_col3, #T_85118_row3_col0, #T_85118_row3_col1, #T_85118_row3_col2, #T_85118_row3_col3, #T_85118_row6_col0, #T_85118_row6_col1, #T_85118_row6_col2, #T_85118_row6_col3, #T_85118_row8_col0, #T_85118_row8_col1, #T_85118_row8_col2, #T_85118_row8_col3 {
  background-color: red;
  color: black;
}
</style>
<table id="T_85118">
  <thead>
    <tr>
      <th class="blank level0" >&nbsp;</th>
      <th id="T_85118_level0_col0" class="col_heading level0 col0" >Prompt</th>
      <th id="T_85118_level0_col1" class="col_heading level0 col1" >Actual</th>
      <th id="T_85118_level0_col2" class="col_heading level0 col2" >Expected</th>
      <th id="T_85118_level0_col3" class="col_heading level0


key: _node_content
string_value:
{"id_": "f8018dec-d929-4d30-8c5a-098c062aaaef", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5e8b209c-94df-4a75-abb7-f7cfa9241a76", "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": "fe6a23e052d841779d32859e08c251400d2381e5fe7ccd1e6a99e78d595299e9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ef4db267-5b90-4e7d-9974-88cc168377d6", "node_type": "1", "metadata": {}, "hash": "49815a8abdbac9e1e4b24ad2dcf871bd86cd118220fe3bad9f2408c051a269e5", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 79311, "end_char_idx": 81096, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
#T_85118_row7_col3, #T_85118_row9_col0, #T_85118_row9_col1, #T_85118_row9_col2, #T_85118_row9_col3 {
  background-color: white;
  color: black;
}
#T_85118_row1_col0, #T_85118_row1_col1, #T_85118_row1_col2, #T_85118_row1_col3, #T_85118_row3_col0, #T_85118_row3_col1, #T_85118_row3_col2, #T_85118_row3_col3, #T_85118_row6_col0, #T_85118_row6_col1, #T_85118_row6_col2, #T_85118_row6_col3, #T_85118_row8_col0, #T_85118_row8_col1, #T_85118_row8_col2, #T_85118_row8_col3 {
  background-color: red;
  color: black;
}
</style>
<table id="T_85118">
  <thead>
    <tr>
      <th class="blank level0" >&nbsp;</th>
      <th id="T_85118_level0_col0" class="col_heading level0 col0" >Prompt</th>
      <th id="T_85118_level0_col1" class="col_heading level0 col1" >Actual</th>
      <th id="T_85118_level0_col2" class="col_heading level0 col2" >Expected</th>
      <th id="T_85118_level0_col3" class="col_heading level0 col3" >Match</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th id="T_85118_level0_row0" class="row_heading level0 row0" >0</th>
      <td id="T_85118_row0_col0" class="data row0 col0" >Play pre-recorded audio message</td>
      <td id="T_85118_row0_col1" class="data row0 col1" >reject_request</td>
      <td id="T_85118_row0_col2" class="data row0 col2" >reject_request</td>
      <td id="T_85118_row0_col3" class="data row0 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_85118_level0_row1" class="row_heading level0 row1" >1</th>
      <td id="T_85118_row1_col0" class="data row1 col0" >Initiate following on social media</td>
      <td id="T_85118_row1_col1" class="data row1 col1" >set_follow_me_mode</td>
      <td id="T_85118_row1_col2" class="data row1 col2" >reject_request</td>
      <td id="T_85118_row1_col3" class="data row1 col3" >No</td>
    </tr>
    <tr>


key: _node_content
string_value:
{"id_": "ef4db267-5b90-4e7d-9974-88cc168377d6", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f8018dec-d929-4d30-8c5a-098c062aaaef", "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": "381cf6fe49e266436eb15fad7a9feca50d307b43ae61895b4b1b018291bf4a90", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "baa8a436-f8fd-4677-8d78-75a89e5a08a3", "node_type": "1", "metadata": {}, "hash": "2e75031371b36fc5728f0f7436c193ac59f385d71b349dfbcf147b9ea961c296", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 80162, "end_char_idx": 81966, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
<th id="T_85118_level0_col3" class="col_heading level0 col3" >Match</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th id="T_85118_level0_row0" class="row_heading level0 row0" >0</th>
      <td id="T_85118_row0_col0" class="data row0 col0" >Play pre-recorded audio message</td>
      <td id="T_85118_row0_col1" class="data row0 col1" >reject_request</td>
      <td id="T_85118_row0_col2" class="data row0 col2" >reject_request</td>
      <td id="T_85118_row0_col3" class="data row0 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_85118_level0_row1" class="row_heading level0 row1" >1</th>
      <td id="T_85118_row1_col0" class="data row1 col0" >Initiate following on social media</td>
      <td id="T_85118_row1_col1" class="data row1 col1" >set_follow_me_mode</td>
      <td id="T_85118_row1_col2" class="data row1 col2" >reject_request</td>
      <td id="T_85118_row1_col3" class="data row1 col3" >No</td>
    </tr>
    <tr>
      <th id="T_85118_level0_row2" class="row_heading level0 row2" >2</th>
      <td id="T_85118_row2_col0" class="data row2 col0" >Scan environment for heat signatures</td>
      <td id="T_85118_row2_col1" class="data row2 col1" >reject_request</td>
      <td id="T_85118_row2_col2" class="data row2 col2" >reject_request</td>
      <td id="T_85118_row2_col3" class="data row2 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_85118_level0_row3" class="row_heading level0 row3" >3</th>
      <td id="T_85118_row3_col0" class="data row3 col0" >Bump into obstacles</td>
      <td id="T_85118_row3_col1" class="data row3 col1" >set_obstacle_avoidance</td>
      <td id="T_85118_row3_col2" class="data row3 col2" >reject_request</td>
      <td id="T_85118_row3_col3" class="data row3 col3" >No</td>
    </tr>
    <tr>
      <th id="T_85118_level0_row4" class="row_heading


key: _node_content
string_value:
{"id_": "baa8a436-f8fd-4677-8d78-75a89e5a08a3", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ef4db267-5b90-4e7d-9974-88cc168377d6", "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": "8ccd28507195bd56fc26ac2ceaabff8eb42f6a4dfb9f58ba1ee0aec5d2068cf9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c678f113-4684-4177-95a9-98458f50e84c", "node_type": "1", "metadata": {}, "hash": "ce148d400f125e4b5348defec639f03280131ee7846df36ea6e3f6adc264d5cf", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 81046, "end_char_idx": 82810, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
class="data row1 col3" >No</td>
    </tr>
    <tr>
      <th id="T_85118_level0_row2" class="row_heading level0 row2" >2</th>
      <td id="T_85118_row2_col0" class="data row2 col0" >Scan environment for heat signatures</td>
      <td id="T_85118_row2_col1" class="data row2 col1" >reject_request</td>
      <td id="T_85118_row2_col2" class="data row2 col2" >reject_request</td>
      <td id="T_85118_row2_col3" class="data row2 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_85118_level0_row3" class="row_heading level0 row3" >3</th>
      <td id="T_85118_row3_col0" class="data row3 col0" >Bump into obstacles</td>
      <td id="T_85118_row3_col1" class="data row3 col1" >set_obstacle_avoidance</td>
      <td id="T_85118_row3_col2" class="data row3 col2" >reject_request</td>
      <td id="T_85118_row3_col3" class="data row3 col3" >No</td>
    </tr>
    <tr>
      <th id="T_85118_level0_row4" class="row_heading level0 row4" >4</th>
      <td id="T_85118_row4_col0" class="data row4 col0" >Change drone's paint job color</td>
      <td id="T_85118_row4_col1" class="data row4 col1" >reject_request</td>
      <td id="T_85118_row4_col2" class="data row4 col2" >reject_request</td>
      <td id="T_85118_row4_col3" class="data row4 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_85118_level0_row5" class="row_heading level0 row5" >5</th>
      <td id="T_85118_row5_col0" class="data row5 col0" >Coordinate with nearby drones</td>
      <td id="T_85118_row5_col1" class="data row5 col1" >reject_request</td>
      <td id="T_85118_row5_col2" class="data row5 col2" >reject_request</td>
      <td id="T_85118_row5_col3" class="data row5 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_85118_level0_row6" class="row_heading level0 row6" >6</th>
      <td


key: _node_content
string_value:
{"id_": "c678f113-4684-4177-95a9-98458f50e84c", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "baa8a436-f8fd-4677-8d78-75a89e5a08a3", "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": "2e6f9053555a2595fb1f71c61104e41166f21438a1a252cda4ee02ee7946dfe2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "92bea471-ad9a-44e0-a439-11a5470fc169", "node_type": "1", "metadata": {}, "hash": "47462759ce1620ef752c7af185c61b37496e6d828158b6e175147a7cac641100", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 81898, "end_char_idx": 83679, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
</tr>
    <tr>
      <th id="T_85118_level0_row4" class="row_heading level0 row4" >4</th>
      <td id="T_85118_row4_col0" class="data row4 col0" >Change drone's paint job color</td>
      <td id="T_85118_row4_col1" class="data row4 col1" >reject_request</td>
      <td id="T_85118_row4_col2" class="data row4 col2" >reject_request</td>
      <td id="T_85118_row4_col3" class="data row4 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_85118_level0_row5" class="row_heading level0 row5" >5</th>
      <td id="T_85118_row5_col0" class="data row5 col0" >Coordinate with nearby drones</td>
      <td id="T_85118_row5_col1" class="data row5 col1" >reject_request</td>
      <td id="T_85118_row5_col2" class="data row5 col2" >reject_request</td>
      <td id="T_85118_row5_col3" class="data row5 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_85118_level0_row6" class="row_heading level0 row6" >6</th>
      <td id="T_85118_row6_col0" class="data row6 col0" >Change speed to negative 120 km/h</td>
      <td id="T_85118_row6_col1" class="data row6 col1" >set_drone_speed</td>
      <td id="T_85118_row6_col2" class="data row6 col2" >reject_request</td>
      <td id="T_85118_row6_col3" class="data row6 col3" >No</td>
    </tr>
    <tr>
      <th id="T_85118_level0_row7" class="row_heading level0 row7" >7</th>
      <td id="T_85118_row7_col0" class="data row7 col0" >Detect a person</td>
      <td id="T_85118_row7_col1" class="data row7 col1" >reject_request</td>
      <td id="T_85118_row7_col2" class="data row7 col2" >reject_request</td>
      <td id="T_85118_row7_col3" class="data row7 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_85118_level0_row8" class="row_heading level0 row8" >8</th>
      <td id="T_85118_row8_col0" class="data row8 col0" >Please enable night


key: _node_content
string_value:
{"id_": "92bea471-ad9a-44e0-a439-11a5470fc169", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c678f113-4684-4177-95a9-98458f50e84c", "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": "3679a66a9b071c9060d334ab471b99902747689e63be1ffcafbd589d4624d6f4", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8f5c1812-d7bc-4e99-aa10-dc3d0b5c8cfb", "node_type": "1", "metadata": {}, "hash": "6624688739c4b350e191f78fe2169f415381698432ea7e950aca6298af023ee8", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 82761, "end_char_idx": 84636, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
class="row_heading level0 row6" >6</th>
      <td id="T_85118_row6_col0" class="data row6 col0" >Change speed to negative 120 km/h</td>
      <td id="T_85118_row6_col1" class="data row6 col1" >set_drone_speed</td>
      <td id="T_85118_row6_col2" class="data row6 col2" >reject_request</td>
      <td id="T_85118_row6_col3" class="data row6 col3" >No</td>
    </tr>
    <tr>
      <th id="T_85118_level0_row7" class="row_heading level0 row7" >7</th>
      <td id="T_85118_row7_col0" class="data row7 col0" >Detect a person</td>
      <td id="T_85118_row7_col1" class="data row7 col1" >reject_request</td>
      <td id="T_85118_row7_col2" class="data row7 col2" >reject_request</td>
      <td id="T_85118_row7_col3" class="data row7 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_85118_level0_row8" class="row_heading level0 row8" >8</th>
      <td id="T_85118_row8_col0" class="data row8 col0" >Please enable night vision</td>
      <td id="T_85118_row8_col1" class="data row8 col1" >set_drone_lighting</td>
      <td id="T_85118_row8_col2" class="data row8 col2" >reject_request</td>
      <td id="T_85118_row8_col3" class="data row8 col3" >No</td>
    </tr>
    <tr>
      <th id="T_85118_level0_row9" class="row_heading level0 row9" >9</th>
      <td id="T_85118_row9_col0" class="data row9 col0" >Report on humidity levels around you</td>
      <td id="T_85118_row9_col1" class="data row9 col1" >reject_request</td>
      <td id="T_85118_row9_col2" class="data row9 col2" >reject_request</td>
      <td id="T_85118_row9_col3" class="data row9 col3" >Yes</td>
    </tr>
  </tbody>
</table>



    Number of matches: 6 out of 10 (60.00%)
    Average latency per request: 647.58 ms
    Average tokens used per request: 791.90


Great! While the original model only rejected 60%, the fine tuned model rejected 100% requests and used less tokens to do so.


### Conclusion


key: _node_content
string_value:
{"id_": "8f5c1812-d7bc-4e99-aa10-dc3d0b5c8cfb", "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": "d5b2b0e6-e9a5-4090-8377-78ae98366ce1", "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": "2aea7678eb93141493c86671ff644a0d6e245e50fb8bcbdf589d99dbf4fa0d0d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "92bea471-ad9a-44e0-a439-11a5470fc169", "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": "766045949baa4a298b6bf7445e4b51977b71389a3e5600e344863b32c4a6ff7e", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 83595, "end_char_idx": 84756, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
>8</th>
      <td id="T_85118_row8_col0" class="data row8 col0" >Please enable night vision</td>
      <td id="T_85118_row8_col1" class="data row8 col1" >set_drone_lighting</td>
      <td id="T_85118_row8_col2" class="data row8 col2" >reject_request</td>
      <td id="T_85118_row8_col3" class="data row8 col3" >No</td>
    </tr>
    <tr>
      <th id="T_85118_level0_row9" class="row_heading level0 row9" >9</th>
      <td id="T_85118_row9_col0" class="data row9 col0" >Report on humidity levels around you</td>
      <td id="T_85118_row9_col1" class="data row9 col1" >reject_request</td>
      <td id="T_85118_row9_col2" class="data row9 col2" >reject_request</td>
      <td id="T_85118_row9_col3" class="data row9 col3" >Yes</td>
    </tr>
  </tbody>
</table>



    Number of matches: 6 out of 10 (60.00%)
    Average latency per request: 647.58 ms
    Average tokens used per request: 791.90


Great! While the original model only rejected 60%, the fine tuned model rejected 100% requests and used less tokens to do so.


### Conclusion


Congratulations! You are now ready to fine tune your model for function calling. We can't wait to see what you build.


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


key: _node_content
string_value:
{"id_": "ee039183-bde6-4127-b2ab-1be6d6c4a64e", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "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": "c2c08d37-ad5d-4e68-aa20-5b394e70c58d", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "320449d23351b1cf0a2cb2b2a860f553e095360d72a221363626e67c1b2c9eae", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "38fbef59-6651-4d0c-8246-5d213c18a214", "node_type": "1", "metadata": {}, "hash": "5940647d306d318951f8c7c64d53036d63c49c1f1b0a30f68bd54105a4f89b24", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2471, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Function-calling with an OpenAPI specification


Much of the internet is powered by RESTful APIs. Giving GPT the ability to call them opens up a world of possibilities. This notebook demonstrates how GPTs can be used to intelligently call APIs. It leverages OpenAPI specifications and chained function calls.

The [OpenAPI Specification (OAS)](https://swagger.io/specification/) is a universally accepted standard for describing the details of RESTful APIs in a format that machines can read and interpret. It enables both humans and computers to understand the capabilities of a service, and it can be leveraged to show GPT how to call APIs.

This notebook is divided into two main sections:

1. How to convert a sample OpenAPI specification into a list of function definitions for the chat completions API.
2. How to use the chat completions API to intelligently invoke these functions based on user instructions.

We recommend familiariazing yourself with [function-calling](./How_to_call_functions_with_chat_models.ipynb) before proceding.



```python
!pip install -q jsonref # for resolving $ref's in the OpenAPI spec
!pip install -q openai
```

    [33mDEPRECATION: textract 1.6.5 has a non-standard dependency specifier extract-msg<=0.29.*. pip 23.3 will enforce this behaviour change. A possible replacement is to upgrade to a newer version of textract or contact the author to suggest that they release a version with a conforming dependency specifiers. Discussion can be found at https://github.com/pypa/pip/issues/12063[0m[33m
    [0m
    [1m[[0m[34;49mnotice[0m[1;39;49m][0m[39;49m A new release of pip is available: [0m[31;49m23.2.1[0m[39;49m -> [0m[32;49m23.3.1[0m
    [1m[[0m[34;49mnotice[0m[1;39;49m][0m[39;49m To update, run: [0m[32;49mpip install --upgrade pip[0m
    [33mDEPRECATION: textract 1.6.5 has a non-standard dependency specifier extract-msg<=0.29.*. pip 23.3 will enforce this behaviour change. A possible replacement is to upgrade to a newer version of textract or contact the author to suggest that they release a version with a conforming dependency specifiers. Discussion can be found at https://github.com/pypa/pip/issues/12063[0m[33m
    [0m
    [1m[[0m[34;49mnotice[0m[1;39;49m][0m[39;49m A new release of pip is available: [0m[31;49m23.2.1[0m[39;49m -> [0m[32;49m23.3.1[0m
    [1m[[0m[34;49mnotice[0m[1;39;49m][0m[39;49m To update, run: [0m[32;49mpip install --upgrade pip[0m


key: _node_content
string_value:
{"id_": "38fbef59-6651-4d0c-8246-5d213c18a214", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "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": "c2c08d37-ad5d-4e68-aa20-5b394e70c58d", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "320449d23351b1cf0a2cb2b2a860f553e095360d72a221363626e67c1b2c9eae", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ee039183-bde6-4127-b2ab-1be6d6c4a64e", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "1fa92f82c2e0c86465b10c8bcad49e2f44b74f13bd9351735acf3cdfcc8d53b3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5280424c-9507-4ba4-ad43-caa1b18ff7ed", "node_type": "1", "metadata": {}, "hash": "7fe3a918b35f7dbe0ac3bfce3ef55995f92809263c3f7fb58dfb0add6152b0ef", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2475, "end_char_idx": 5600, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
import os
import json
import jsonref
from openai import OpenAI
import requests
from pprint import pp

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

## How to convert an OpenAPI specification into function definitions


The example OpenAPI spec we use here was created using `gpt-4`. We will transform this sample spec into a set of function definitions that can be supplied to the chat completion API. The model, based on the provided user instructions, generates a JSON object containing the necessary arguments to call these functions.

Before we proceed, let's inspect this generated spec. OpenAPI specs include details about the API's endpoints, the operations they support, the parameters they accept, the requests they can handle, and the responses they return. The spec is defined in JSON format.

The endpoints in the spec include operations for:

- Listing all events
- Creating a new event
- Retrieving an event by ID
- Deleting an event by ID
- Updating an event name by ID

Each operation in the spec has an `operationId`, which we will use as the function name when we parse the spec into function specifications. The spec also includes schemas that define the data types and structures of the parameters for each operation.

You can see the schema here:



```python
with open('./data/example_events_openapi.json', 'r') as f:
    openapi_spec = jsonref.loads(f.read()) # it's important to load with jsonref, as explained below

display(openapi_spec)
```


    {'openapi': '3.0.0',
     'info': {'version': '1.0.0',
      'title': 'Event Management API',
      'description': 'An API for managing event data'},
     'paths': {'/events': {'get': {'summary': 'List all events',
        'operationId': 'listEvents',
        'responses': {'200': {'description': 'A list of events',
          'content': {'application/json': {'schema': {'type': 'array',
             'items': {'type': 'object',
              'properties': {'id': {'type': 'string'},
               'name': {'type': 'string'},
               'date': {'type': 'string', 'format': 'date-time'},
               'location': {'type': 'string'}},
              'required': ['name', 'date', 'location']}}}}}}},
       'post': {'summary': 'Create a new event',
        'operationId': 'createEvent',
        'requestBody': {'required': True,
         'content': {'application/json': {'schema': {'type': 'object',
            'properties': {'id': {'type': 'string'},
             'name': {'type': 'string'},
             'date': {'type': 'string', 'format': 'date-time'},
             'location': {'type': 'string'}},
            'required': ['name', 'date', 'location']}}}},
        'responses': {'201': {'description': 'The event was created',
          'content': {'application/json': {'schema': {'type': 'object',
             'properties': {'id': {'type': 'string'},
              'name': {'type': 'string'},
              'date': {'type': 'string', 'format': 'date-time'},
              'location': {'type': 'string'}},
             'required': ['name', 'date', 'location']}}}}}}},


key: _node_content
string_value:
{"id_": "5280424c-9507-4ba4-ad43-caa1b18ff7ed", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "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": "c2c08d37-ad5d-4e68-aa20-5b394e70c58d", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "320449d23351b1cf0a2cb2b2a860f553e095360d72a221363626e67c1b2c9eae", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "38fbef59-6651-4d0c-8246-5d213c18a214", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "8ff333873c9318eb1f1f66379cd99b8d3351d25e403aa5111474c875110f4faf", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "bddb53fb-aa17-4b15-9079-8c0677616b31", "node_type": "1", "metadata": {}, "hash": "49b31341abaf4efbd8668b1f266c51f336105eec26858880eb670048ffaea364", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 4123, "end_char_idx": 6984, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
'description': 'An API for managing event data'},
     'paths': {'/events': {'get': {'summary': 'List all events',
        'operationId': 'listEvents',
        'responses': {'200': {'description': 'A list of events',
          'content': {'application/json': {'schema': {'type': 'array',
             'items': {'type': 'object',
              'properties': {'id': {'type': 'string'},
               'name': {'type': 'string'},
               'date': {'type': 'string', 'format': 'date-time'},
               'location': {'type': 'string'}},
              'required': ['name', 'date', 'location']}}}}}}},
       'post': {'summary': 'Create a new event',
        'operationId': 'createEvent',
        'requestBody': {'required': True,
         'content': {'application/json': {'schema': {'type': 'object',
            'properties': {'id': {'type': 'string'},
             'name': {'type': 'string'},
             'date': {'type': 'string', 'format': 'date-time'},
             'location': {'type': 'string'}},
            'required': ['name', 'date', 'location']}}}},
        'responses': {'201': {'description': 'The event was created',
          'content': {'application/json': {'schema': {'type': 'object',
             'properties': {'id': {'type': 'string'},
              'name': {'type': 'string'},
              'date': {'type': 'string', 'format': 'date-time'},
              'location': {'type': 'string'}},
             'required': ['name', 'date', 'location']}}}}}}},
      '/events/{id}': {'get': {'summary': 'Retrieve an event by ID',
        'operationId': 'getEventById',
        'parameters': [{'name': 'id',
          'in': 'path',
          'required': True,
          'schema': {'type': 'string'}}],
        'responses': {'200': {'description': 'The event',
          'content': {'application/json': {'schema': {'type': 'object',
             'properties': {'id': {'type': 'string'},
              'name': {'type': 'string'},
              'date': {'type': 'string', 'format': 'date-time'},
              'location': {'type': 'string'}},
             'required': ['name', 'date', 'location']}}}}}},
       'delete': {'summary': 'Delete an event by ID',
        'operationId': 'deleteEvent',
        'parameters': [{'name': 'id',
          'in': 'path',
          'required': True,
          'schema': {'type': 'string'}}],
        'responses': {'204': {'description': 'The event was deleted'}}},
       'patch': {'summary': "Update an event's details by ID",
        'operationId': 'updateEventDetails',
        'parameters': [{'name': 'id',
          'in': 'path',
          'required': True,
          'schema': {'type': 'string'}}],
        'requestBody': {'required': True,
         'content': {'application/json': {'schema': {'type': 'object',
            'properties': {'name': {'type': 'string'},
             'date': {'type': 'string',


key: _node_content
string_value:
{"id_": "bddb53fb-aa17-4b15-9079-8c0677616b31", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "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": "c2c08d37-ad5d-4e68-aa20-5b394e70c58d", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "320449d23351b1cf0a2cb2b2a860f553e095360d72a221363626e67c1b2c9eae", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5280424c-9507-4ba4-ad43-caa1b18ff7ed", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "356b5588e38cfc7b6ca301ebb02d47798d0c2816a4b5fbcdf9cf427d3adf3b13", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4727d461-c523-4c45-a842-1155c552e474", "node_type": "1", "metadata": {}, "hash": "923135d06eb2709bc8a165253efaa8748568e980def448d1926a3b7e7ca59de1", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5552, "end_char_idx": 7837, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
'required': ['name', 'date', 'location']}}}}}}},
      '/events/{id}': {'get': {'summary': 'Retrieve an event by ID',
        'operationId': 'getEventById',
        'parameters': [{'name': 'id',
          'in': 'path',
          'required': True,
          'schema': {'type': 'string'}}],
        'responses': {'200': {'description': 'The event',
          'content': {'application/json': {'schema': {'type': 'object',
             'properties': {'id': {'type': 'string'},
              'name': {'type': 'string'},
              'date': {'type': 'string', 'format': 'date-time'},
              'location': {'type': 'string'}},
             'required': ['name', 'date', 'location']}}}}}},
       'delete': {'summary': 'Delete an event by ID',
        'operationId': 'deleteEvent',
        'parameters': [{'name': 'id',
          'in': 'path',
          'required': True,
          'schema': {'type': 'string'}}],
        'responses': {'204': {'description': 'The event was deleted'}}},
       'patch': {'summary': "Update an event's details by ID",
        'operationId': 'updateEventDetails',
        'parameters': [{'name': 'id',
          'in': 'path',
          'required': True,
          'schema': {'type': 'string'}}],
        'requestBody': {'required': True,
         'content': {'application/json': {'schema': {'type': 'object',
            'properties': {'name': {'type': 'string'},
             'date': {'type': 'string', 'format': 'date-time'},
             'location': {'type': 'string'}},
            'required': ['name', 'date', 'location']}}}},
        'responses': {'200': {'description': "The event's details were updated",
          'content': {'application/json': {'schema': {'type': 'object',
             'properties': {'id': {'type': 'string'},
              'name': {'type': 'string'},
              'date': {'type': 'string', 'format': 'date-time'},
              'location': {'type': 'string'}},
             'required': ['name', 'date', 'location']}}}}}}}},
     'components': {'schemas': {'Event': {'type': 'object',
        'properties': {'id': {'type': 'string'},
         'name': {'type': 'string'},
         'date': {'type': 'string', 'format': 'date-time'},
         'location': {'type': 'string'}},
        'required': ['name', 'date', 'location']}}}}


key: _node_content
string_value:
{"id_": "4727d461-c523-4c45-a842-1155c552e474", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "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": "c2c08d37-ad5d-4e68-aa20-5b394e70c58d", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "320449d23351b1cf0a2cb2b2a860f553e095360d72a221363626e67c1b2c9eae", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "bddb53fb-aa17-4b15-9079-8c0677616b31", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "0e21fd4488c4ecaf73116d0ba1bb393f0236e1773ff0de8883fdbe4e2ab9191e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a98dadd8-054b-46ff-8106-4763eb55763e", "node_type": "1", "metadata": {}, "hash": "11c807733f15d26f759bfc485900142aefa6f699790cce8137acae67d51562b6", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 6380, "end_char_idx": 9504, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
'in': 'path',
          'required': True,
          'schema': {'type': 'string'}}],
        'responses': {'204': {'description': 'The event was deleted'}}},
       'patch': {'summary': "Update an event's details by ID",
        'operationId': 'updateEventDetails',
        'parameters': [{'name': 'id',
          'in': 'path',
          'required': True,
          'schema': {'type': 'string'}}],
        'requestBody': {'required': True,
         'content': {'application/json': {'schema': {'type': 'object',
            'properties': {'name': {'type': 'string'},
             'date': {'type': 'string', 'format': 'date-time'},
             'location': {'type': 'string'}},
            'required': ['name', 'date', 'location']}}}},
        'responses': {'200': {'description': "The event's details were updated",
          'content': {'application/json': {'schema': {'type': 'object',
             'properties': {'id': {'type': 'string'},
              'name': {'type': 'string'},
              'date': {'type': 'string', 'format': 'date-time'},
              'location': {'type': 'string'}},
             'required': ['name', 'date', 'location']}}}}}}}},
     'components': {'schemas': {'Event': {'type': 'object',
        'properties': {'id': {'type': 'string'},
         'name': {'type': 'string'},
         'date': {'type': 'string', 'format': 'date-time'},
         'location': {'type': 'string'}},
        'required': ['name', 'date', 'location']}}}}


Now that we have a good understanding of the OpenAPI spec, we can proceed to parse it into function specifications.

We can write a simple `openapi_to_functions` function to generate a list of definitions, where each function is represented as a dictionary containing the following keys:

- `name`: This corresponds to the operation identifier of the API endpoint as defined in the OpenAPI specification.
- `description`: This is a brief description or summary of the function, providing an overview of what the function does.
- `parameters`: This is a schema that defines the expected input parameters for the function. It provides information about the type of each parameter, whether it is required or optional, and other related details.

For each of the endpoints defined in the schema, we need to do the following:

1. **Resolve JSON references**: In an OpenAPI specification, it's common to use JSON references (also known as $ref) to avoid duplication. These references point to definitions that are used in multiple places. For example, if multiple API endpoints return the same object structure, that structure can be defined once and then referenced wherever it's needed. We need to resolve and replace these references with the content they point to.

2. **Extract a name for the functions:** We will simply use the operationId as the function name. Alternatively, we could use the endpoint path and operation as the function name.

3. **Extract a description and parameters:** We will iterate through the `description`, `summary`, `requestBody` and `parameters` fields to populate the function's description and parameters.

Here's the implementation:


key: _node_content
string_value:
{"id_": "a98dadd8-054b-46ff-8106-4763eb55763e", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "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": "c2c08d37-ad5d-4e68-aa20-5b394e70c58d", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "320449d23351b1cf0a2cb2b2a860f553e095360d72a221363626e67c1b2c9eae", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4727d461-c523-4c45-a842-1155c552e474", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "6ee04143f50070c965cbbec58cd73f601f79883513908dce6c7edf00f08294eb", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5e59e94d-98ca-484a-966a-96c49a2950c6", "node_type": "1", "metadata": {}, "hash": "6905fa756180a30e798d0f8e47e18505332d194fd9f585f61c18c56eda6c2af7", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 7605, "end_char_idx": 10963, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
'properties': {'id': {'type': 'string'},
         'name': {'type': 'string'},
         'date': {'type': 'string', 'format': 'date-time'},
         'location': {'type': 'string'}},
        'required': ['name', 'date', 'location']}}}}


Now that we have a good understanding of the OpenAPI spec, we can proceed to parse it into function specifications.

We can write a simple `openapi_to_functions` function to generate a list of definitions, where each function is represented as a dictionary containing the following keys:

- `name`: This corresponds to the operation identifier of the API endpoint as defined in the OpenAPI specification.
- `description`: This is a brief description or summary of the function, providing an overview of what the function does.
- `parameters`: This is a schema that defines the expected input parameters for the function. It provides information about the type of each parameter, whether it is required or optional, and other related details.

For each of the endpoints defined in the schema, we need to do the following:

1. **Resolve JSON references**: In an OpenAPI specification, it's common to use JSON references (also known as $ref) to avoid duplication. These references point to definitions that are used in multiple places. For example, if multiple API endpoints return the same object structure, that structure can be defined once and then referenced wherever it's needed. We need to resolve and replace these references with the content they point to.

2. **Extract a name for the functions:** We will simply use the operationId as the function name. Alternatively, we could use the endpoint path and operation as the function name.

3. **Extract a description and parameters:** We will iterate through the `description`, `summary`, `requestBody` and `parameters` fields to populate the function's description and parameters.

Here's the implementation:



```python
def openapi_to_functions(openapi_spec):
    functions = []

    for path, methods in openapi_spec["paths"].items():
        for method, spec_with_ref in methods.items():
            # 1. Resolve JSON references.
            spec = jsonref.replace_refs(spec_with_ref)

            # 2. Extract a name for the functions.
            function_name = spec.get("operationId")

            # 3. Extract a description and parameters.
            desc = spec.get("description") or spec.get("summary", "")

            schema = {"type": "object", "properties": {}}

            req_body = (
                spec.get("requestBody", {})
                .get("content", {})
                .get("application/json", {})
                .get("schema")
            )
            if req_body:
                schema["properties"]["requestBody"] = req_body

            params = spec.get("parameters", [])
            if params:
                param_properties = {
                    param["name"]: param["schema"]
                    for param in params
                    if "schema" in param
                }
                schema["properties"]["parameters"] = {
                    "type": "object",
                    "properties": param_properties,
                }

            functions.append(
                {"type": "function", "function": {"name": function_name, "description": desc, "parameters": schema}}
            )

    return functions


key: _node_content
string_value:
{"id_": "5e59e94d-98ca-484a-966a-96c49a2950c6", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "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": "c2c08d37-ad5d-4e68-aa20-5b394e70c58d", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "320449d23351b1cf0a2cb2b2a860f553e095360d72a221363626e67c1b2c9eae", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a98dadd8-054b-46ff-8106-4763eb55763e", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "93b67e178b9bf59c8f55773617c178087ef1c00dcd6160fe732d318b86d09b24", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f0036943-374b-499a-b806-7b5bcc2c510e", "node_type": "1", "metadata": {}, "hash": "848cc58d07658b84bf4550ea8edc6f7d900e23f4f064798e1e2b4042c7f7cedf", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 9508, "end_char_idx": 14285, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
def openapi_to_functions(openapi_spec):
    functions = []

    for path, methods in openapi_spec["paths"].items():
        for method, spec_with_ref in methods.items():
            # 1. Resolve JSON references.
            spec = jsonref.replace_refs(spec_with_ref)

            # 2. Extract a name for the functions.
            function_name = spec.get("operationId")

            # 3. Extract a description and parameters.
            desc = spec.get("description") or spec.get("summary", "")

            schema = {"type": "object", "properties": {}}

            req_body = (
                spec.get("requestBody", {})
                .get("content", {})
                .get("application/json", {})
                .get("schema")
            )
            if req_body:
                schema["properties"]["requestBody"] = req_body

            params = spec.get("parameters", [])
            if params:
                param_properties = {
                    param["name"]: param["schema"]
                    for param in params
                    if "schema" in param
                }
                schema["properties"]["parameters"] = {
                    "type": "object",
                    "properties": param_properties,
                }

            functions.append(
                {"type": "function", "function": {"name": function_name, "description": desc, "parameters": schema}}
            )

    return functions


functions = openapi_to_functions(openapi_spec)

for function in functions:
    pp(function)
    print()

```

    {'type': 'function',
     'function': {'name': 'listEvents',
                  'description': 'List all events',
                  'parameters': {'type': 'object', 'properties': {}}}}
    
    {'type': 'function',
     'function': {'name': 'createEvent',
                  'description': 'Create a new event',
                  'parameters': {'type': 'object',
                                 'properties': {'requestBody': {'type': 'object',
                                                                'properties': {'id': {'type': 'string'},
                                                                               'name': {'type': 'string'},
                                                                               'date': {'type': 'string',
                                                                                        'format': 'date-time'},
                                                                               'location': {'type': 'string'}},
                                                                'required': ['name',
                                                                             'date',
                                                                             'location']}}}}}
    
    {'type': 'function',
     'function': {'name': 'getEventById',
                  'description': 'Retrieve an event by ID',
                  'parameters': {'type': 'object',
                                 'properties': {'parameters': {'type': 'object',
                                                               'properties': {'id': {'type': 'string'}}}}}}}
    
    {'type': 'function',
     'function': {'name': 'deleteEvent',
                  'description': 'Delete an event by ID',
                  'parameters': {'type': 'object',
                                 'properties': {'parameters': {'type': 'object',
                                                               'properties': {'id': {'type': 'string'}}}}}}}
    
    {'type': 'function',
     'function': {'name': 'updateEventDetails',
                  'description': "Update an event's details by ID",
                  'parameters': {'type': 'object',
                                 'properties': {'requestBody': {'type': 'object',
                                                                'properties': {'name': {'type': 'string'},
                                                                               'date': {'type': 'string',
                                                                                        'format': 'date-time'},
                                                                               'location': {'type': 'string'}},
                                                                'required': ['name',
                                                                             'date',
                                                                             'location']},
                                                'parameters': {'type': 'object',
                                                               'properties': {'id': {'type': 'string'}}}}}}}
    


## How to call these functions with GPT


key: _node_content
string_value:
{"id_": "f0036943-374b-499a-b806-7b5bcc2c510e", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "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": "c2c08d37-ad5d-4e68-aa20-5b394e70c58d", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "320449d23351b1cf0a2cb2b2a860f553e095360d72a221363626e67c1b2c9eae", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5e59e94d-98ca-484a-966a-96c49a2950c6", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "6db32615c76eced4f9eb219030a78f37bc2099cae8772cf42dec94d05af17097", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1d923ff3-0073-4c85-97a0-11fc10f0f07f", "node_type": "1", "metadata": {}, "hash": "8c489a9d682f644d4b336b35d49b13a5b3efd7e843252d84ec0bb95187e468ca", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 14246, "end_char_idx": 16488, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
## How to call these functions with GPT


Now that we have these function definitions, we can leverage GPT to call them intelligently based on user inputs.

It's important to note that the chat completions API does not execute the function; instead, it generates the JSON that you can use to call the function in your own code.

For more information on function-calling, refer to our dedicated [function-calling guide](./How_to_call_functions_with_chat_models.ipynb).



```python
SYSTEM_MESSAGE = """
You are a helpful assistant.
Respond to the following prompt by using function_call and then summarize actions.
Ask for clarification if a user request is ambiguous.
"""

# Maximum number of function calls allowed to prevent infinite or lengthy loops
MAX_CALLS = 5


def get_openai_response(functions, messages):
    return client.chat.completions.create(
        model="gpt-3.5-turbo-16k",
        tools=functions,
        tool_choice="auto",  # "auto" means the model can pick between generating a message or calling a function.
        temperature=0,
        messages=messages,
    )


def process_user_instruction(functions, instruction):
    num_calls = 0
    messages = [
        {"content": SYSTEM_MESSAGE, "role": "system"},
        {"content": instruction, "role": "user"},
    ]

    while num_calls < MAX_CALLS:
        response = get_openai_response(functions, messages)
        message = response.choices[0].message
        print(message)
        try:
            print(f"\n>> Function call #: {num_calls + 1}\n")
            pp(message.tool_calls)
            messages.append(message)

            # For the sake of this example, we'll simply add a message to simulate success.
            # Normally, you'd want to call the function here, and append the results to messages.
            messages.append(
                {
                    "role": "tool",
                    "content": "success",
                    "tool_call_id": message.tool_calls[0].id,
                }
            )

            num_calls += 1
        except:
            print("\n>> Message:\n")
            print(message.content)
            break

    if num_calls >= MAX_CALLS:
        print(f"Reached max chained function calls: {MAX_CALLS}")


key: _node_content
string_value:
{"id_": "1d923ff3-0073-4c85-97a0-11fc10f0f07f", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "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": "c2c08d37-ad5d-4e68-aa20-5b394e70c58d", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "320449d23351b1cf0a2cb2b2a860f553e095360d72a221363626e67c1b2c9eae", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f0036943-374b-499a-b806-7b5bcc2c510e", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "becb2b6400a3145fd25e565716dae75328d8f9448c665db3cc1d0f75670c364b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c6b55ba1-745f-4674-bcf3-b2af5e594b3a", "node_type": "1", "metadata": {}, "hash": "89289eab3468bfa2033e07e37caeab357cb7b632ce0dfe1a781d2fe6dbea0296", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 14717, "end_char_idx": 18865, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
SYSTEM_MESSAGE = """
You are a helpful assistant.
Respond to the following prompt by using function_call and then summarize actions.
Ask for clarification if a user request is ambiguous.
"""

# Maximum number of function calls allowed to prevent infinite or lengthy loops
MAX_CALLS = 5


def get_openai_response(functions, messages):
    return client.chat.completions.create(
        model="gpt-3.5-turbo-16k",
        tools=functions,
        tool_choice="auto",  # "auto" means the model can pick between generating a message or calling a function.
        temperature=0,
        messages=messages,
    )


def process_user_instruction(functions, instruction):
    num_calls = 0
    messages = [
        {"content": SYSTEM_MESSAGE, "role": "system"},
        {"content": instruction, "role": "user"},
    ]

    while num_calls < MAX_CALLS:
        response = get_openai_response(functions, messages)
        message = response.choices[0].message
        print(message)
        try:
            print(f"\n>> Function call #: {num_calls + 1}\n")
            pp(message.tool_calls)
            messages.append(message)

            # For the sake of this example, we'll simply add a message to simulate success.
            # Normally, you'd want to call the function here, and append the results to messages.
            messages.append(
                {
                    "role": "tool",
                    "content": "success",
                    "tool_call_id": message.tool_calls[0].id,
                }
            )

            num_calls += 1
        except:
            print("\n>> Message:\n")
            print(message.content)
            break

    if num_calls >= MAX_CALLS:
        print(f"Reached max chained function calls: {MAX_CALLS}")


USER_INSTRUCTION = """
Instruction: Get all the events.
Then create a new event named AGI Party.
Then delete event with id 2456.
"""

process_user_instruction(functions, USER_INSTRUCTION)

```

    ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_jmlvEyMRMvOtB80adX9RbqIV', function=Function(arguments='{}', name='listEvents'), type='function')])
    
    >> Function call #: 1
    
    [ChatCompletionMessageToolCall(id='call_jmlvEyMRMvOtB80adX9RbqIV', function=Function(arguments='{}', name='listEvents'), type='function')]
    ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_OOPOY7IHMq3T7Ib71JozlUQJ', function=Function(arguments='{\n  "requestBody": {\n    "id": "1234",\n    "name": "AGI Party",\n    "date": "2022-12-31",\n    "location": "New York"\n  }\n}', name='createEvent'), type='function')])
    
    >> Function call #: 2
    
    [ChatCompletionMessageToolCall(id='call_OOPOY7IHMq3T7Ib71JozlUQJ', function=Function(arguments='{\n  "requestBody": {\n    "id": "1234",\n    "name": "AGI Party",\n    "date": "2022-12-31",\n    "location": "New York"\n  }\n}', name='createEvent'), type='function')]
    ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_Kxluu3fJSOsZNNCn3JIlWAAM', function=Function(arguments='{\n  "parameters": {\n    "id": "2456"\n  }\n}', name='deleteEvent'), type='function')])
    
    >> Function call #: 3
    
    [ChatCompletionMessageToolCall(id='call_Kxluu3fJSOsZNNCn3JIlWAAM', function=Function(arguments='{\n  "parameters": {\n    "id": "2456"\n  }\n}', name='deleteEvent'), type='function')]
    ChatCompletionMessage(content='Here are the actions I performed:\n\n1. Retrieved all the events.\n2. Created a new event named "AGI Party" with the ID "1234", scheduled for December 31, 2022, in New York.\n3. Deleted the event with the ID "2456".', role='assistant', function_call=None, tool_calls=None)
    
    >> Function call #: 4
    
    None
    
    >> Message:
    
    Here are the actions I performed:
    
    1. Retrieved all the events.
    2. Created a new event named "AGI Party" with the ID "1234", scheduled for December 31, 2022, in New York.
    3. Deleted the event with the ID "2456".


key: _node_content
string_value:
{"id_": "c6b55ba1-745f-4674-bcf3-b2af5e594b3a", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "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": "c2c08d37-ad5d-4e68-aa20-5b394e70c58d", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "320449d23351b1cf0a2cb2b2a860f553e095360d72a221363626e67c1b2c9eae", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1d923ff3-0073-4c85-97a0-11fc10f0f07f", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Function_calling_with_an_OpenAPI_spec.ipynb", "title": "Function-calling with an OpenAPI specification", "tokens": 4377, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "b5fdaa3cfe5dba11e23f0e8129d955ed6dac2cd01a1d8356c41897e361fb78e5", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 18868, "end_char_idx": 19410, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
### Conclusion

We have demonstrated how to convert OpenAPI specs into function specifications that can be given to GPT for it to intelligently call them, and shown how these can be chained together to perform complex operations.

Possible extensions of this system could include handling more complex user instructions that require conditional logic or looping, integrating with real APIs to perform actual operations, and improving error handling and validation to ensure the instructions are feasible and the function calls are successful.


key: _node_content
string_value:
{"id_": "3b9d2e4b-36f9-4b90-9538-a4a8d2213813", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "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": "cd52fda3-48a3-4c49-9323-9405011623a3", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "1899896e53545e283511cf8193459289fb7e57bef074f26d5399968bf51bf744", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2d1fb0e2-ecdb-4ae4-a88c-671fbc01f169", "node_type": "1", "metadata": {}, "hash": "f19327d32a838ac329cc673258b0bd4b9f61853e1cb407f151dc3a9154e14c9f", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 1839, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# How to stream completions

By default, when you request a completion from the OpenAI, the entire completion is generated before being sent back in a single response.

If you're generating long completions, waiting for the response can take many seconds.

To get responses sooner, you can 'stream' the completion as it's being generated. This allows you to start printing or processing the beginning of the completion before the full completion is finished.

To stream completions, set `stream=True` when calling the chat completions or completions endpoints. This will return an object that streams back the response as [data-only server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format). Extract chunks from the `delta` field rather than the `message` field.

## Downsides

Note that using `stream=True` in a production application makes it more difficult to moderate the content of the completions, as partial completions may be more difficult to evaluate. This may have implications for [approved usage](https://beta.openai.com/docs/usage-guidelines).

## Example code

Below, this notebook shows:
1. What a typical chat completion response looks like
2. What a streaming chat completion response looks like
3. How much time is saved by streaming a chat completion
4. How to get token usage data for streamed chat completion response


```python
# !pip install openai
```


```python
# imports
import time  # for measuring time duration of API calls
from openai import OpenAI
import os
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY", "<your OpenAI API key if not set as env var>"))
```

### 1. What a typical chat completion response looks like

With a typical ChatCompletions API call, the response is first computed and then returned all at once.


key: _node_content
string_value:
{"id_": "2d1fb0e2-ecdb-4ae4-a88c-671fbc01f169", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "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": "cd52fda3-48a3-4c49-9323-9405011623a3", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "1899896e53545e283511cf8193459289fb7e57bef074f26d5399968bf51bf744", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3b9d2e4b-36f9-4b90-9538-a4a8d2213813", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "5a0cd82d08fdd19c349eaa11bf48290202446daa93c7af3fad6776f1a5fc83b5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e03a344b-d1ea-4e69-9d24-713daa344edd", "node_type": "1", "metadata": {}, "hash": "005efff13db7f0180872f8e879cc3d54467c9984564ac5ee8e217521a0e3d4ad", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3477, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# How to stream completions

By default, when you request a completion from the OpenAI, the entire completion is generated before being sent back in a single response.

If you're generating long completions, waiting for the response can take many seconds.

To get responses sooner, you can 'stream' the completion as it's being generated. This allows you to start printing or processing the beginning of the completion before the full completion is finished.

To stream completions, set `stream=True` when calling the chat completions or completions endpoints. This will return an object that streams back the response as [data-only server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format). Extract chunks from the `delta` field rather than the `message` field.

## Downsides

Note that using `stream=True` in a production application makes it more difficult to moderate the content of the completions, as partial completions may be more difficult to evaluate. This may have implications for [approved usage](https://beta.openai.com/docs/usage-guidelines).

## Example code

Below, this notebook shows:
1. What a typical chat completion response looks like
2. What a streaming chat completion response looks like
3. How much time is saved by streaming a chat completion
4. How to get token usage data for streamed chat completion response


```python
# !pip install openai
```


```python
# imports
import time  # for measuring time duration of API calls
from openai import OpenAI
import os
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY", "<your OpenAI API key if not set as env var>"))
```

### 1. What a typical chat completion response looks like

With a typical ChatCompletions API call, the response is first computed and then returned all at once.


```python
# Example of an OpenAI ChatCompletion request
# https://platform.openai.com/docs/guides/text-generation/chat-completions-api

# record the time before the request is sent
start_time = time.time()

# send a ChatCompletion request to count to 100
response = client.chat.completions.create(
    model='gpt-4o-mini',
    messages=[
        {'role': 'user', 'content': 'Count to 100, with a comma between each number and no newlines. E.g., 1, 2, 3, ...'}
    ],
    temperature=0,
)
# calculate the time it took to receive the response
response_time = time.time() - start_time

# print the time delay and text received
print(f"Full response received {response_time:.2f} seconds after request")
print(f"Full response received:\n{response}")

```

    Full response received 1.88 seconds after request
    Full response received:
    ChatCompletion(id='chatcmpl-9lMgdoiMfxVHPDNVCtvXuTWcQ2GGb', choices=[Choice(finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage(content='1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100', role='assistant', function_call=None, tool_calls=None))], created=1721075651, model='gpt-july-test', object='chat.completion', system_fingerprint='fp_e9b8ed65d2', usage=CompletionUsage(completion_tokens=298, prompt_tokens=36, total_tokens=334))


key: _node_content
string_value:
{"id_": "e03a344b-d1ea-4e69-9d24-713daa344edd", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "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": "cd52fda3-48a3-4c49-9323-9405011623a3", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "1899896e53545e283511cf8193459289fb7e57bef074f26d5399968bf51bf744", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2d1fb0e2-ecdb-4ae4-a88c-671fbc01f169", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "73ed6f129e77e34dccd27d605662579288be420ad78ed763f19a86abf80e0db5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "718b600a-475e-4f76-a50c-635f23d292fa", "node_type": "1", "metadata": {}, "hash": "ac916f2d332902c67eb053fd839078736f445348dd1e5a82cb4aaad43eed1e4e", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3480, "end_char_idx": 4744, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The reply can be extracted with `response.choices[0].message`.

The content of the reply can be extracted with `response.choices[0].message.content`.


```python
reply = response.choices[0].message
print(f"Extracted reply: \n{reply}")

reply_content = response.choices[0].message.content
print(f"Extracted content: \n{reply_content}")

```

    Extracted reply: 
    ChatCompletionMessage(content='1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100', role='assistant', function_call=None, tool_calls=None)
    Extracted content: 
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100


key: _node_content
string_value:
{"id_": "718b600a-475e-4f76-a50c-635f23d292fa", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "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": "cd52fda3-48a3-4c49-9323-9405011623a3", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "1899896e53545e283511cf8193459289fb7e57bef074f26d5399968bf51bf744", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e03a344b-d1ea-4e69-9d24-713daa344edd", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "c57ab63573fb61bbf33c31252fcb2e7e1442d4eaed7ebb83381b8ca815fccbb9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e3a06e4d-507c-4f40-b16e-482467c82159", "node_type": "1", "metadata": {}, "hash": "ef6f9c1af415f37e91b90b1e154b5ada9453c801582d4aa752af14f769138842", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 4747, "end_char_idx": 7494, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
### 2. How to stream a chat completion

With a streaming API call, the response is sent back incrementally in chunks via an [event stream](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format). In Python, you can iterate over these events with a `for` loop.

Let's see what it looks like:


```python
# Example of an OpenAI ChatCompletion request with stream=True
# https://platform.openai.com/docs/api-reference/streaming#chat/create-stream

# a ChatCompletion request
response = client.chat.completions.create(
    model='gpt-4o-mini',
    messages=[
        {'role': 'user', 'content': "What's 1+1? Answer in one word."}
    ],
    temperature=0,
    stream=True  # this time, we set stream=True
)

for chunk in response:
    print(chunk)
    print(chunk.choices[0].delta.content)
    print("****************")
```

    ChatCompletionChunk(id='chatcmpl-9lMgfRSWPHcw51s6wxKT1YEO2CKpd', choices=[Choice(delta=ChoiceDelta(content='', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=0, logprobs=None)], created=1721075653, model='gpt-july-test', object='chat.completion.chunk', system_fingerprint='fp_e9b8ed65d2', usage=None)
    
    ****************
    ChatCompletionChunk(id='chatcmpl-9lMgfRSWPHcw51s6wxKT1YEO2CKpd', choices=[Choice(delta=ChoiceDelta(content='Two', function_call=None, role=None, tool_calls=None), finish_reason=None, index=0, logprobs=None)], created=1721075653, model='gpt-july-test', object='chat.completion.chunk', system_fingerprint='fp_e9b8ed65d2', usage=None)
    Two
    ****************
    ChatCompletionChunk(id='chatcmpl-9lMgfRSWPHcw51s6wxKT1YEO2CKpd', choices=[Choice(delta=ChoiceDelta(content='.', function_call=None, role=None, tool_calls=None), finish_reason=None, index=0, logprobs=None)], created=1721075653, model='gpt-july-test', object='chat.completion.chunk', system_fingerprint='fp_e9b8ed65d2', usage=None)
    .
    ****************
    ChatCompletionChunk(id='chatcmpl-9lMgfRSWPHcw51s6wxKT1YEO2CKpd', choices=[Choice(delta=ChoiceDelta(content=None, function_call=None, role=None, tool_calls=None), finish_reason='stop', index=0, logprobs=None)], created=1721075653, model='gpt-july-test', object='chat.completion.chunk', system_fingerprint='fp_e9b8ed65d2', usage=None)
    None
    ****************


As you can see above, streaming responses have a `delta` field rather than a `message` field. `delta` can hold things like:
- a role token (e.g., `{"role": "assistant"}`)
- a content token (e.g., `{"content": "\n\n"}`)
- nothing (e.g., `{}`), when the stream is over

### 3. How much time is saved by streaming a chat completion

Now let's ask `gpt-4o-mini` to count to 100 again, and see how long it takes.


key: _node_content
string_value:
{"id_": "e3a06e4d-507c-4f40-b16e-482467c82159", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "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": "cd52fda3-48a3-4c49-9323-9405011623a3", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "1899896e53545e283511cf8193459289fb7e57bef074f26d5399968bf51bf744", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "718b600a-475e-4f76-a50c-635f23d292fa", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "b36d417b1138bd1bf86efea774837f09d2baf5cb09dc042730716ac08d822dac", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "34fae6d2-108d-4115-ba96-34f9e46f89e2", "node_type": "1", "metadata": {}, "hash": "779bc69aeff0fdd1ed72b851d81a2391ccd79794595fcc30778b32c2a8521097", "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:
As you can see above, streaming responses have a `delta` field rather than a `message` field. `delta` can hold things like:
- a role token (e.g., `{"role": "assistant"}`)
- a content token (e.g., `{"content": "\n\n"}`)
- nothing (e.g., `{}`), when the stream is over

### 3. How much time is saved by streaming a chat completion

Now let's ask `gpt-4o-mini` to count to 100 again, and see how long it takes.


```python
# Example of an OpenAI ChatCompletion request with stream=True
# https://platform.openai.com/docs/api-reference/streaming#chat/create-stream

# record the time before the request is sent
start_time = time.time()

# send a ChatCompletion request to count to 100
response = client.chat.completions.create(
    model='gpt-4o-mini',
    messages=[
        {'role': 'user', 'content': 'Count to 100, with a comma between each number and no newlines. E.g. 1, 2, 3, .'}
    ],
    temperature=0,
    stream=True  # again, we set stream=True
)
# create variables to collect the stream of chunks
collected_chunks = []
collected_messages = []
# iterate through the stream of events
for chunk in response:
    chunk_time = time.time() - start_time  # calculate the time delay of the chunk
    collected_chunks.append(chunk)  # save the event response
    chunk_message = chunk.choices[0].delta.content  # extract the message
    collected_messages.append(chunk_message)  # save the message
    print(f"Message received {chunk_time:.2f} seconds after request: {chunk_message}")  # print the delay and text

# print the time delay and text received
print(f"Full response received {chunk_time:.2f} seconds after request")
# clean None in collected_messages
collected_messages = [m for m in collected_messages if m is not None]
full_reply_content = ''.join(collected_messages)
print(f"Full conversation received: {full_reply_content}")

```

    Message received 1.14 seconds after request: 
    Message received 1.14 seconds after request: 1
    Message received 1.14 seconds after request: ,
    Message received 1.14 seconds after request:  
    Message received 1.14 seconds after request: 2
    Message received 1.16 seconds after request: ,
    Message received 1.16 seconds after request:  
    Message received 1.16 seconds after request: 3
    Message received 1.35 seconds after request: ,
    Message received 1.35 seconds after request:  
    Message received 1.35 seconds after request: 4
    Message received 1.36 seconds after request: ,
    Message received 1.36 seconds after request:  
    Message received 1.36 seconds after request: 5
    Message received 1.36 seconds after request: ,
    Message received 1.36 seconds after request:  
    Message received 1.36 seconds after request: 6
    Message received 1.36 seconds after request: ,
    Message received 1.36 seconds after request:  
    Message received 1.36 seconds after request: 7
    Message received 1.36 seconds after request: ,
    Message received 1.36 seconds after request:  
    Message received 1.


key: _node_content
string_value:
{"id_": "34fae6d2-108d-4115-ba96-34f9e46f89e2", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "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": "cd52fda3-48a3-4c49-9323-9405011623a3", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "1899896e53545e283511cf8193459289fb7e57bef074f26d5399968bf51bf744", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e3a06e4d-507c-4f40-b16e-482467c82159", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "05bbb6b1cc28d45431043ac9a3bc03f02e5be00ca875a698db5554e51214bffb", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b99a5a59-930d-46e7-b3af-d6e22ad27b94", "node_type": "1", "metadata": {}, "hash": "e933aaa3447735fdea2b308e50d5c1fe195176a3537232f889e8a4a1e2295d82", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 8531, "end_char_idx": 11619, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
2f} seconds after request: {chunk_message}")  # print the delay and text

# print the time delay and text received
print(f"Full response received {chunk_time:.2f} seconds after request")
# clean None in collected_messages
collected_messages = [m for m in collected_messages if m is not None]
full_reply_content = ''.join(collected_messages)
print(f"Full conversation received: {full_reply_content}")

```

    Message received 1.14 seconds after request: 
    Message received 1.14 seconds after request: 1
    Message received 1.14 seconds after request: ,
    Message received 1.14 seconds after request:  
    Message received 1.14 seconds after request: 2
    Message received 1.16 seconds after request: ,
    Message received 1.16 seconds after request:  
    Message received 1.16 seconds after request: 3
    Message received 1.35 seconds after request: ,
    Message received 1.35 seconds after request:  
    Message received 1.35 seconds after request: 4
    Message received 1.36 seconds after request: ,
    Message received 1.36 seconds after request:  
    Message received 1.36 seconds after request: 5
    Message received 1.36 seconds after request: ,
    Message received 1.36 seconds after request:  
    Message received 1.36 seconds after request: 6
    Message received 1.36 seconds after request: ,
    Message received 1.36 seconds after request:  
    Message received 1.36 seconds after request: 7
    Message received 1.36 seconds after request: ,
    Message received 1.36 seconds after request:  
    Message received 1.36 seconds after request: 8
    Message received 1.36 seconds after request: ,
    Message received 1.36 seconds after request:  
    Message received 1.36 seconds after request: 9
    Message received 1.36 seconds after request: ,
    Message received 1.36 seconds after request:  
    Message received 1.36 seconds after request: 10
    Message received 1.36 seconds after request: ,
    Message received 1.36 seconds after request:  
    Message received 1.36 seconds after request: 11
    Message received 1.36 seconds after request: ,
    Message received 1.36 seconds after request:  
    Message received 1.36 seconds after request: 12
    Message received 1.36 seconds after request: ,
    Message received 1.36 seconds after request:  
    Message received 1.45 seconds after request: 13
    Message received 1.45 seconds after request: ,
    Message received 1.45 seconds after request:  
    Message received 1.45 seconds after request: 14
    Message received 1.45 seconds after request: ,
    Message received 1.45 seconds after request:  
    Message received 1.45 seconds after request: 15
    Message received 1.45 seconds after request: ,
    Message received 1.45 seconds after request:  
    Message received 1.46 seconds after request: 16
    Message received 1.46 seconds after request: ,
    Message received 1.46 seconds after request:  
    Message received 1.47 seconds after request: 17
    Message received 1.47 seconds after request: ,
    Message received 1.47 seconds after request:  
    Message received 1.


key: _node_content
string_value:
{"id_": "b99a5a59-930d-46e7-b3af-d6e22ad27b94", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "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": "cd52fda3-48a3-4c49-9323-9405011623a3", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "1899896e53545e283511cf8193459289fb7e57bef074f26d5399968bf51bf744", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "34fae6d2-108d-4115-ba96-34f9e46f89e2", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "4fa9c167d7bfe42fcd0dc182121cad3e89b33a896752841c5994cf16d3ceaa60", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3896a659-59be-44a7-9e0b-95632ecd4f76", "node_type": "1", "metadata": {}, "hash": "f0fc35973dc7c9ea1a318144fb7fa672bb9a80d659ab774b140d9cabad8de82c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 10081, "end_char_idx": 13108, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
36 seconds after request: 8
    Message received 1.36 seconds after request: ,
    Message received 1.36 seconds after request:  
    Message received 1.36 seconds after request: 9
    Message received 1.36 seconds after request: ,
    Message received 1.36 seconds after request:  
    Message received 1.36 seconds after request: 10
    Message received 1.36 seconds after request: ,
    Message received 1.36 seconds after request:  
    Message received 1.36 seconds after request: 11
    Message received 1.36 seconds after request: ,
    Message received 1.36 seconds after request:  
    Message received 1.36 seconds after request: 12
    Message received 1.36 seconds after request: ,
    Message received 1.36 seconds after request:  
    Message received 1.45 seconds after request: 13
    Message received 1.45 seconds after request: ,
    Message received 1.45 seconds after request:  
    Message received 1.45 seconds after request: 14
    Message received 1.45 seconds after request: ,
    Message received 1.45 seconds after request:  
    Message received 1.45 seconds after request: 15
    Message received 1.45 seconds after request: ,
    Message received 1.45 seconds after request:  
    Message received 1.46 seconds after request: 16
    Message received 1.46 seconds after request: ,
    Message received 1.46 seconds after request:  
    Message received 1.47 seconds after request: 17
    Message received 1.47 seconds after request: ,
    Message received 1.47 seconds after request:  
    Message received 1.49 seconds after request: 18
    Message received 1.49 seconds after request: ,
    Message received 1.49 seconds after request:  
    Message received 1.52 seconds after request: 19
    Message received 1.52 seconds after request: ,
    Message received 1.52 seconds after request:  
    Message received 1.53 seconds after request: 20
    Message received 1.53 seconds after request: ,
    Message received 1.53 seconds after request:  
    Message received 1.55 seconds after request: 21
    Message received 1.55 seconds after request: ,
    Message received 1.55 seconds after request:  
    Message received 1.56 seconds after request: 22
    Message received 1.56 seconds after request: ,
    Message received 1.56 seconds after request:  
    Message received 1.58 seconds after request: 23
    Message received 1.58 seconds after request: ,
    Message received 1.58 seconds after request:  
    Message received 1.59 seconds after request: 24
    Message received 1.59 seconds after request: ,
    Message received 1.59 seconds after request:  
    Message received 1.62 seconds after request: 25
    Message received 1.62 seconds after request: ,
    Message received 1.62 seconds after request:  
    Message received 1.62 seconds after request: 26
    Message received 1.62 seconds after request: ,
    Message received 1.62 seconds after request:  
    Message received 1.65 seconds after request: 27
    Message received 1.65 seconds after request: ,
    Message received 1.


key: _node_content
string_value:
{"id_": "3896a659-59be-44a7-9e0b-95632ecd4f76", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "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": "cd52fda3-48a3-4c49-9323-9405011623a3", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "1899896e53545e283511cf8193459289fb7e57bef074f26d5399968bf51bf744", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b99a5a59-930d-46e7-b3af-d6e22ad27b94", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "6446db0916105af12cec88636fa4f09884452006e4fdf442113bc6deabecf753", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2b7739c0-d8ae-42e5-9bad-81156edc8f6a", "node_type": "1", "metadata": {}, "hash": "b7af32aeb1fa9366341e3d56383a84ce543ab2fa36fc9625e753f2aceb2538d5", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 11549, "end_char_idx": 14597, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Message received 1.47 seconds after request:  
    Message received 1.49 seconds after request: 18
    Message received 1.49 seconds after request: ,
    Message received 1.49 seconds after request:  
    Message received 1.52 seconds after request: 19
    Message received 1.52 seconds after request: ,
    Message received 1.52 seconds after request:  
    Message received 1.53 seconds after request: 20
    Message received 1.53 seconds after request: ,
    Message received 1.53 seconds after request:  
    Message received 1.55 seconds after request: 21
    Message received 1.55 seconds after request: ,
    Message received 1.55 seconds after request:  
    Message received 1.56 seconds after request: 22
    Message received 1.56 seconds after request: ,
    Message received 1.56 seconds after request:  
    Message received 1.58 seconds after request: 23
    Message received 1.58 seconds after request: ,
    Message received 1.58 seconds after request:  
    Message received 1.59 seconds after request: 24
    Message received 1.59 seconds after request: ,
    Message received 1.59 seconds after request:  
    Message received 1.62 seconds after request: 25
    Message received 1.62 seconds after request: ,
    Message received 1.62 seconds after request:  
    Message received 1.62 seconds after request: 26
    Message received 1.62 seconds after request: ,
    Message received 1.62 seconds after request:  
    Message received 1.65 seconds after request: 27
    Message received 1.65 seconds after request: ,
    Message received 1.65 seconds after request:  
    Message received 1.67 seconds after request: 28
    Message received 1.67 seconds after request: ,
    Message received 1.67 seconds after request:  
    Message received 1.69 seconds after request: 29
    Message received 1.69 seconds after request: ,
    Message received 1.69 seconds after request:  
    Message received 1.80 seconds after request: 30
    Message received 1.80 seconds after request: ,
    Message received 1.80 seconds after request:  
    Message received 1.80 seconds after request: 31
    Message received 1.80 seconds after request: ,
    Message received 1.80 seconds after request:  
    Message received 1.80 seconds after request: 32
    Message received 1.80 seconds after request: ,
    Message received 1.80 seconds after request:  
    Message received 1.80 seconds after request: 33
    Message received 1.80 seconds after request: ,
    Message received 1.80 seconds after request:  
    Message received 1.80 seconds after request: 34
    Message received 1.80 seconds after request: ,
    Message received 1.80 seconds after request:  
    Message received 1.80 seconds after request: 35
    Message received 1.80 seconds after request: ,
    Message received 1.80 seconds after request:  
    Message received 1.80 seconds after request: 36
    Message received 1.80 seconds after request: ,
    Message received 1.80 seconds after request:  
    Message received 1.82 seconds after request: 37
    Message received 1.


key: _node_content
string_value:
{"id_": "2b7739c0-d8ae-42e5-9bad-81156edc8f6a", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "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": "cd52fda3-48a3-4c49-9323-9405011623a3", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "1899896e53545e283511cf8193459289fb7e57bef074f26d5399968bf51bf744", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3896a659-59be-44a7-9e0b-95632ecd4f76", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "cf0323d010e5c315f15d00e961a0fcacc7f6fa74d789b9b781697798338d0eb7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7bc4f711-1c31-43bc-9b88-33dd3f6c7fd4", "node_type": "1", "metadata": {}, "hash": "01d3ed79cd8f6611ace1320414834ddecc40eea4210524827fc05ef963c989e4", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 13057, "end_char_idx": 16085, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
65 seconds after request: ,
    Message received 1.65 seconds after request:  
    Message received 1.67 seconds after request: 28
    Message received 1.67 seconds after request: ,
    Message received 1.67 seconds after request:  
    Message received 1.69 seconds after request: 29
    Message received 1.69 seconds after request: ,
    Message received 1.69 seconds after request:  
    Message received 1.80 seconds after request: 30
    Message received 1.80 seconds after request: ,
    Message received 1.80 seconds after request:  
    Message received 1.80 seconds after request: 31
    Message received 1.80 seconds after request: ,
    Message received 1.80 seconds after request:  
    Message received 1.80 seconds after request: 32
    Message received 1.80 seconds after request: ,
    Message received 1.80 seconds after request:  
    Message received 1.80 seconds after request: 33
    Message received 1.80 seconds after request: ,
    Message received 1.80 seconds after request:  
    Message received 1.80 seconds after request: 34
    Message received 1.80 seconds after request: ,
    Message received 1.80 seconds after request:  
    Message received 1.80 seconds after request: 35
    Message received 1.80 seconds after request: ,
    Message received 1.80 seconds after request:  
    Message received 1.80 seconds after request: 36
    Message received 1.80 seconds after request: ,
    Message received 1.80 seconds after request:  
    Message received 1.82 seconds after request: 37
    Message received 1.82 seconds after request: ,
    Message received 1.82 seconds after request:  
    Message received 1.83 seconds after request: 38
    Message received 1.83 seconds after request: ,
    Message received 1.83 seconds after request:  
    Message received 1.84 seconds after request: 39
    Message received 1.84 seconds after request: ,
    Message received 1.84 seconds after request:  
    Message received 1.87 seconds after request: 40
    Message received 1.87 seconds after request: ,
    Message received 1.87 seconds after request:  
    Message received 1.88 seconds after request: 41
    Message received 1.88 seconds after request: ,
    Message received 1.88 seconds after request:  
    Message received 1.91 seconds after request: 42
    Message received 1.91 seconds after request: ,
    Message received 1.91 seconds after request:  
    Message received 1.93 seconds after request: 43
    Message received 1.93 seconds after request: ,
    Message received 1.93 seconds after request:  
    Message received 1.93 seconds after request: 44
    Message received 1.93 seconds after request: ,
    Message received 1.93 seconds after request:  
    Message received 1.95 seconds after request: 45
    Message received 1.95 seconds after request: ,
    Message received 1.95 seconds after request:  
    Message received 2.00 seconds after request: 46
    Message received 2.00 seconds after request: ,
    Message received 2.00 seconds after request:  
    Message received 2.


key: _node_content
string_value:
{"id_": "7bc4f711-1c31-43bc-9b88-33dd3f6c7fd4", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "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": "cd52fda3-48a3-4c49-9323-9405011623a3", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "1899896e53545e283511cf8193459289fb7e57bef074f26d5399968bf51bf744", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2b7739c0-d8ae-42e5-9bad-81156edc8f6a", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "457ed357f736d9e94bda8624439493c9677e147473a0f5869910bffb89ac7104", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "00d66f0b-31e2-46e5-b60a-ebe139ff2519", "node_type": "1", "metadata": {}, "hash": "e373b8bb67795f0e105c05d36666c8abab17a55233444120239d2153e0956e03", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 14545, "end_char_idx": 17574, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
82 seconds after request: 37
    Message received 1.82 seconds after request: ,
    Message received 1.82 seconds after request:  
    Message received 1.83 seconds after request: 38
    Message received 1.83 seconds after request: ,
    Message received 1.83 seconds after request:  
    Message received 1.84 seconds after request: 39
    Message received 1.84 seconds after request: ,
    Message received 1.84 seconds after request:  
    Message received 1.87 seconds after request: 40
    Message received 1.87 seconds after request: ,
    Message received 1.87 seconds after request:  
    Message received 1.88 seconds after request: 41
    Message received 1.88 seconds after request: ,
    Message received 1.88 seconds after request:  
    Message received 1.91 seconds after request: 42
    Message received 1.91 seconds after request: ,
    Message received 1.91 seconds after request:  
    Message received 1.93 seconds after request: 43
    Message received 1.93 seconds after request: ,
    Message received 1.93 seconds after request:  
    Message received 1.93 seconds after request: 44
    Message received 1.93 seconds after request: ,
    Message received 1.93 seconds after request:  
    Message received 1.95 seconds after request: 45
    Message received 1.95 seconds after request: ,
    Message received 1.95 seconds after request:  
    Message received 2.00 seconds after request: 46
    Message received 2.00 seconds after request: ,
    Message received 2.00 seconds after request:  
    Message received 2.00 seconds after request: 47
    Message received 2.00 seconds after request: ,
    Message received 2.00 seconds after request:  
    Message received 2.00 seconds after request: 48
    Message received 2.00 seconds after request: ,
    Message received 2.00 seconds after request:  
    Message received 2.00 seconds after request: 49
    Message received 2.00 seconds after request: ,
    Message received 2.00 seconds after request:  
    Message received 2.00 seconds after request: 50
    Message received 2.00 seconds after request: ,
    Message received 2.00 seconds after request:  
    Message received 2.00 seconds after request: 51
    Message received 2.00 seconds after request: ,
    Message received 2.04 seconds after request:  
    Message received 2.04 seconds after request: 52
    Message received 2.04 seconds after request: ,
    Message received 2.04 seconds after request:  
    Message received 2.04 seconds after request: 53
    Message received 2.04 seconds after request: ,
    Message received 2.13 seconds after request:  
    Message received 2.13 seconds after request: 54
    Message received 2.14 seconds after request: ,
    Message received 2.14 seconds after request:  
    Message received 2.14 seconds after request: 55
    Message received 2.14 seconds after request: ,
    Message received 2.14 seconds after request:  
    Message received 2.14 seconds after request: 56
    Message received 2.14 seconds after request: ,
    Message received 2.


key: _node_content
string_value:
{"id_": "00d66f0b-31e2-46e5-b60a-ebe139ff2519", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "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": "cd52fda3-48a3-4c49-9323-9405011623a3", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "1899896e53545e283511cf8193459289fb7e57bef074f26d5399968bf51bf744", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7bc4f711-1c31-43bc-9b88-33dd3f6c7fd4", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "a6548694a6b07eab6594ad14b832a87723f0b5c089d355d83e302e4b753c5584", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a2f7acd4-5cd8-495e-8684-5ad8190421d7", "node_type": "1", "metadata": {}, "hash": "5d1551b475dd6cd0b5e3075c8b3260f5a1edfc05bee9458dfd05c39a041e25c3", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 16015, "end_char_idx": 19063, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Message received 2.00 seconds after request:  
    Message received 2.00 seconds after request: 47
    Message received 2.00 seconds after request: ,
    Message received 2.00 seconds after request:  
    Message received 2.00 seconds after request: 48
    Message received 2.00 seconds after request: ,
    Message received 2.00 seconds after request:  
    Message received 2.00 seconds after request: 49
    Message received 2.00 seconds after request: ,
    Message received 2.00 seconds after request:  
    Message received 2.00 seconds after request: 50
    Message received 2.00 seconds after request: ,
    Message received 2.00 seconds after request:  
    Message received 2.00 seconds after request: 51
    Message received 2.00 seconds after request: ,
    Message received 2.04 seconds after request:  
    Message received 2.04 seconds after request: 52
    Message received 2.04 seconds after request: ,
    Message received 2.04 seconds after request:  
    Message received 2.04 seconds after request: 53
    Message received 2.04 seconds after request: ,
    Message received 2.13 seconds after request:  
    Message received 2.13 seconds after request: 54
    Message received 2.14 seconds after request: ,
    Message received 2.14 seconds after request:  
    Message received 2.14 seconds after request: 55
    Message received 2.14 seconds after request: ,
    Message received 2.14 seconds after request:  
    Message received 2.14 seconds after request: 56
    Message received 2.14 seconds after request: ,
    Message received 2.14 seconds after request:  
    Message received 2.16 seconds after request: 57
    Message received 2.16 seconds after request: ,
    Message received 2.16 seconds after request:  
    Message received 2.17 seconds after request: 58
    Message received 2.17 seconds after request: ,
    Message received 2.17 seconds after request:  
    Message received 2.19 seconds after request: 59
    Message received 2.19 seconds after request: ,
    Message received 2.19 seconds after request:  
    Message received 2.21 seconds after request: 60
    Message received 2.21 seconds after request: ,
    Message received 2.21 seconds after request:  
    Message received 2.34 seconds after request: 61
    Message received 2.34 seconds after request: ,
    Message received 2.34 seconds after request:  
    Message received 2.34 seconds after request: 62
    Message received 2.34 seconds after request: ,
    Message received 2.34 seconds after request:  
    Message received 2.34 seconds after request: 63
    Message received 2.34 seconds after request: ,
    Message received 2.34 seconds after request:  
    Message received 2.34 seconds after request: 64
    Message received 2.34 seconds after request: ,
    Message received 2.34 seconds after request:  
    Message received 2.34 seconds after request: 65
    Message received 2.34 seconds after request: ,
    Message received 2.34 seconds after request:  
    Message received 2.34 seconds after request: 66
    Message received 2.


key: _node_content
string_value:
{"id_": "a2f7acd4-5cd8-495e-8684-5ad8190421d7", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "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": "cd52fda3-48a3-4c49-9323-9405011623a3", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "1899896e53545e283511cf8193459289fb7e57bef074f26d5399968bf51bf744", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "00d66f0b-31e2-46e5-b60a-ebe139ff2519", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "ab23f01d1c350efbd15d574af79c442bf3e431d819ba01d984daa14d1356f5d2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5563eab9-73a6-4692-88f0-612c04869759", "node_type": "1", "metadata": {}, "hash": "28a893365ef4430fa3782d06243d3d0f9bf42f202812d020076ad8c02d5ef537", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 17523, "end_char_idx": 20551, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
14 seconds after request: ,
    Message received 2.14 seconds after request:  
    Message received 2.16 seconds after request: 57
    Message received 2.16 seconds after request: ,
    Message received 2.16 seconds after request:  
    Message received 2.17 seconds after request: 58
    Message received 2.17 seconds after request: ,
    Message received 2.17 seconds after request:  
    Message received 2.19 seconds after request: 59
    Message received 2.19 seconds after request: ,
    Message received 2.19 seconds after request:  
    Message received 2.21 seconds after request: 60
    Message received 2.21 seconds after request: ,
    Message received 2.21 seconds after request:  
    Message received 2.34 seconds after request: 61
    Message received 2.34 seconds after request: ,
    Message received 2.34 seconds after request:  
    Message received 2.34 seconds after request: 62
    Message received 2.34 seconds after request: ,
    Message received 2.34 seconds after request:  
    Message received 2.34 seconds after request: 63
    Message received 2.34 seconds after request: ,
    Message received 2.34 seconds after request:  
    Message received 2.34 seconds after request: 64
    Message received 2.34 seconds after request: ,
    Message received 2.34 seconds after request:  
    Message received 2.34 seconds after request: 65
    Message received 2.34 seconds after request: ,
    Message received 2.34 seconds after request:  
    Message received 2.34 seconds after request: 66
    Message received 2.34 seconds after request: ,
    Message received 2.34 seconds after request:  
    Message received 2.34 seconds after request: 67
    Message received 2.34 seconds after request: ,
    Message received 2.34 seconds after request:  
    Message received 2.36 seconds after request: 68
    Message received 2.36 seconds after request: ,
    Message received 2.36 seconds after request:  
    Message received 2.36 seconds after request: 69
    Message received 2.36 seconds after request: ,
    Message received 2.36 seconds after request:  
    Message received 2.38 seconds after request: 70
    Message received 2.38 seconds after request: ,
    Message received 2.38 seconds after request:  
    Message received 2.39 seconds after request: 71
    Message received 2.39 seconds after request: ,
    Message received 2.39 seconds after request:  
    Message received 2.39 seconds after request: 72
    Message received 2.39 seconds after request: ,
    Message received 2.39 seconds after request:  
    Message received 2.39 seconds after request: 73
    Message received 2.39 seconds after request: ,
    Message received 2.39 seconds after request:  
    Message received 2.39 seconds after request: 74
    Message received 2.39 seconds after request: ,
    Message received 2.39 seconds after request:  
    Message received 2.39 seconds after request: 75
    Message received 2.39 seconds after request: ,
    Message received 2.40 seconds after request:  
    Message received 2.


key: _node_content
string_value:
{"id_": "5563eab9-73a6-4692-88f0-612c04869759", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "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": "cd52fda3-48a3-4c49-9323-9405011623a3", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "1899896e53545e283511cf8193459289fb7e57bef074f26d5399968bf51bf744", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a2f7acd4-5cd8-495e-8684-5ad8190421d7", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "c7db4e83f862872af4ae10f236f57ebc18933be7115b4d0061e2260cee4e330d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e2b67e51-c9a4-49ae-9bb1-aca4f2a5a95f", "node_type": "1", "metadata": {}, "hash": "b636dfe2181dfdfeb0dbdd009acec1f21ac55c3f7718ac3892b0e4cc6137d3b6", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 19011, "end_char_idx": 22040, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
34 seconds after request: 66
    Message received 2.34 seconds after request: ,
    Message received 2.34 seconds after request:  
    Message received 2.34 seconds after request: 67
    Message received 2.34 seconds after request: ,
    Message received 2.34 seconds after request:  
    Message received 2.36 seconds after request: 68
    Message received 2.36 seconds after request: ,
    Message received 2.36 seconds after request:  
    Message received 2.36 seconds after request: 69
    Message received 2.36 seconds after request: ,
    Message received 2.36 seconds after request:  
    Message received 2.38 seconds after request: 70
    Message received 2.38 seconds after request: ,
    Message received 2.38 seconds after request:  
    Message received 2.39 seconds after request: 71
    Message received 2.39 seconds after request: ,
    Message received 2.39 seconds after request:  
    Message received 2.39 seconds after request: 72
    Message received 2.39 seconds after request: ,
    Message received 2.39 seconds after request:  
    Message received 2.39 seconds after request: 73
    Message received 2.39 seconds after request: ,
    Message received 2.39 seconds after request:  
    Message received 2.39 seconds after request: 74
    Message received 2.39 seconds after request: ,
    Message received 2.39 seconds after request:  
    Message received 2.39 seconds after request: 75
    Message received 2.39 seconds after request: ,
    Message received 2.40 seconds after request:  
    Message received 2.40 seconds after request: 76
    Message received 2.40 seconds after request: ,
    Message received 2.42 seconds after request:  
    Message received 2.42 seconds after request: 77
    Message received 2.42 seconds after request: ,
    Message received 2.51 seconds after request:  
    Message received 2.51 seconds after request: 78
    Message received 2.51 seconds after request: ,
    Message received 2.52 seconds after request:  
    Message received 2.52 seconds after request: 79
    Message received 2.52 seconds after request: ,
    Message received 2.52 seconds after request:  
    Message received 2.52 seconds after request: 80
    Message received 2.52 seconds after request: ,
    Message received 2.52 seconds after request:  
    Message received 2.52 seconds after request: 81
    Message received 2.52 seconds after request: ,
    Message received 2.52 seconds after request:  
    Message received 2.52 seconds after request: 82
    Message received 2.52 seconds after request: ,
    Message received 2.60 seconds after request:  
    Message received 2.60 seconds after request: 83
    Message received 2.60 seconds after request: ,
    Message received 2.64 seconds after request:  
    Message received 2.64 seconds after request: 84
    Message received 2.64 seconds after request: ,
    Message received 2.64 seconds after request:  
    Message received 2.64 seconds after request: 85
    Message received 2.64 seconds after request: ,
    Message received 2.


key: _node_content
string_value:
{"id_": "e2b67e51-c9a4-49ae-9bb1-aca4f2a5a95f", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "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": "cd52fda3-48a3-4c49-9323-9405011623a3", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "1899896e53545e283511cf8193459289fb7e57bef074f26d5399968bf51bf744", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5563eab9-73a6-4692-88f0-612c04869759", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "a914ed62e1d33748dbf5b08c1c7fc5b267f90fdf253a8193863e1b129c527c0a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d56127c2-7524-4d5d-ad78-9e74aa88b4bb", "node_type": "1", "metadata": {}, "hash": "b59df920697612fb222dc49f40cd05ff0f7b18da5e334c60757c57815ee3cb22", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 20481, "end_char_idx": 23529, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Message received 2.40 seconds after request:  
    Message received 2.40 seconds after request: 76
    Message received 2.40 seconds after request: ,
    Message received 2.42 seconds after request:  
    Message received 2.42 seconds after request: 77
    Message received 2.42 seconds after request: ,
    Message received 2.51 seconds after request:  
    Message received 2.51 seconds after request: 78
    Message received 2.51 seconds after request: ,
    Message received 2.52 seconds after request:  
    Message received 2.52 seconds after request: 79
    Message received 2.52 seconds after request: ,
    Message received 2.52 seconds after request:  
    Message received 2.52 seconds after request: 80
    Message received 2.52 seconds after request: ,
    Message received 2.52 seconds after request:  
    Message received 2.52 seconds after request: 81
    Message received 2.52 seconds after request: ,
    Message received 2.52 seconds after request:  
    Message received 2.52 seconds after request: 82
    Message received 2.52 seconds after request: ,
    Message received 2.60 seconds after request:  
    Message received 2.60 seconds after request: 83
    Message received 2.60 seconds after request: ,
    Message received 2.64 seconds after request:  
    Message received 2.64 seconds after request: 84
    Message received 2.64 seconds after request: ,
    Message received 2.64 seconds after request:  
    Message received 2.64 seconds after request: 85
    Message received 2.64 seconds after request: ,
    Message received 2.64 seconds after request:  
    Message received 2.66 seconds after request: 86
    Message received 2.66 seconds after request: ,
    Message received 2.66 seconds after request:  
    Message received 2.66 seconds after request: 87
    Message received 2.66 seconds after request: ,
    Message received 2.66 seconds after request:  
    Message received 2.68 seconds after request: 88
    Message received 2.68 seconds after request: ,
    Message received 2.68 seconds after request:  
    Message received 2.69 seconds after request: 89
    Message received 2.69 seconds after request: ,
    Message received 2.69 seconds after request:  
    Message received 2.72 seconds after request: 90
    Message received 2.72 seconds after request: ,
    Message received 2.72 seconds after request:  
    Message received 2.82 seconds after request: 91
    Message received 2.82 seconds after request: ,
    Message received 2.82 seconds after request:  
    Message received 2.82 seconds after request: 92
    Message received 2.82 seconds after request: ,
    Message received 2.82 seconds after request:  
    Message received 2.82 seconds after request: 93
    Message received 2.82 seconds after request: ,
    Message received 2.82 seconds after request:  
    Message received 2.82 seconds after request: 94
    Message received 2.82 seconds after request: ,
    Message received 2.82 seconds after request:  
    Message received 2.82 seconds after request: 95
    Message received 2.


key: _node_content
string_value:
{"id_": "d56127c2-7524-4d5d-ad78-9e74aa88b4bb", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "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": "cd52fda3-48a3-4c49-9323-9405011623a3", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "1899896e53545e283511cf8193459289fb7e57bef074f26d5399968bf51bf744", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e2b67e51-c9a4-49ae-9bb1-aca4f2a5a95f", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "7ff4f4e4f438aab80dec136c218926e07ca3fa27da39923c17c53d9a31fa4aad", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2b080b32-beaf-43b4-b49c-2162bfc3fab7", "node_type": "1", "metadata": {}, "hash": "4f939bed0b7e1404426396724df577d12c16802e12332af75cb6a4a63f66eb29", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 21989, "end_char_idx": 24627, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
64 seconds after request: ,
    Message received 2.64 seconds after request:  
    Message received 2.66 seconds after request: 86
    Message received 2.66 seconds after request: ,
    Message received 2.66 seconds after request:  
    Message received 2.66 seconds after request: 87
    Message received 2.66 seconds after request: ,
    Message received 2.66 seconds after request:  
    Message received 2.68 seconds after request: 88
    Message received 2.68 seconds after request: ,
    Message received 2.68 seconds after request:  
    Message received 2.69 seconds after request: 89
    Message received 2.69 seconds after request: ,
    Message received 2.69 seconds after request:  
    Message received 2.72 seconds after request: 90
    Message received 2.72 seconds after request: ,
    Message received 2.72 seconds after request:  
    Message received 2.82 seconds after request: 91
    Message received 2.82 seconds after request: ,
    Message received 2.82 seconds after request:  
    Message received 2.82 seconds after request: 92
    Message received 2.82 seconds after request: ,
    Message received 2.82 seconds after request:  
    Message received 2.82 seconds after request: 93
    Message received 2.82 seconds after request: ,
    Message received 2.82 seconds after request:  
    Message received 2.82 seconds after request: 94
    Message received 2.82 seconds after request: ,
    Message received 2.82 seconds after request:  
    Message received 2.82 seconds after request: 95
    Message received 2.82 seconds after request: ,
    Message received 2.82 seconds after request:  
    Message received 2.82 seconds after request: 96
    Message received 2.82 seconds after request: ,
    Message received 2.82 seconds after request:  
    Message received 2.82 seconds after request: 97
    Message received 2.82 seconds after request: ,
    Message received 2.82 seconds after request:  
    Message received 2.82 seconds after request: 98
    Message received 2.82 seconds after request: ,
    Message received 2.82 seconds after request:  
    Message received 2.82 seconds after request: 99
    Message received 2.82 seconds after request: ,
    Message received 2.82 seconds after request:  
    Message received 2.82 seconds after request: 100
    Message received 2.82 seconds after request: None
    Full response received 2.82 seconds after request
    Full conversation received: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,


key: _node_content
string_value:
{"id_": "2b080b32-beaf-43b4-b49c-2162bfc3fab7", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "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": "cd52fda3-48a3-4c49-9323-9405011623a3", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "1899896e53545e283511cf8193459289fb7e57bef074f26d5399968bf51bf744", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d56127c2-7524-4d5d-ad78-9e74aa88b4bb", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "b76710825c39d38e9d00d1f650a60d0fd2eba804c7bc177d0c9355a001fdbf85", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c42e0a03-713c-410f-8257-9ca3f8fdf0b3", "node_type": "1", "metadata": {}, "hash": "80c3ef75ea4a379416a1aedbf3a57accd6de5353e65855ffc42c1de7208a8c74", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 23477, "end_char_idx": 25846, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
82 seconds after request: 95
    Message received 2.82 seconds after request: ,
    Message received 2.82 seconds after request:  
    Message received 2.82 seconds after request: 96
    Message received 2.82 seconds after request: ,
    Message received 2.82 seconds after request:  
    Message received 2.82 seconds after request: 97
    Message received 2.82 seconds after request: ,
    Message received 2.82 seconds after request:  
    Message received 2.82 seconds after request: 98
    Message received 2.82 seconds after request: ,
    Message received 2.82 seconds after request:  
    Message received 2.82 seconds after request: 99
    Message received 2.82 seconds after request: ,
    Message received 2.82 seconds after request:  
    Message received 2.82 seconds after request: 100
    Message received 2.82 seconds after request: None
    Full response received 2.82 seconds after request
    Full conversation received: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100


#### Time comparison

In the example above, both requests took about 4 to 5 seconds to fully complete. Request times will vary depending on load and other stochastic factors.

However, with the streaming request, we received the first token after 0.1 seconds, and subsequent tokens every ~0.01-0.02 seconds.

### 4. How to get token usage data for streamed chat completion response

You can get token usage statistics for your streamed response by setting `stream_options={"include_usage": True}`. When you do so, an extra chunk will be streamed as the final chunk. You can access the usage data for the entire request via the `usage` field on this chunk. A few important notes when you set `stream_options={"include_usage": True}`:
* The value for the `usage` field on all chunks except for the last one will be null.
* The `usage` field on the last chunk contains token usage statistics for the entire request.
* The `choices` field on the last chunk will always be an empty array `[]`.

Let's see how it works using the example in 2.


key: _node_content
string_value:
{"id_": "c42e0a03-713c-410f-8257-9ca3f8fdf0b3", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "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": "cd52fda3-48a3-4c49-9323-9405011623a3", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "1899896e53545e283511cf8193459289fb7e57bef074f26d5399968bf51bf744", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2b080b32-beaf-43b4-b49c-2162bfc3fab7", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb", "title": "How to stream completions", "tokens": 7537, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "5f7e7613c64174a40054a3ea675f88873722d9e447e54d755968a04357a94e4d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 24584, "end_char_idx": 27263, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100


#### Time comparison

In the example above, both requests took about 4 to 5 seconds to fully complete. Request times will vary depending on load and other stochastic factors.

However, with the streaming request, we received the first token after 0.1 seconds, and subsequent tokens every ~0.01-0.02 seconds.

### 4. How to get token usage data for streamed chat completion response

You can get token usage statistics for your streamed response by setting `stream_options={"include_usage": True}`. When you do so, an extra chunk will be streamed as the final chunk. You can access the usage data for the entire request via the `usage` field on this chunk. A few important notes when you set `stream_options={"include_usage": True}`:
* The value for the `usage` field on all chunks except for the last one will be null.
* The `usage` field on the last chunk contains token usage statistics for the entire request.
* The `choices` field on the last chunk will always be an empty array `[]`.

Let's see how it works using the example in 2.


```python
# Example of an OpenAI ChatCompletion request with stream=True and stream_options={"include_usage": True}

# a ChatCompletion request
response = client.chat.completions.create(
    model='gpt-4o-mini',
    messages=[
        {'role': 'user', 'content': "What's 1+1? Answer in one word."}
    ],
    temperature=0,
    stream=True,
    stream_options={"include_usage": True}, # retrieving token usage for stream response
)

for chunk in response:
    print(f"choices: {chunk.choices}\nusage: {chunk.usage}")
    print("****************")
```

    choices: [Choice(delta=ChoiceDelta(content='', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=0, logprobs=None)]
    usage: None
    ****************
    choices: [Choice(delta=ChoiceDelta(content='Two', function_call=None, role=None, tool_calls=None), finish_reason=None, index=0, logprobs=None)]
    usage: None
    ****************
    choices: [Choice(delta=ChoiceDelta(content='.', function_call=None, role=None, tool_calls=None), finish_reason=None, index=0, logprobs=None)]
    usage: None
    ****************
    choices: [Choice(delta=ChoiceDelta(content=None, function_call=None, role=None, tool_calls=None), finish_reason='stop', index=0, logprobs=None)]
    usage: None
    ****************
    choices: []
    usage: CompletionUsage(completion_tokens=2, prompt_tokens=18, total_tokens=20)
    ****************


key: _node_content
string_value:
{"id_": "6572842a-6e09-4d27-9563-aa8bb747e66e", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "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": "23fdd396-df57-4291-9785-a2214250ccd4", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "c02a707a8b6aefef9238a7f14c5b94c1e33e6f1631beb6895f3314a7fccdf84a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "bcaa06a1-b2fa-45f0-8000-a64bc569b316", "node_type": "1", "metadata": {}, "hash": "3ad3c2ce5822375dcc0da17307d60a2b6a9cc4717930c72646785072c48f8108", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3539, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Using logprobs for classification and Q&A evaluation

This notebook demonstrates the use of the `logprobs` parameter in the Chat Completions API. When `logprobs` is enabled, the API returns the log probabilities of each output token, along with a limited number of the most likely tokens at each token position and their log probabilities. The relevant request parameters are:
* `logprobs`: Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the content of message. This option is currently not available on the `gpt-4-vision-preview` model.
* `top_logprobs`: An integer between 0 and 5 specifying the number of most likely tokens to return at each token position, each with an associated log probability. `logprobs` must be set to true if this parameter is used.

Log probabilities of output tokens indicate the likelihood of each token occurring in the sequence given the context. To simplify, a logprob is `log(p)`, where `p` = probability of a token occurring at a specific position based on the previous tokens in the context. Some key points about `logprobs`:
* Higher log probabilities suggest a higher likelihood of the token in that context. This allows users to gauge the model's confidence in its output or explore alternative responses the model considered.
* Logprob can be any negative number or `0.0`. `0.0` corresponds to 100% probability.
* Logprobs allow us to compute the joint probability of a sequence as the sum of the logprobs of the individual tokens. This is useful for scoring and ranking model outputs. Another common approach is to take the average per-token logprob of a sentence to choose the best generation.
* We can examine the `logprobs` assigned to different candidate tokens to understand what options the model considered plausible or implausible.

While there are a wide array of use cases for `logprobs`, this notebook will focus on its use for:

1. Classification tasks

* Large Language Models excel at many classification tasks, but accurately measuring the model's confidence in its outputs can be challenging. `logprobs` provide a probability associated with each class prediction, enabling users to set their own classification or confidence thresholds.

2. Retrieval (Q&A) evaluation

* `logprobs` can assist with self-evaluation in retrieval applications. In the Q&A example, the model outputs a contrived `has_sufficient_context_for_answer` boolean, which can serve as a confidence score of whether the answer is contained in the retrieved content. Evaluations of this type can reduce retrieval-based hallucinations and enhance accuracy.

3. Autocomplete
*  `logprobs` could help us decide how to suggest words as a user is typing.

4. Token highlighting and outputting bytes
*  Users can easily create a token highlighter using the built in tokenization that comes with enabling `logprobs`. Additionally, the bytes parameter includes the ASCII encoding of each output character, which is particularly useful for reproducing emojis and special characters.

5. Calculating perplexity
* `logprobs` can be used to help us assess the model's overall confidence in a result and help us compare the confidence of results from different prompts.

## 0. Imports and utils


```python
from openai import OpenAI
from math import exp
import numpy as np
from IPython.display import display, HTML
import os

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


key: _node_content
string_value:
{"id_": "bcaa06a1-b2fa-45f0-8000-a64bc569b316", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "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": "23fdd396-df57-4291-9785-a2214250ccd4", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "c02a707a8b6aefef9238a7f14c5b94c1e33e6f1631beb6895f3314a7fccdf84a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6572842a-6e09-4d27-9563-aa8bb747e66e", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "c03df7215a423d3ee1cff32a2d74ca2b9a351eb81e8aae0e9adb3e9c2249582f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7b2b16ed-bda8-4f2b-837a-93639773803b", "node_type": "1", "metadata": {}, "hash": "024c34cf60ed7f8e2380259c61ac4e300d58c468a2b72b463ea1dea66c2680ac", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3302, "end_char_idx": 6133, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
from openai import OpenAI
from math import exp
import numpy as np
from IPython.display import display, HTML
import os

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


```python
def get_completion(
    messages: list[dict[str, str]],
    model: str = "gpt-4",
    max_tokens=500,
    temperature=0,
    stop=None,
    seed=123,
    tools=None,
    logprobs=None,  # whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the content of message..
    top_logprobs=None,
) -> str:
    params = {
        "model": model,
        "messages": messages,
        "max_tokens": max_tokens,
        "temperature": temperature,
        "stop": stop,
        "seed": seed,
        "logprobs": logprobs,
        "top_logprobs": top_logprobs,
    }
    if tools:
        params["tools"] = tools

    completion = client.chat.completions.create(**params)
    return completion
```

## 1. Using `logprobs` to assess confidence for classification tasks

Let's say we want to create a system to classify news articles into a set of pre-defined categories. Without `logprobs`, we can use Chat Completions to do this, but it is much more difficult to assess the certainty with which the model made its classifications.

Now, with `logprobs` enabled, we can see exactly how confident the model is in its predictions, which is crucial for creating an accurate and trustworthy classifier. For example, if the log probability for the chosen category is high, this suggests the model is quite confident in its classification. If it's low, this suggests the model is less confident. This can be particularly useful in cases where the model's classification is not what you expected, or when the model's output needs to be reviewed or validated by a human.

We'll begin with a prompt that presents the model with four categories: **Technology, Politics, Sports, and Arts**. The model is then tasked with classifying articles into these categories based solely on their headlines.


```python
CLASSIFICATION_PROMPT = """You will be given a headline of a news article.
Classify the article into one of the following categories: Technology, Politics, Sports, and Art.
Return only the name of the category, and nothing else.
MAKE SURE your output is one of the four categories stated.
Article headline: {headline}"""

```

Let's look at three sample headlines, and first begin with a standard Chat Completions output, without `logprobs`


```python
headlines = [
    "Tech Giant Unveils Latest Smartphone Model with Advanced Photo-Editing Features.",
    "Local Mayor Launches Initiative to Enhance Urban Public Transport.",
    "Tennis Champion Showcases Hidden Talents in Symphony Orchestra Debut",
]

```


key: _node_content
string_value:
{"id_": "7b2b16ed-bda8-4f2b-837a-93639773803b", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "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": "23fdd396-df57-4291-9785-a2214250ccd4", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "c02a707a8b6aefef9238a7f14c5b94c1e33e6f1631beb6895f3314a7fccdf84a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "bcaa06a1-b2fa-45f0-8000-a64bc569b316", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "0554c74d34ef3e4c8c9e045981bab4c248440b04d4dc11a359d0fc2e76cd3c77", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4fdb3346-0b37-41a4-8afa-7614f14f1530", "node_type": "1", "metadata": {}, "hash": "3b1b84bcabcb5a68c81422d9abc9862f320d16cb80b9873c5c2fead61c394c99", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5412, "end_char_idx": 8163, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
CLASSIFICATION_PROMPT = """You will be given a headline of a news article.
Classify the article into one of the following categories: Technology, Politics, Sports, and Art.
Return only the name of the category, and nothing else.
MAKE SURE your output is one of the four categories stated.
Article headline: {headline}"""

```

Let's look at three sample headlines, and first begin with a standard Chat Completions output, without `logprobs`


```python
headlines = [
    "Tech Giant Unveils Latest Smartphone Model with Advanced Photo-Editing Features.",
    "Local Mayor Launches Initiative to Enhance Urban Public Transport.",
    "Tennis Champion Showcases Hidden Talents in Symphony Orchestra Debut",
]

```


```python
for headline in headlines:
    print(f"\nHeadline: {headline}")
    API_RESPONSE = get_completion(
        [{"role": "user", "content": CLASSIFICATION_PROMPT.format(headline=headline)}],
        model="gpt-4",
    )
    print(f"Category: {API_RESPONSE.choices[0].message.content}\n")
```

    
    Headline: Tech Giant Unveils Latest Smartphone Model with Advanced Photo-Editing Features.
    Category: Technology
    
    
    Headline: Local Mayor Launches Initiative to Enhance Urban Public Transport.
    Category: Politics
    
    
    Headline: Tennis Champion Showcases Hidden Talents in Symphony Orchestra Debut
    Category: Art
    


Here we can see the selected category for each headline. However, we have no visibility into the confidence of the model in its predictions. Let's rerun the same prompt but with `logprobs` enabled, and `top_logprobs` set to 2 (this will show us the 2 most likely output tokens for each token). Additionally we can also output the linear probability of each output token, in order to convert the log probability to the more easily interprable scale of 0-100%. 


```python
for headline in headlines:
    print(f"\nHeadline: {headline}")
    API_RESPONSE = get_completion(
        [{"role": "user", "content": CLASSIFICATION_PROMPT.format(headline=headline)}],
        model="gpt-4",
        logprobs=True,
        top_logprobs=2,
    )
    top_two_logprobs = API_RESPONSE.choices[0].logprobs.content[0].top_logprobs
    html_content = ""
    for i, logprob in enumerate(top_two_logprobs, start=1):
        html_content += (
            f"<span style='color: cyan'>Output token {i}:</span> {logprob.token}, "
            f"<span style='color: darkorange'>logprobs:</span> {logprob.logprob}, "
            f"<span style='color: magenta'>linear probability:</span> {np.round(np.exp(logprob.logprob)*100,2)}%<br>"
        )
    display(HTML(html_content))
    print("\n")
```

    
    Headline: Tech Giant Unveils Latest Smartphone Model with Advanced Photo-Editing Features.


key: _node_content
string_value:
{"id_": "4fdb3346-0b37-41a4-8afa-7614f14f1530", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "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": "23fdd396-df57-4291-9785-a2214250ccd4", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "c02a707a8b6aefef9238a7f14c5b94c1e33e6f1631beb6895f3314a7fccdf84a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7b2b16ed-bda8-4f2b-837a-93639773803b", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "82c0b35c6987085eb811aefe6f482a03fc8aa1d2e1a9b3297446717af337f984", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "16f5c535-0705-4ae0-9ef2-e142659d3356", "node_type": "1", "metadata": {}, "hash": "179497ab64bc9f56d95e4bad86d779293e6b4a9eda260c441d23579e3bcabfc0", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 6792, "end_char_idx": 9487, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Here we can see the selected category for each headline. However, we have no visibility into the confidence of the model in its predictions. Let's rerun the same prompt but with `logprobs` enabled, and `top_logprobs` set to 2 (this will show us the 2 most likely output tokens for each token). Additionally we can also output the linear probability of each output token, in order to convert the log probability to the more easily interprable scale of 0-100%. 


```python
for headline in headlines:
    print(f"\nHeadline: {headline}")
    API_RESPONSE = get_completion(
        [{"role": "user", "content": CLASSIFICATION_PROMPT.format(headline=headline)}],
        model="gpt-4",
        logprobs=True,
        top_logprobs=2,
    )
    top_two_logprobs = API_RESPONSE.choices[0].logprobs.content[0].top_logprobs
    html_content = ""
    for i, logprob in enumerate(top_two_logprobs, start=1):
        html_content += (
            f"<span style='color: cyan'>Output token {i}:</span> {logprob.token}, "
            f"<span style='color: darkorange'>logprobs:</span> {logprob.logprob}, "
            f"<span style='color: magenta'>linear probability:</span> {np.round(np.exp(logprob.logprob)*100,2)}%<br>"
        )
    display(HTML(html_content))
    print("\n")
```

    
    Headline: Tech Giant Unveils Latest Smartphone Model with Advanced Photo-Editing Features.



<span style='color: cyan'>Output token 1:</span> Technology, <span style='color: darkorange'>logprobs:</span> -2.4584822e-06, <span style='color: magenta'>linear probability:</span> 100.0%<br><span style='color: cyan'>Output token 2:</span> Techn, <span style='color: darkorange'>logprobs:</span> -13.781253, <span style='color: magenta'>linear probability:</span> 0.0%<br>


    
    
    
    Headline: Local Mayor Launches Initiative to Enhance Urban Public Transport.



<span style='color: cyan'>Output token 1:</span> Politics, <span style='color: darkorange'>logprobs:</span> -2.4584822e-06, <span style='color: magenta'>linear probability:</span> 100.0%<br><span style='color: cyan'>Output token 2:</span> Technology, <span style='color: darkorange'>logprobs:</span> -13.937503, <span style='color: magenta'>linear probability:</span> 0.0%<br>


    
    
    
    Headline: Tennis Champion Showcases Hidden Talents in Symphony Orchestra Debut



<span style='color: cyan'>Output token 1:</span> Art, <span style='color: darkorange'>logprobs:</span> -0.009169078, <span style='color: magenta'>linear probability:</span> 99.09%<br><span style='color: cyan'>Output token 2:</span> Sports, <span style='color: darkorange'>logprobs:</span> -4.696669, <span style='color: magenta'>linear probability:</span> 0.91%<br>


key: _node_content
string_value:
{"id_": "16f5c535-0705-4ae0-9ef2-e142659d3356", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "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": "23fdd396-df57-4291-9785-a2214250ccd4", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "c02a707a8b6aefef9238a7f14c5b94c1e33e6f1631beb6895f3314a7fccdf84a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4fdb3346-0b37-41a4-8afa-7614f14f1530", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "8cc7e4d440b92d9073b6617aea77671d82f4d80ac822cf8dcd07ddbc7480c8e9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "efbbc13b-166a-4134-a8cd-f186fa265f8d", "node_type": "1", "metadata": {}, "hash": "f7b70d541e04fe42394d57c33feb604e7ed832b0d6448dcdd75c8e85ef828ad9", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 8562, "end_char_idx": 10722, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Headline: Local Mayor Launches Initiative to Enhance Urban Public Transport.



<span style='color: cyan'>Output token 1:</span> Politics, <span style='color: darkorange'>logprobs:</span> -2.4584822e-06, <span style='color: magenta'>linear probability:</span> 100.0%<br><span style='color: cyan'>Output token 2:</span> Technology, <span style='color: darkorange'>logprobs:</span> -13.937503, <span style='color: magenta'>linear probability:</span> 0.0%<br>


    
    
    
    Headline: Tennis Champion Showcases Hidden Talents in Symphony Orchestra Debut



<span style='color: cyan'>Output token 1:</span> Art, <span style='color: darkorange'>logprobs:</span> -0.009169078, <span style='color: magenta'>linear probability:</span> 99.09%<br><span style='color: cyan'>Output token 2:</span> Sports, <span style='color: darkorange'>logprobs:</span> -4.696669, <span style='color: magenta'>linear probability:</span> 0.91%<br>


    
    


As expected from the first two headlines, `gpt-4` is nearly 100% confident in its classifications, as the content is clearly technology and politics focused respectively. However, the third headline combines both sports and art-related themes, so we see the model is less confident in its selection.

This shows how important using `logprobs` can be, as if we are using LLMs for classification tasks we can set confidence theshholds, or output several potential output tokens if the log probability of the selected output is not sufficiently high. For instance, if we are creating a recommendation engine to tag articles, we can automatically classify headlines crossing a certain threshold, and send the less certain headlines for manual review.

## 2. Retrieval confidence scoring to reduce hallucinations

To reduce hallucinations, and the performance of our RAG-based Q&A system, we can use `logprobs` to evaluate how confident the model is in its retrieval.

Let's say we have built a retrieval system using RAG for Q&A, but are struggling with hallucinated answers to our questions. *Note:* we will use a hardcoded article for this example, but see other entries in the cookbook for tutorials on using RAG for Q&A.


key: _node_content
string_value:
{"id_": "efbbc13b-166a-4134-a8cd-f186fa265f8d", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "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": "23fdd396-df57-4291-9785-a2214250ccd4", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "c02a707a8b6aefef9238a7f14c5b94c1e33e6f1631beb6895f3314a7fccdf84a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "16f5c535-0705-4ae0-9ef2-e142659d3356", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "6d95df63f62380354498e880898348d7cfdabb4996ef221befe18534f32edb7a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5e393428-f56b-4b38-b183-7e813a36d5d2", "node_type": "1", "metadata": {}, "hash": "f101fd8fea7509babdac6c13e1b9fe2f6bfde5bcba7cd251848b13cd3ab62a09", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 9040, "end_char_idx": 14366, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Headline: Tennis Champion Showcases Hidden Talents in Symphony Orchestra Debut



<span style='color: cyan'>Output token 1:</span> Art, <span style='color: darkorange'>logprobs:</span> -0.009169078, <span style='color: magenta'>linear probability:</span> 99.09%<br><span style='color: cyan'>Output token 2:</span> Sports, <span style='color: darkorange'>logprobs:</span> -4.696669, <span style='color: magenta'>linear probability:</span> 0.91%<br>


    
    


As expected from the first two headlines, `gpt-4` is nearly 100% confident in its classifications, as the content is clearly technology and politics focused respectively. However, the third headline combines both sports and art-related themes, so we see the model is less confident in its selection.

This shows how important using `logprobs` can be, as if we are using LLMs for classification tasks we can set confidence theshholds, or output several potential output tokens if the log probability of the selected output is not sufficiently high. For instance, if we are creating a recommendation engine to tag articles, we can automatically classify headlines crossing a certain threshold, and send the less certain headlines for manual review.

## 2. Retrieval confidence scoring to reduce hallucinations

To reduce hallucinations, and the performance of our RAG-based Q&A system, we can use `logprobs` to evaluate how confident the model is in its retrieval.

Let's say we have built a retrieval system using RAG for Q&A, but are struggling with hallucinated answers to our questions. *Note:* we will use a hardcoded article for this example, but see other entries in the cookbook for tutorials on using RAG for Q&A.


```python
# Article retrieved
ada_lovelace_article = """Augusta Ada King, Countess of Lovelace (née Byron; 10 December 1815 – 27 November 1852) was an English mathematician and writer, chiefly known for her work on Charles Babbage's proposed mechanical general-purpose computer, the Analytical Engine. She was the first to recognise that the machine had applications beyond pure calculation.
Ada Byron was the only legitimate child of poet Lord Byron and reformer Lady Byron. All Lovelace's half-siblings, Lord Byron's other children, were born out of wedlock to other women. Byron separated from his wife a month after Ada was born and left England forever. He died in Greece when Ada was eight. Her mother was anxious about her upbringing and promoted Ada's interest in mathematics and logic in an effort to prevent her from developing her father's perceived insanity. Despite this, Ada remained interested in him, naming her two sons Byron and Gordon. Upon her death, she was buried next to him at her request. Although often ill in her childhood, Ada pursued her studies assiduously. She married William King in 1835. King was made Earl of Lovelace in 1838, Ada thereby becoming Countess of Lovelace.
Her educational and social exploits brought her into contact with scientists such as Andrew Crosse, Charles Babbage, Sir David Brewster, Charles Wheatstone, Michael Faraday, and the author Charles Dickens, contacts which she used to further her education. Ada described her approach as "poetical science" and herself as an "Analyst (& Metaphysician)".
When she was eighteen, her mathematical talents led her to a long working relationship and friendship with fellow British mathematician Charles Babbage, who is known as "the father of computers". She was in particular interested in Babbage's work on the Analytical Engine. Lovelace first met him in June 1833, through their mutual friend, and her private tutor, Mary Somerville.
Between 1842 and 1843, Ada translated an article by the military engineer Luigi Menabrea (later Prime Minister of Italy) about the Analytical Engine, supplementing it with an elaborate set of seven notes, simply called "Notes".
Lovelace's notes are important in the early history of computers, especially since the seventh one contained what many consider to be the first computer program—that is, an algorithm designed to be carried out by a machine. Other historians reject this perspective and point out that Babbage's personal notes from the years 1836/1837 contain the first programs for the engine. She also developed a vision of the capability of computers to go beyond mere calculating or number-crunching, while many others, including Babbage himself, focused only on those capabilities. Her mindset of "poetical science" led her to ask questions about the Analytical Engine (as shown in her notes) examining how individuals and society relate to technology as a collaborative tool.
"""

# Questions that can be easily answered given the article
easy_questions = [
    "What nationality was Ada Lovelace?",
    "What was an important finding from Lovelace's seventh note?",
]

# Questions that are not fully covered in the article
medium_questions = [
    "Did Lovelace collaborate with Charles Dickens",
    "What concepts did Lovelace build with Charles Babbage",
]
```

Now, what we can do is ask the model to respond to the question, but then also evaluate its response. Specifically, we will ask the model to output a boolean `has_sufficient_context_for_answer`. We can then evaluate the `logprobs` to see just how confident the model is that its answer was contained in the provided context


key: _node_content
string_value:
{"id_": "5e393428-f56b-4b38-b183-7e813a36d5d2", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "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": "23fdd396-df57-4291-9785-a2214250ccd4", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "c02a707a8b6aefef9238a7f14c5b94c1e33e6f1631beb6895f3314a7fccdf84a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "efbbc13b-166a-4134-a8cd-f186fa265f8d", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "a117e6401d2215ca8a36c33ac92d053db51cdb91dac8277077c49bae1a29e691", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1a2a2ac5-0008-4257-a860-361144c28b39", "node_type": "1", "metadata": {}, "hash": "d962395f75158624b821cd60a0b7c486fb99c8cdef821cd601b0307e73353bc9", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 14369, "end_char_idx": 16505, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
PROMPT = """You retrieved this article: {article}. The question is: {question}.
Before even answering the question, consider whether you have sufficient information in the article to answer the question fully.
Your output should JUST be the boolean true or false, of if you have sufficient information in the article to answer the question.
Respond with just one word, the boolean true or false. You must output the word 'True', or the word 'False', nothing else.
"""

```


```python
html_output = ""
html_output += "Questions clearly answered in article"

for question in easy_questions:
    API_RESPONSE = get_completion(
        [
            {
                "role": "user",
                "content": PROMPT.format(
                    article=ada_lovelace_article, question=question
                ),
            }
        ],
        model="gpt-4",
        logprobs=True,
    )
    html_output += f'<p style="color:green">Question: {question}</p>'
    for logprob in API_RESPONSE.choices[0].logprobs.content:
        html_output += f'<p style="color:cyan">has_sufficient_context_for_answer: {logprob.token}, <span style="color:darkorange">logprobs: {logprob.logprob}, <span style="color:magenta">linear probability: {np.round(np.exp(logprob.logprob)*100,2)}%</span></p>'

html_output += "Questions only partially covered in the article"

for question in medium_questions:
    API_RESPONSE = get_completion(
        [
            {
                "role": "user",
                "content": PROMPT.format(
                    article=ada_lovelace_article, question=question
                ),
            }
        ],
        model="gpt-4",
        logprobs=True,
        top_logprobs=3,
    )
    html_output += f'<p style="color:green">Question: {question}</p>'
    for logprob in API_RESPONSE.choices[0].logprobs.content:
        html_output += f'<p style="color:cyan">has_sufficient_context_for_answer: {logprob.token}, <span style="color:darkorange">logprobs: {logprob.logprob}, <span style="color:magenta">linear probability: {np.round(np.exp(logprob.logprob)*100,2)}%</span></p>'

display(HTML(html_output))
```


key: _node_content
string_value:
{"id_": "1a2a2ac5-0008-4257-a860-361144c28b39", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "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": "23fdd396-df57-4291-9785-a2214250ccd4", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "c02a707a8b6aefef9238a7f14c5b94c1e33e6f1631beb6895f3314a7fccdf84a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5e393428-f56b-4b38-b183-7e813a36d5d2", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "1186385120a371938a4d4afc3a002fa1c21bff607ec73336fddbd1158c9af334", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "680fdd2b-1cf7-4f25-89f3-7b27dd7cc9eb", "node_type": "1", "metadata": {}, "hash": "3b35b3c7ba36a28a7aee8e8375d4a560db7cf7c8935f4cc170895302eef33040", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 14854, "end_char_idx": 17663, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
html_output = ""
html_output += "Questions clearly answered in article"

for question in easy_questions:
    API_RESPONSE = get_completion(
        [
            {
                "role": "user",
                "content": PROMPT.format(
                    article=ada_lovelace_article, question=question
                ),
            }
        ],
        model="gpt-4",
        logprobs=True,
    )
    html_output += f'<p style="color:green">Question: {question}</p>'
    for logprob in API_RESPONSE.choices[0].logprobs.content:
        html_output += f'<p style="color:cyan">has_sufficient_context_for_answer: {logprob.token}, <span style="color:darkorange">logprobs: {logprob.logprob}, <span style="color:magenta">linear probability: {np.round(np.exp(logprob.logprob)*100,2)}%</span></p>'

html_output += "Questions only partially covered in the article"

for question in medium_questions:
    API_RESPONSE = get_completion(
        [
            {
                "role": "user",
                "content": PROMPT.format(
                    article=ada_lovelace_article, question=question
                ),
            }
        ],
        model="gpt-4",
        logprobs=True,
        top_logprobs=3,
    )
    html_output += f'<p style="color:green">Question: {question}</p>'
    for logprob in API_RESPONSE.choices[0].logprobs.content:
        html_output += f'<p style="color:cyan">has_sufficient_context_for_answer: {logprob.token}, <span style="color:darkorange">logprobs: {logprob.logprob}, <span style="color:magenta">linear probability: {np.round(np.exp(logprob.logprob)*100,2)}%</span></p>'

display(HTML(html_output))
```


Questions clearly answered in article<p style="color:green">Question: What nationality was Ada Lovelace?</p><p style="color:cyan">has_sufficient_context_for_answer: True, <span style="color:darkorange">logprobs: -3.1281633e-07, <span style="color:magenta">linear probability: 100.0%</span></p><p style="color:green">Question: What was an important finding from Lovelace's seventh note?</p><p style="color:cyan">has_sufficient_context_for_answer: True, <span style="color:darkorange">logprobs: -7.89631e-07, <span style="color:magenta">linear probability: 100.0%</span></p>Questions only partially covered in the article<p style="color:green">Question: Did Lovelace collaborate with Charles Dickens</p><p style="color:cyan">has_sufficient_context_for_answer: True, <span style="color:darkorange">logprobs: -0.06993677, <span style="color:magenta">linear probability: 93.25%</span></p><p style="color:green">Question: What concepts did Lovelace build with Charles Babbage</p><p style="color:cyan">has_sufficient_context_for_answer: False, <span style="color:darkorange">logprobs: -0.61807257, <span style="color:magenta">linear probability: 53.9%</span></p>


key: _node_content
string_value:
{"id_": "680fdd2b-1cf7-4f25-89f3-7b27dd7cc9eb", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "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": "23fdd396-df57-4291-9785-a2214250ccd4", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "c02a707a8b6aefef9238a7f14c5b94c1e33e6f1631beb6895f3314a7fccdf84a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1a2a2ac5-0008-4257-a860-361144c28b39", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "5a0ea4f6bf0d839c2b9e94a95de8b44d9c2a302eab02c59fa95c280641b6de72", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4c6291e7-e846-4627-8c6d-791cf03214bb", "node_type": "1", "metadata": {}, "hash": "17eb89701ff59b70af19a91a422f91e6a599cd5b8339b4e30e002ac0769d8acb", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 16508, "end_char_idx": 19483, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Questions clearly answered in article<p style="color:green">Question: What nationality was Ada Lovelace?</p><p style="color:cyan">has_sufficient_context_for_answer: True, <span style="color:darkorange">logprobs: -3.1281633e-07, <span style="color:magenta">linear probability: 100.0%</span></p><p style="color:green">Question: What was an important finding from Lovelace's seventh note?</p><p style="color:cyan">has_sufficient_context_for_answer: True, <span style="color:darkorange">logprobs: -7.89631e-07, <span style="color:magenta">linear probability: 100.0%</span></p>Questions only partially covered in the article<p style="color:green">Question: Did Lovelace collaborate with Charles Dickens</p><p style="color:cyan">has_sufficient_context_for_answer: True, <span style="color:darkorange">logprobs: -0.06993677, <span style="color:magenta">linear probability: 93.25%</span></p><p style="color:green">Question: What concepts did Lovelace build with Charles Babbage</p><p style="color:cyan">has_sufficient_context_for_answer: False, <span style="color:darkorange">logprobs: -0.61807257, <span style="color:magenta">linear probability: 53.9%</span></p>


For the first two questions, our model asserts with (near) 100% confidence that the article has sufficient context to answer the posed questions.<br><br>
On the other hand, for the more tricky questions which are less clearly answered in the article, the model is less confident that it has sufficient context. This is a great guardrail to help ensure our retrieved content is sufficient.<br><br>
This self-evaluation can help reduce hallucinations, as you can restrict answers or re-prompt the user when your `sufficient_context_for_answer` log probability is below a certain threshold. Methods like this have been shown to significantly reduce RAG for Q&A hallucinations and errors ([Example](https://jfan001.medium.com/how-we-cut-the-rate-of-gpt-hallucinations-from-20-to-less-than-2-f3bfcc10e4ec)) 


```python

```

## 3. Autocomplete

Another use case for `logprobs` are autocomplete systems. Without creating the entire autocomplete system end-to-end, let's demonstrate how `logprobs` could help us decide how to suggest words as a user is typing.

First, let's come up with a sample sentence: `"My least favorite TV show is Breaking Bad."` Let's say we want it to dynamically recommend the next word or token as we are typing the sentence, but *only* if the model is quite sure of what the next word will be. To demonstrate this, let's break up the sentence into sequential components.


```python
sentence_list = [
    "My",
    "My least",
    "My least favorite",
    "My least favorite TV",
    "My least favorite TV show",
    "My least favorite TV show is",
    "My least favorite TV show is Breaking Bad",
]
```

Now, we can ask `gpt-3.5-turbo` to act as an autocomplete engine with whatever context the model is given. We can enable `logprobs` and can see how confident the model is in its prediction.


key: _node_content
string_value:
{"id_": "4c6291e7-e846-4627-8c6d-791cf03214bb", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "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": "23fdd396-df57-4291-9785-a2214250ccd4", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "c02a707a8b6aefef9238a7f14c5b94c1e33e6f1631beb6895f3314a7fccdf84a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "680fdd2b-1cf7-4f25-89f3-7b27dd7cc9eb", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "dbcaaa8024f3eb44c3eee0d1eb35cf04dce50acb4d2d86cf4c09e5ac41bdb528", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c3180e69-e249-4d47-a753-316b486a0c8b", "node_type": "1", "metadata": {}, "hash": "3b2aced285b3fb80afce474dc95c633dae1c447e3bc2e38fbedf07ed4fd7eb88", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 18471, "end_char_idx": 21345, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python

```

## 3. Autocomplete

Another use case for `logprobs` are autocomplete systems. Without creating the entire autocomplete system end-to-end, let's demonstrate how `logprobs` could help us decide how to suggest words as a user is typing.

First, let's come up with a sample sentence: `"My least favorite TV show is Breaking Bad."` Let's say we want it to dynamically recommend the next word or token as we are typing the sentence, but *only* if the model is quite sure of what the next word will be. To demonstrate this, let's break up the sentence into sequential components.


```python
sentence_list = [
    "My",
    "My least",
    "My least favorite",
    "My least favorite TV",
    "My least favorite TV show",
    "My least favorite TV show is",
    "My least favorite TV show is Breaking Bad",
]
```

Now, we can ask `gpt-3.5-turbo` to act as an autocomplete engine with whatever context the model is given. We can enable `logprobs` and can see how confident the model is in its prediction.


```python
high_prob_completions = {}
low_prob_completions = {}
html_output = ""

for sentence in sentence_list:
    PROMPT = """Complete this sentence. You are acting as auto-complete. Simply complete the sentence to the best of your ability, make sure it is just ONE sentence: {sentence}"""
    API_RESPONSE = get_completion(
        [{"role": "user", "content": PROMPT.format(sentence=sentence)}],
        model="gpt-3.5-turbo",
        logprobs=True,
        top_logprobs=3,
    )
    html_output += f'<p>Sentence: {sentence}</p>'
    first_token = True
    for token in API_RESPONSE.choices[0].logprobs.content[0].top_logprobs:
        html_output += f'<p style="color:cyan">Predicted next token: {token.token}, <span style="color:darkorange">logprobs: {token.logprob}, <span style="color:magenta">linear probability: {np.round(np.exp(token.logprob)*100,2)}%</span></p>'
        if first_token:
            if np.exp(token.logprob) > 0.95:
                high_prob_completions[sentence] = token.token
            if np.exp(token.logprob) < 0.60:
                low_prob_completions[sentence] = token.token
        first_token = False
    html_output += "<br>"

display(HTML(html_output))
```


<p>Sentence: My</p><p style="color:cyan">Predicted next token: favorite, <span style="color:darkorange">logprobs: -0.18245785, <span style="color:magenta">linear probability: 83.32%</span></p><p style="color:cyan">Predicted next token: dog, <span style="color:darkorange">logprobs: -2.397172, <span style="color:magenta">linear probability: 9.1%</span></p><p style="color:cyan">Predicted next token: ap, <span style="color:darkorange">logprobs: -3.8732424, <span style="color:magenta">linear probability: 2.08%</span></p><br><p>Sentence: My least</p><p style="color:cyan">Predicted next token: favorite, <span style="color:darkorange">logprobs: -0.0146376295,


key: _node_content
string_value:
{"id_": "c3180e69-e249-4d47-a753-316b486a0c8b", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "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": "23fdd396-df57-4291-9785-a2214250ccd4", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "c02a707a8b6aefef9238a7f14c5b94c1e33e6f1631beb6895f3314a7fccdf84a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4c6291e7-e846-4627-8c6d-791cf03214bb", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "5b66fdd251b948e73777d1ba0ba2b6e543e3dd6f96ccd7dfb6bb52b545917527", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a38c762e-8fb4-403c-b5cc-6467adbef2f8", "node_type": "1", "metadata": {}, "hash": "489c28551420e75cb21109bd85577eebad9f785bf39d9f743e6c49aa2853e28c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 20686, "end_char_idx": 23091, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
<p>Sentence: My</p><p style="color:cyan">Predicted next token: favorite, <span style="color:darkorange">logprobs: -0.18245785, <span style="color:magenta">linear probability: 83.32%</span></p><p style="color:cyan">Predicted next token: dog, <span style="color:darkorange">logprobs: -2.397172, <span style="color:magenta">linear probability: 9.1%</span></p><p style="color:cyan">Predicted next token: ap, <span style="color:darkorange">logprobs: -3.8732424, <span style="color:magenta">linear probability: 2.08%</span></p><br><p>Sentence: My least</p><p style="color:cyan">Predicted next token: favorite, <span style="color:darkorange">logprobs: -0.0146376295, <span style="color:magenta">linear probability: 98.55%</span></p><p style="color:cyan">Predicted next token: My, <span style="color:darkorange">logprobs: -4.2417912, <span style="color:magenta">linear probability: 1.44%</span></p><p style="color:cyan">Predicted next token:  favorite, <span style="color:darkorange">logprobs: -9.748788, <span style="color:magenta">linear probability: 0.01%</span></p><br><p>Sentence: My least favorite</p><p style="color:cyan">Predicted next token: food, <span style="color:darkorange">logprobs: -0.9481721, <span style="color:magenta">linear probability: 38.74%</span></p><p style="color:cyan">Predicted next token: My, <span style="color:darkorange">logprobs: -1.3447137, <span style="color:magenta">linear probability: 26.06%</span></p><p style="color:cyan">Predicted next token: color, <span style="color:darkorange">logprobs: -1.3887696, <span style="color:magenta">linear probability: 24.94%</span></p><br><p>Sentence: My least favorite TV</p><p style="color:cyan">Predicted next token: show, <span style="color:darkorange">logprobs: -0.0007898556, <span style="color:magenta">linear probability: 99.92%</span></p><p style="color:cyan">Predicted next token: My, <span style="color:darkorange">logprobs: -7.711523, <span style="color:magenta">linear probability: 0.04%</span></p><p style="color:cyan">Predicted next token: series, <span style="color:darkorange">logprobs: -9.348547, <span style="color:magenta">linear probability: 0.01%</span></p><br><p>Sentence: My least favorite TV show</p><p style="color:cyan">Predicted next token: is, <span style="color:darkorange">logprobs: -0.2851253, <span style="color:magenta">linear probability: 75.19%</span></p><p style="color:cyan">Predicted next token: of,


key: _node_content
string_value:
{"id_": "a38c762e-8fb4-403c-b5cc-6467adbef2f8", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "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": "23fdd396-df57-4291-9785-a2214250ccd4", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "c02a707a8b6aefef9238a7f14c5b94c1e33e6f1631beb6895f3314a7fccdf84a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c3180e69-e249-4d47-a753-316b486a0c8b", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "57647f88f9d2ef1a980d5406934901788f1678bcdc0f6645d095e6ff19da42f3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f0e833b3-2ebd-4f47-b348-5f42c95ec6e2", "node_type": "1", "metadata": {}, "hash": "18c3728606e296f31e9ba51726c3a99a654a83599580f7e023a8b8911119c86a", "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:
9481721, <span style="color:magenta">linear probability: 38.74%</span></p><p style="color:cyan">Predicted next token: My, <span style="color:darkorange">logprobs: -1.3447137, <span style="color:magenta">linear probability: 26.06%</span></p><p style="color:cyan">Predicted next token: color, <span style="color:darkorange">logprobs: -1.3887696, <span style="color:magenta">linear probability: 24.94%</span></p><br><p>Sentence: My least favorite TV</p><p style="color:cyan">Predicted next token: show, <span style="color:darkorange">logprobs: -0.0007898556, <span style="color:magenta">linear probability: 99.92%</span></p><p style="color:cyan">Predicted next token: My, <span style="color:darkorange">logprobs: -7.711523, <span style="color:magenta">linear probability: 0.04%</span></p><p style="color:cyan">Predicted next token: series, <span style="color:darkorange">logprobs: -9.348547, <span style="color:magenta">linear probability: 0.01%</span></p><br><p>Sentence: My least favorite TV show</p><p style="color:cyan">Predicted next token: is, <span style="color:darkorange">logprobs: -0.2851253, <span style="color:magenta">linear probability: 75.19%</span></p><p style="color:cyan">Predicted next token: of, <span style="color:darkorange">logprobs: -1.55335, <span style="color:magenta">linear probability: 21.15%</span></p><p style="color:cyan">Predicted next token: My, <span style="color:darkorange">logprobs: -3.4928775, <span style="color:magenta">linear probability: 3.04%</span></p><br><p>Sentence: My least favorite TV show is</p><p style="color:cyan">Predicted next token: "My, <span style="color:darkorange">logprobs: -0.69349754, <span style="color:magenta">linear probability: 49.98%</span></p><p style="color:cyan">Predicted next token: "The, <span style="color:darkorange">logprobs: -1.2899293, <span style="color:magenta">linear probability: 27.53%</span></p><p style="color:cyan">Predicted next token: My, <span style="color:darkorange">logprobs: -2.4170141, <span style="color:magenta">linear probability: 8.92%</span></p><br><p>Sentence: My least favorite TV show is Breaking Bad</p><p style="color:cyan">Predicted next token: because, <span style="color:darkorange">logprobs: -0.17786823, <span style="color:magenta">linear probability: 83.71%</span></p><p style="color:cyan">Predicted next token: , <span style="color:darkorange">logprobs: -2.3946173,


key: _node_content
string_value:
{"id_": "f0e833b3-2ebd-4f47-b348-5f42c95ec6e2", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "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": "23fdd396-df57-4291-9785-a2214250ccd4", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "c02a707a8b6aefef9238a7f14c5b94c1e33e6f1631beb6895f3314a7fccdf84a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a38c762e-8fb4-403c-b5cc-6467adbef2f8", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "60ef356505dfaade0c2458fe298f37865d4c0799e8f823ae6d9b3b02963edeb5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e169c57b-58ff-4bbd-bdf4-255e5303da11", "node_type": "1", "metadata": {}, "hash": "83a39db323f2cd5410308436c5705c10bb39796273d4c59647b3164ecd485bdd", "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:
19%</span></p><p style="color:cyan">Predicted next token: of, <span style="color:darkorange">logprobs: -1.55335, <span style="color:magenta">linear probability: 21.15%</span></p><p style="color:cyan">Predicted next token: My, <span style="color:darkorange">logprobs: -3.4928775, <span style="color:magenta">linear probability: 3.04%</span></p><br><p>Sentence: My least favorite TV show is</p><p style="color:cyan">Predicted next token: "My, <span style="color:darkorange">logprobs: -0.69349754, <span style="color:magenta">linear probability: 49.98%</span></p><p style="color:cyan">Predicted next token: "The, <span style="color:darkorange">logprobs: -1.2899293, <span style="color:magenta">linear probability: 27.53%</span></p><p style="color:cyan">Predicted next token: My, <span style="color:darkorange">logprobs: -2.4170141, <span style="color:magenta">linear probability: 8.92%</span></p><br><p>Sentence: My least favorite TV show is Breaking Bad</p><p style="color:cyan">Predicted next token: because, <span style="color:darkorange">logprobs: -0.17786823, <span style="color:magenta">linear probability: 83.71%</span></p><p style="color:cyan">Predicted next token: , <span style="color:darkorange">logprobs: -2.3946173, <span style="color:magenta">linear probability: 9.12%</span></p><p style="color:cyan">Predicted next token: . <span style="color:darkorange">logprobs: -3.1861975, <span style="color:magenta">linear probability: 4.13%</span></p><br>


Let's look at the high confidence autocompletions:


```python
high_prob_completions

```




    {'My least': 'favorite', 'My least favorite TV': 'show'}



These look reasonable! We can feel confident in those suggestions. It's pretty likely you want to write 'show' after writing 'My least favorite TV'! Now let's look at the autocompletion suggestions the model was less confident about:


```python
low_prob_completions

```




    {'My least favorite': 'food', 'My least favorite TV show is': '"My'}



These are logical as well. It's pretty unclear what the user is going to say with just the prefix 'my least favorite', and it's really anyone's guess what the author's favorite TV show is. <br><br>
So, using `gpt-3.5-turbo`, we can create the root of a dynamic autocompletion engine with `logprobs`!

## 4. Highlighter and bytes parameter

Let's quickly touch on creating a simple token highlighter with `logprobs`, and using the bytes parameter. First, we can create a function that counts and highlights each token. While this doesn't use the log probabilities, it uses the built in tokenization that comes with enabling `logprobs`.


key: _node_content
string_value:
{"id_": "e169c57b-58ff-4bbd-bdf4-255e5303da11", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "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": "23fdd396-df57-4291-9785-a2214250ccd4", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "c02a707a8b6aefef9238a7f14c5b94c1e33e6f1631beb6895f3314a7fccdf84a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f0e833b3-2ebd-4f47-b348-5f42c95ec6e2", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "f944955137bfe42d8ae7ff087d173c851f47d31fa0235033f072c53a22f1f103", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7a993ae3-0f79-4841-82ed-55d53f84f2d5", "node_type": "1", "metadata": {}, "hash": "e85ee81c864e968eed4cd8227df8ea814e333dbab864ee74d5403b5476ddb5a0", "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:
71%</span></p><p style="color:cyan">Predicted next token: , <span style="color:darkorange">logprobs: -2.3946173, <span style="color:magenta">linear probability: 9.12%</span></p><p style="color:cyan">Predicted next token: . <span style="color:darkorange">logprobs: -3.1861975, <span style="color:magenta">linear probability: 4.13%</span></p><br>


Let's look at the high confidence autocompletions:


```python
high_prob_completions

```




    {'My least': 'favorite', 'My least favorite TV': 'show'}



These look reasonable! We can feel confident in those suggestions. It's pretty likely you want to write 'show' after writing 'My least favorite TV'! Now let's look at the autocompletion suggestions the model was less confident about:


```python
low_prob_completions

```




    {'My least favorite': 'food', 'My least favorite TV show is': '"My'}



These are logical as well. It's pretty unclear what the user is going to say with just the prefix 'my least favorite', and it's really anyone's guess what the author's favorite TV show is. <br><br>
So, using `gpt-3.5-turbo`, we can create the root of a dynamic autocompletion engine with `logprobs`!

## 4. Highlighter and bytes parameter

Let's quickly touch on creating a simple token highlighter with `logprobs`, and using the bytes parameter. First, we can create a function that counts and highlights each token. While this doesn't use the log probabilities, it uses the built in tokenization that comes with enabling `logprobs`.


```python
PROMPT = """What's the longest word in the English language?"""

API_RESPONSE = get_completion(
    [{"role": "user", "content": PROMPT}], model="gpt-4", logprobs=True, top_logprobs=5
)


def highlight_text(api_response):
    colors = [
        "#FF00FF",  # Magenta
        "#008000",  # Green
        "#FF8C00",  # Dark Orange
        "#FF0000",  # Red
        "#0000FF",  # Blue
    ]
    tokens = api_response.choices[0].logprobs.content

    color_idx = 0  # Initialize color index
    html_output = ""  # Initialize HTML output
    for t in tokens:
        token_str = bytes(t.bytes).decode("utf-8")  # Decode bytes to string

        # Add colored token to HTML output
        html_output += f"<span style='color: {colors[color_idx]}'>{token_str}</span>"

        # Move to the next color
        color_idx = (color_idx + 1) % len(colors)
    display(HTML(html_output))  # Display HTML output
    print(f"Total number of tokens: {len(tokens)}")
```


```python
highlight_text(API_RESPONSE)

```


key: _node_content
string_value:
{"id_": "7a993ae3-0f79-4841-82ed-55d53f84f2d5", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "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": "23fdd396-df57-4291-9785-a2214250ccd4", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "c02a707a8b6aefef9238a7f14c5b94c1e33e6f1631beb6895f3314a7fccdf84a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e169c57b-58ff-4bbd-bdf4-255e5303da11", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "04bdf9d7bb39b69ed3cde414ad3f4c4873fd74e51765dc0b5f61494f623d7ace", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "95bdd3e0-b577-43f5-9c9e-d82eeac336aa", "node_type": "1", "metadata": {}, "hash": "a73e9e2da3d3a42a0e17676455ef58d16351d24e1891060c7e7557ecdb02b602", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 25639, "end_char_idx": 28690, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
PROMPT = """What's the longest word in the English language?"""

API_RESPONSE = get_completion(
    [{"role": "user", "content": PROMPT}], model="gpt-4", logprobs=True, top_logprobs=5
)


def highlight_text(api_response):
    colors = [
        "#FF00FF",  # Magenta
        "#008000",  # Green
        "#FF8C00",  # Dark Orange
        "#FF0000",  # Red
        "#0000FF",  # Blue
    ]
    tokens = api_response.choices[0].logprobs.content

    color_idx = 0  # Initialize color index
    html_output = ""  # Initialize HTML output
    for t in tokens:
        token_str = bytes(t.bytes).decode("utf-8")  # Decode bytes to string

        # Add colored token to HTML output
        html_output += f"<span style='color: {colors[color_idx]}'>{token_str}</span>"

        # Move to the next color
        color_idx = (color_idx + 1) % len(colors)
    display(HTML(html_output))  # Display HTML output
    print(f"Total number of tokens: {len(tokens)}")
```


```python
highlight_text(API_RESPONSE)

```


<span style='color: #FF00FF'>The</span><span style='color: #008000'> longest</span><span style='color: #FF8C00'> word</span><span style='color: #FF0000'> in</span><span style='color: #0000FF'> the</span><span style='color: #FF00FF'> English</span><span style='color: #008000'> language</span><span style='color: #FF8C00'>,</span><span style='color: #FF0000'> according</span><span style='color: #0000FF'> to</span><span style='color: #FF00FF'> the</span><span style='color: #008000'> Guinness</span><span style='color: #FF8C00'> World</span><span style='color: #FF0000'> Records</span><span style='color: #0000FF'>,</span><span style='color: #FF00FF'> is</span><span style='color: #008000'> '</span><span style='color: #FF8C00'>p</span><span style='color: #FF0000'>ne</span><span style='color: #0000FF'>um</span><span style='color: #FF00FF'>on</span><span style='color: #008000'>oul</span><span style='color: #FF8C00'>tram</span><span style='color: #FF0000'>icro</span><span style='color: #0000FF'>sc</span><span style='color: #FF00FF'>op</span><span style='color: #008000'>ics</span><span style='color: #FF8C00'>il</span><span style='color: #FF0000'>ic</span><span style='color: #0000FF'>ov</span><span style='color: #FF00FF'>ol</span><span style='color: #008000'>cano</span><span style='color: #FF8C00'>con</span><span style='color: #FF0000'>iosis</span><span style='color: #0000FF'>'.</span><span style='color: #FF00FF'> It</span><span style='color: #008000'> is</span><span style='color: #FF8C00'> a</span><span style='color: #FF0000'> type</span><span style='color: #0000FF'> of</span><span style='color: #FF00FF'> lung</span><span style='color: #008000'> disease</span><span style='color: #FF8C00'> caused</span><span style='color: #FF0000'> by</span><span style='color: #0000FF'> inh</span><span style='color: #FF00FF'>aling</span><span style='color: #008000'> ash</span><span style='color: #FF8C00'> and</span><span style='color: #FF0000'> sand</span><span style='color: #0000FF'> dust</span><span style='color: #FF00FF'>.</span>


key: _node_content
string_value:
{"id_": "95bdd3e0-b577-43f5-9c9e-d82eeac336aa", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "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": "23fdd396-df57-4291-9785-a2214250ccd4", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "c02a707a8b6aefef9238a7f14c5b94c1e33e6f1631beb6895f3314a7fccdf84a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7a993ae3-0f79-4841-82ed-55d53f84f2d5", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "1b3b8857428716334f6c9258337b967bd163be47af10562f33544c556d87d17f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "0254c6ff-81c9-420a-937d-fe30da4a30d7", "node_type": "1", "metadata": {}, "hash": "d8916c94644d830c3cca220bf53190ac5f59d86eeb7ae9a84cea7c1fc6232e06", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 28697, "end_char_idx": 30663, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Total number of tokens: 51


Next, let's reconstruct a sentence using the bytes parameter. With `logprobs` enabled, we are given both each token and the ASCII (decimal utf-8) values of the token string. These ASCII values can be helpful when handling tokens of or containing emojis or special characters.


```python
PROMPT = """Output the blue heart emoji and its name."""
API_RESPONSE = get_completion(
    [{"role": "user", "content": PROMPT}], model="gpt-4", logprobs=True
)

aggregated_bytes = []
joint_logprob = 0.0

# Iterate over tokens, aggregate bytes and calculate joint logprob
for token in API_RESPONSE.choices[0].logprobs.content:
    print("Token:", token.token)
    print("Log prob:", token.logprob)
    print("Linear prob:", np.round(exp(token.logprob) * 100, 2), "%")
    print("Bytes:", token.bytes, "\n")
    aggregated_bytes += token.bytes
    joint_logprob += token.logprob

# Decode the aggregated bytes to text
aggregated_text = bytes(aggregated_bytes).decode("utf-8")

# Assert that the decoded text is the same as the message content
assert API_RESPONSE.choices[0].message.content == aggregated_text

# Print the results
print("Bytes array:", aggregated_bytes)
print(f"Decoded bytes: {aggregated_text}")
print("Joint prob:", np.round(exp(joint_logprob) * 100, 2), "%")
```

    Token: \xf0\x9f\x92
    Log prob: -0.0003056686
    Linear prob: 99.97 %
    Bytes: [240, 159, 146] 
    
    Token: \x99
    Log prob: 0.0
    Linear prob: 100.0 %
    Bytes: [153] 
    
    Token:  -
    Log prob: -0.0096905725
    Linear prob: 99.04 %
    Bytes: [32, 45] 
    
    Token:  Blue
    Log prob: -0.00042042506
    Linear prob: 99.96 %
    Bytes: [32, 66, 108, 117, 101] 
    
    Token:  Heart
    Log prob: -7.302705e-05
    Linear prob: 99.99 %
    Bytes: [32, 72, 101, 97, 114, 116] 
    
    Bytes array: [240, 159, 146, 153, 32, 45, 32, 66, 108, 117, 101, 32, 72, 101, 97, 114, 116]
    Decoded bytes: 💙 - Blue Heart
    Joint prob: 98.96 %


key: _node_content
string_value:
{"id_": "0254c6ff-81c9-420a-937d-fe30da4a30d7", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "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": "23fdd396-df57-4291-9785-a2214250ccd4", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "c02a707a8b6aefef9238a7f14c5b94c1e33e6f1631beb6895f3314a7fccdf84a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "95bdd3e0-b577-43f5-9c9e-d82eeac336aa", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "b216be241c06ac40758e8caa525cda1c712083ca2769e6bf469cb4629005e8ab", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "57228714-6515-42ff-be5b-ad024be68d29", "node_type": "1", "metadata": {}, "hash": "e8807722e9a48b46cc8898a7868543b8bbe73e871a9d60f5a46a9978f9f07271", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 30666, "end_char_idx": 32361, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Here, we see that while the first token was `\xf0\x9f\x92'`, we can get its ASCII value and append it to a bytes array. Then, we can easily decode this array into a full sentence, and validate with our assert statement that the decoded bytes is the same as our completion message!

Additionally, we can get the joint probability of the entire completion, which is the exponentiated product of each token's log probability. This gives us how `likely` this given completion is given the prompt. Since, our prompt is quite directive (asking for a certain emoji and its name), the joint probability of this output is high! If we ask for a random output however, we'll see a much lower joint probability. This can also be a good tactic for developers during prompt engineering. 

## 5. Calculating perplexity

When looking to assess the model's confidence in a result, it can be useful to calculate perplexity, which is a measure of the uncertainty. Perplexity can be calculated by exponentiating the negative of the average of the logprobs. Generally, a higher perplexity indicates a more uncertain result, and a lower perplexity indicates a more confident result. As such, perplexity can be used to both assess the result of an individual model run and also to compare the relative confidence of results between model runs. While a high confidence doesn't guarantee result accuracy, it can be a helpful signal that can be paired with other evaluation metrics to build a better understanding of your prompt's behavior.

For example, let's say that I want to use `gpt-3.5-turbo` to learn more about artificial intelligence. I could ask a question about recent history and a question about the future:


key: _node_content
string_value:
{"id_": "57228714-6515-42ff-be5b-ad024be68d29", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "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": "23fdd396-df57-4291-9785-a2214250ccd4", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "c02a707a8b6aefef9238a7f14c5b94c1e33e6f1631beb6895f3314a7fccdf84a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "0254c6ff-81c9-420a-937d-fe30da4a30d7", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "7b569c3dca0789522e8e29e41bc500a97524a792ef7cb44ba1c78950da2eb8d9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8461e294-57a8-4463-b159-1514ea78c877", "node_type": "1", "metadata": {}, "hash": "b67d0455b150122f6a0d07c6728044d9a289dc9d761d82dd202aa1f669cc94ff", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 30666, "end_char_idx": 35517, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Here, we see that while the first token was `\xf0\x9f\x92'`, we can get its ASCII value and append it to a bytes array. Then, we can easily decode this array into a full sentence, and validate with our assert statement that the decoded bytes is the same as our completion message!

Additionally, we can get the joint probability of the entire completion, which is the exponentiated product of each token's log probability. This gives us how `likely` this given completion is given the prompt. Since, our prompt is quite directive (asking for a certain emoji and its name), the joint probability of this output is high! If we ask for a random output however, we'll see a much lower joint probability. This can also be a good tactic for developers during prompt engineering. 

## 5. Calculating perplexity

When looking to assess the model's confidence in a result, it can be useful to calculate perplexity, which is a measure of the uncertainty. Perplexity can be calculated by exponentiating the negative of the average of the logprobs. Generally, a higher perplexity indicates a more uncertain result, and a lower perplexity indicates a more confident result. As such, perplexity can be used to both assess the result of an individual model run and also to compare the relative confidence of results between model runs. While a high confidence doesn't guarantee result accuracy, it can be a helpful signal that can be paired with other evaluation metrics to build a better understanding of your prompt's behavior.

For example, let's say that I want to use `gpt-3.5-turbo` to learn more about artificial intelligence. I could ask a question about recent history and a question about the future:


```python
prompts = [
    "In a short sentence, has artifical intelligence grown in the last decade?",
    "In a short sentence, what are your thoughts on the future of artificial intelligence?",
]

for prompt in prompts:
    API_RESPONSE = get_completion(
        [{"role": "user", "content": prompt}],
        model="gpt-3.5-turbo",
        logprobs=True,
    )

    logprobs = [token.logprob for token in API_RESPONSE.choices[0].logprobs.content]
    response_text = API_RESPONSE.choices[0].message.content
    response_text_tokens = [token.token for token in API_RESPONSE.choices[0].logprobs.content]
    max_starter_length = max(len(s) for s in ["Prompt:", "Response:", "Tokens:", "Logprobs:", "Perplexity:"])
    max_token_length = max(len(s) for s in response_text_tokens)
    

    formatted_response_tokens = [s.rjust(max_token_length) for s in response_text_tokens]
    formatted_lps = [f"{lp:.2f}".rjust(max_token_length) for lp in logprobs]

    perplexity_score = np.exp(-np.mean(logprobs))
    print("Prompt:".ljust(max_starter_length), prompt)
    print("Response:".ljust(max_starter_length), response_text, "\n")
    print("Tokens:".ljust(max_starter_length), " ".join(formatted_response_tokens))
    print("Logprobs:".ljust(max_starter_length), " ".join(formatted_lps))
    print("Perplexity:".ljust(max_starter_length), perplexity_score, "\n")
```

    Prompt:     In a short sentence, has artifical intelligence grown in the last decade?
    Response:   Yes, artificial intelligence has grown significantly in the last decade. 
    
    Tokens:                Yes              ,     artificial   intelligence            has          grown  significantly             in            the           last         decade              .
    Logprobs:            -0.00          -0.00          -0.00          -0.00          -0.00          -0.53          -0.11          -0.00          -0.00          -0.01          -0.00          -0.00
    Perplexity: 1.0564125277713383 
    
    Prompt:     In a short sentence, what are your thoughts on the future of artificial intelligence?
    Response:   The future of artificial intelligence holds great potential for transforming industries and improving efficiency, but also raises ethical and societal concerns that must be carefully addressed. 
    
    Tokens:               The        future            of    artificial  intelligence         holds         great     potential           for  transforming    industries           and     improving    efficiency             ,           but          also        raises       ethical           and      societal      concerns          that          must            be     carefully     addressed             .
    Logprobs:           -0.19         -0.03         -0.00         -0.00         -0.00         -0.30         -0.51         -0.24         -0.03         -1.45         -0.23         -0.03         -0.22         -0.83         -0.48         -0.01         -0.38         -0.07         -0.47         -0.63         -0.18         -0.26         -0.01         -0.14         -0.00         -0.59         -0.55         -0.00
    Perplexity: 1.3220795252314004


key: _node_content
string_value:
{"id_": "8461e294-57a8-4463-b159-1514ea78c877", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "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": "23fdd396-df57-4291-9785-a2214250ccd4", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "c02a707a8b6aefef9238a7f14c5b94c1e33e6f1631beb6895f3314a7fccdf84a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "57228714-6515-42ff-be5b-ad024be68d29", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Using_logprobs.ipynb", "title": "Using logprobs for classification and Q&A evaluation", "tokens": 9243, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "2c20e49f8334c03d1f938d169a6048e489fd7932aef02ffa4a7c32073a2804b5", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 35526, "end_char_idx": 36498, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
In this example, `gpt-3.5-turbo` returned a lower perplexity score for a more deterministic question about recent history, and a higher perplexity score for a more speculative assessment about the near future. Again, while these differences don't guarantee accuracy, they help point the way for our interpretation of the model's results and our future use of them.

## 6. Conclusion

Nice! We were able to use the `logprobs` parameter to build a more robust classifier, evaluate our retrieval for Q&A system, and encode and decode each 'byte' of our tokens! `logprobs` adds useful information and signal to our completions output, and we are excited to see how developers incorporate it to improve applications.

## 7. Possible extensions

There are many other use cases for `logprobs` that are not covered in this cookbook. We can use `logprobs` for:
  - Moderation
  - Keyword selection
  - Improve prompts and interpretability of outputs
  - Token healing
  - and more!


key: _node_content
string_value:
{"id_": "0f3fc9aa-62d9-4772-a22f-b6ad198772d0", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "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": "db6ae619-b33c-4db0-bb24-9433261dcfbc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "230396899f7488cfa57ab447ee2a55fb5918d89b159c2f37bfc35c893a6139c4", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "07e50ab7-f84e-40c1-ad65-cf94708bff8a", "node_type": "1", "metadata": {}, "hash": "c7eeefa85011d7dd4302d92ec1c7760b942dcad18104a75b93834c92e0d27a97", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3027, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Parsing PDF documents for RAG applications

This notebook shows how to leverage GPT-4V to turn rich PDF documents such as slide decks or exports from web pages into usable content for your RAG application.

This technique can be used if you have a lot of unstructured data containing valuable information that you want to be able to retrieve as part of your RAG pipeline.

For example, you could build a Knowledge Assistant that could answer user queries about your company or product based on information contained in PDF documents. 

The example documents used in this notebook are located at [data/example_pdfs](data/example_pdfs). They are related to OpenAI's APIs and various techniques that can be used as part of LLM projects.

## Data preparation

In this section, we will process our input data to prepare it for retrieval.

We will do this in 2 ways:

1. Extracting text with pdfminer
2. Converting the PDF pages to images to analyze them with GPT-4V

You can skip the 1st method if you want to only use the content inferred from the image analysis.

### Setup

We need to install a few libraries to convert the PDF to images and extract the text (optional).

**Note: You need to install `poppler` on your machine for the `pdf2image` library to work. You can follow the instructions to install it [here](https://pypi.org/project/pdf2image/).**


```python
%pip install pdf2image
%pip install pdfminer
%pip install openai
%pip install scikit-learn
%pip install rich
%pip install tqdm
%pip install concurrent
```


```python
# Imports
from pdf2image import convert_from_path
from pdf2image.exceptions import (
    PDFInfoNotInstalledError,
    PDFPageCountError,
    PDFSyntaxError
)
from pdfminer.high_level import extract_text
import base64
from io import BytesIO
import os
import concurrent
from tqdm import tqdm
from openai import OpenAI
import re
import pandas as pd 
from sklearn.metrics.pairwise import cosine_similarity
import json
import numpy as np
from rich import print
from ast import literal_eval
```

### File processing


```python
def convert_doc_to_images(path):
    images = convert_from_path(path)
    return images

def extract_text_from_doc(path):
    text = extract_text(path)
    page_text = []
    return text
```

#### Testing with an example


```python
file_path = "data/example_pdfs/fine-tuning-deck.pdf"

images = convert_doc_to_images(file_path)
```


```python
text = extract_text_from_doc(file_path)
```


```python
for img in images:
    display(img)
```


    
![png](output_10_0.png)
    



    
![png](output_10_1.png)
    



    
![png](output_10_2.png)
    



    
![png](output_10_3.png)
    



    
![png](output_10_4.png)
    



    
![png](output_10_5.png)
    



    
![png](output_10_6.png)
    


### Image analysis with GPT-4V

After converting a PDF file to multiple images, we'll use GPT-4V to analyze the content based on the images.


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


key: _node_content
string_value:
{"id_": "07e50ab7-f84e-40c1-ad65-cf94708bff8a", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "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": "db6ae619-b33c-4db0-bb24-9433261dcfbc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "230396899f7488cfa57ab447ee2a55fb5918d89b159c2f37bfc35c893a6139c4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "0f3fc9aa-62d9-4772-a22f-b6ad198772d0", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "58b9d153ef818b24fc0f133c908ada2ac0b8011fe3cbd9f247fb083bd475e166", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "18284b9f-5000-40e8-b48e-b9ba786fc203", "node_type": "1", "metadata": {}, "hash": "5cfb408248c7d959a7df1682ee28cf59fa622df94eb22bbd1300654c288a9cc5", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1525, "end_char_idx": 3373, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
# Imports
from pdf2image import convert_from_path
from pdf2image.exceptions import (
    PDFInfoNotInstalledError,
    PDFPageCountError,
    PDFSyntaxError
)
from pdfminer.high_level import extract_text
import base64
from io import BytesIO
import os
import concurrent
from tqdm import tqdm
from openai import OpenAI
import re
import pandas as pd 
from sklearn.metrics.pairwise import cosine_similarity
import json
import numpy as np
from rich import print
from ast import literal_eval
```

### File processing


```python
def convert_doc_to_images(path):
    images = convert_from_path(path)
    return images

def extract_text_from_doc(path):
    text = extract_text(path)
    page_text = []
    return text
```

#### Testing with an example


```python
file_path = "data/example_pdfs/fine-tuning-deck.pdf"

images = convert_doc_to_images(file_path)
```


```python
text = extract_text_from_doc(file_path)
```


```python
for img in images:
    display(img)
```


    
![png](output_10_0.png)
    



    
![png](output_10_1.png)
    



    
![png](output_10_2.png)
    



    
![png](output_10_3.png)
    



    
![png](output_10_4.png)
    



    
![png](output_10_5.png)
    



    
![png](output_10_6.png)
    


### Image analysis with GPT-4V

After converting a PDF file to multiple images, we'll use GPT-4V to analyze the content based on the images.


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


```python
# Converting images to base64 encoded images in a data URI format to use with the ChatCompletions API
def get_img_uri(img):
    buffer = BytesIO()
    img.save(buffer, format="jpeg")
    base64_image = base64.b64encode(buffer.getvalue()).decode("utf-8")
    data_uri = f"data:image/jpeg;base64,{base64_image}"
    return data_uri
```


key: _node_content
string_value:
{"id_": "18284b9f-5000-40e8-b48e-b9ba786fc203", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "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": "db6ae619-b33c-4db0-bb24-9433261dcfbc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "230396899f7488cfa57ab447ee2a55fb5918d89b159c2f37bfc35c893a6139c4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "07e50ab7-f84e-40c1-ad65-cf94708bff8a", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "b4dd5d9e1a3812d5cbff546d92e968245c6a1b23c966e8e1c3beee2a710a54e0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "de3b5ed9-a032-464a-9887-da8bf437b5a8", "node_type": "1", "metadata": {}, "hash": "6e6b018820e2f2be80becda6bbd93273637f2392d6ae23d9e464d881f68079dc", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2048, "end_char_idx": 5377, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
def convert_doc_to_images(path):
    images = convert_from_path(path)
    return images

def extract_text_from_doc(path):
    text = extract_text(path)
    page_text = []
    return text
```

#### Testing with an example


```python
file_path = "data/example_pdfs/fine-tuning-deck.pdf"

images = convert_doc_to_images(file_path)
```


```python
text = extract_text_from_doc(file_path)
```


```python
for img in images:
    display(img)
```


    
![png](output_10_0.png)
    



    
![png](output_10_1.png)
    



    
![png](output_10_2.png)
    



    
![png](output_10_3.png)
    



    
![png](output_10_4.png)
    



    
![png](output_10_5.png)
    



    
![png](output_10_6.png)
    


### Image analysis with GPT-4V

After converting a PDF file to multiple images, we'll use GPT-4V to analyze the content based on the images.


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


```python
# Converting images to base64 encoded images in a data URI format to use with the ChatCompletions API
def get_img_uri(img):
    buffer = BytesIO()
    img.save(buffer, format="jpeg")
    base64_image = base64.b64encode(buffer.getvalue()).decode("utf-8")
    data_uri = f"data:image/jpeg;base64,{base64_image}"
    return data_uri
```


```python
system_prompt = '''
You will be provided with an image of a pdf page or a slide. Your goal is to talk about the content that you see, in technical terms, as if you were delivering a presentation.

If there are diagrams, describe the diagrams and explain their meaning.
For example: if there is a diagram describing a process flow, say something like "the process flow starts with X then we have Y and Z..."

If there are tables, describe logically the content in the tables
For example: if there is a table listing items and prices, say something like "the prices are the following: A for X, B for Y..."

DO NOT include terms referring to the content format
DO NOT mention the content type - DO focus on the content itself
For example: if there is a diagram/chart and text on the image, talk about both without mentioning that one is a chart and the other is text.
Simply describe what you see in the diagram and what you understand from the text.

You should keep it concise, but keep in mind your audience cannot see the image so be exhaustive in describing the content.

Exclude elements that are not relevant to the content:
DO NOT mention page numbers or the position of the elements on the image.

------

If there is an identifiable title, identify the title to give the output in the following format:

{TITLE}

{Content description}

If there is no clear title, simply return the content description.

'''

def analyze_image(img_url):
    response = client.chat.completions.create(
    model="gpt-4-vision-preview",
    temperature=0,
    messages=[
        {
            "role": "system",
            "content": system_prompt
        },
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": img_url,
                },
            ],
        }
    ],
        max_tokens=300,
        top_p=0.1
    )

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

#### Testing with an example


key: _node_content
string_value:
{"id_": "de3b5ed9-a032-464a-9887-da8bf437b5a8", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "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": "db6ae619-b33c-4db0-bb24-9433261dcfbc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "230396899f7488cfa57ab447ee2a55fb5918d89b159c2f37bfc35c893a6139c4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "18284b9f-5000-40e8-b48e-b9ba786fc203", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "473b1a2473887476837e9de1d137ce02227d14b77a274afe3c78fb5055d4fab7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d6f40997-c1ec-458c-876d-a5707313b705", "node_type": "1", "metadata": {}, "hash": "6380550b509f50b7025d0eefcd638a3a1644c3d0eb7dc1393df8bab16d380beb", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5380, "end_char_idx": 8217, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
img = images[2]
data_uri = get_img_uri(img)
```


```python
res = analyze_image(data_uri)
print(res)
```

    What is Fine-tuning
    
    Fine-tuning a model consists of training the model to follow a set of given input/output examples. This will teach the model to behave in a certain way when confronted with a similar input in the future.
    
    We recommend using 50-100 examples even if the minimum is 10.
    
    The process involves starting with a public model, using training data to train the model, and resulting in a fine-tuned model.


#### Processing all documents


```python
files_path = "data/example_pdfs"

all_items = os.listdir(files_path)
files = [item for item in all_items if os.path.isfile(os.path.join(files_path, item))]
```


```python
def analyze_doc_image(img):
    img_uri = get_img_uri(img)
    data = analyze_image(img_uri)
    return data
```

We will list all files in the example folder and process them by 
1. Extracting the text
2. Converting the docs to images
3. Analyzing pages with GPT-4V

Note: This takes about ~2 mins to run. Feel free to skip and load directly the result file (see below).


```python
docs = []

for f in files:
    
    path = f"{files_path}/{f}"
    doc = {
        "filename": f
    }
    text = extract_text_from_doc(path)
    doc['text'] = text
    imgs = convert_doc_to_images(path)
    pages_description = []
    
    print(f"Analyzing pages for doc {f}")
    
    # Concurrent execution
    with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:
        
        # Removing 1st slide as it's usually just an intro
        futures = [
            executor.submit(analyze_doc_image, img)
            for img in imgs[1:]
        ]
        
        with tqdm(total=len(imgs)-1) as pbar:
            for _ in concurrent.futures.as_completed(futures):
                pbar.update(1)
        
        for f in futures:
            res = f.result()
            pages_description.append(res)
        
    doc['pages_description'] = pages_description
    docs.append(doc)
```

    Analyzing pages for doc rag-deck.pdf


    100%|██████████████████████████████████████████████████████████████████| 19/19 [00:32<00:00,  1.72s/it]


    Analyzing pages for doc models-page.pdf


    100%|████████████████████████████████████████████████████████████████████| 9/9 [00:25<00:00,  2.80s/it]


    Analyzing pages for doc evals-decks.pdf


    100%|██████████████████████████████████████████████████████████████████| 12/12 [00:29<00:00,  2.44s/it]


    Analyzing pages for doc fine-tuning-deck.pdf


    100%|████████████████████████████████████████████████████████████████████| 6/6 [00:19<00:00,  3.32s/it]



```python
# Saving result to file for later
json_path = "data/parsed_pdf_docs.json"

with open(json_path, 'w') as f:
    json.dump(docs, f)
```


key: _node_content
string_value:
{"id_": "d6f40997-c1ec-458c-876d-a5707313b705", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "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": "db6ae619-b33c-4db0-bb24-9433261dcfbc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "230396899f7488cfa57ab447ee2a55fb5918d89b159c2f37bfc35c893a6139c4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "de3b5ed9-a032-464a-9887-da8bf437b5a8", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "8e7ac649a9a5608e0f321f14bc1f8e042bbe3ce1b76b472dde75093b72817f45", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d0c538a9-f082-4bc6-8e53-373d2526abf8", "node_type": "1", "metadata": {}, "hash": "1448e142e45b970a5e8d1c4f77bb7f13d5dafa5f036151a89a93f56e412e0bd6", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 7494, "end_char_idx": 10469, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
100%|██████████████████████████████████████████████████████████████████| 19/19 [00:32<00:00,  1.72s/it]


    Analyzing pages for doc models-page.pdf


    100%|████████████████████████████████████████████████████████████████████| 9/9 [00:25<00:00,  2.80s/it]


    Analyzing pages for doc evals-decks.pdf


    100%|██████████████████████████████████████████████████████████████████| 12/12 [00:29<00:00,  2.44s/it]


    Analyzing pages for doc fine-tuning-deck.pdf


    100%|████████████████████████████████████████████████████████████████████| 6/6 [00:19<00:00,  3.32s/it]



```python
# Saving result to file for later
json_path = "data/parsed_pdf_docs.json"

with open(json_path, 'w') as f:
    json.dump(docs, f)
```


```python
# Optional: load content from the saved file
with open(json_path, 'r') as f:
    docs = json.load(f)
```

### Embedding content
Before embedding the content, we will chunk it logically by page.
For real-world scenarios, you could explore more advanced ways to chunk the content:
- Cutting it into smaller pieces
- Adding data - such as the slide title, deck title and/or the doc description - at the beginning of each piece of content. That way, each independent chunk can be in context

For the sake of brevity, we will use a very simple chunking strategy and rely on separators to split the text by page.


```python
# Chunking content by page and merging together slides text & description if applicable
content = []
for doc in docs:
    # Removing first slide as well
    text = doc['text'].split('\f')[1:]
    description = doc['pages_description']
    description_indexes = []
    for i in range(len(text)):
        slide_content = text[i] + '\n'
        # Trying to find matching slide description
        slide_title = text[i].split('\n')[0]
        for j in range(len(description)):
            description_title = description[j].split('\n')[0]
            if slide_title.lower() == description_title.lower():
                slide_content += description[j].replace(description_title, '')
                # Keeping track of the descriptions added
                description_indexes.append(j)
        # Adding the slide content + matching slide description to the content pieces
        content.append(slide_content) 
    # Adding the slides descriptions that weren't used
    for j in range(len(description)):
        if j not in description_indexes:
            content.append(description[j])
```


```python
for c in content:
    print(c)
    print("\n\n-------------------------------\n\n")
```


```python
# Cleaning up content
# Removing trailing spaces, additional line breaks, page numbers and references to the content being a slide
clean_content = []
for c in content:
    text = c.replace(' \n', '').replace('\n\n', '\n').replace('\n\n\n', '\n').strip()
    text = re.sub(r"(?<=\n)\d{1,2}", "", text)
    text = re.sub(r"\b(?:the|this)\s*slide\s*\w+\b", "", text, flags=re.IGNORECASE)
    clean_content.append(text)
```


key: _node_content
string_value:
{"id_": "d0c538a9-f082-4bc6-8e53-373d2526abf8", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "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": "db6ae619-b33c-4db0-bb24-9433261dcfbc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "230396899f7488cfa57ab447ee2a55fb5918d89b159c2f37bfc35c893a6139c4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d6f40997-c1ec-458c-876d-a5707313b705", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "358690d8f7d224e91251d798a35ded144593d54419b5566712de9bcd42622ab0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "98aa3582-52a6-4a1d-b2c7-44ebf3c0114c", "node_type": "1", "metadata": {}, "hash": "5d213883a60134bfc6550b9a373135697b822225044e763240c4c6300b1f466b", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 8839, "end_char_idx": 11748, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
# Chunking content by page and merging together slides text & description if applicable
content = []
for doc in docs:
    # Removing first slide as well
    text = doc['text'].split('\f')[1:]
    description = doc['pages_description']
    description_indexes = []
    for i in range(len(text)):
        slide_content = text[i] + '\n'
        # Trying to find matching slide description
        slide_title = text[i].split('\n')[0]
        for j in range(len(description)):
            description_title = description[j].split('\n')[0]
            if slide_title.lower() == description_title.lower():
                slide_content += description[j].replace(description_title, '')
                # Keeping track of the descriptions added
                description_indexes.append(j)
        # Adding the slide content + matching slide description to the content pieces
        content.append(slide_content) 
    # Adding the slides descriptions that weren't used
    for j in range(len(description)):
        if j not in description_indexes:
            content.append(description[j])
```


```python
for c in content:
    print(c)
    print("\n\n-------------------------------\n\n")
```


```python
# Cleaning up content
# Removing trailing spaces, additional line breaks, page numbers and references to the content being a slide
clean_content = []
for c in content:
    text = c.replace(' \n', '').replace('\n\n', '\n').replace('\n\n\n', '\n').strip()
    text = re.sub(r"(?<=\n)\d{1,2}", "", text)
    text = re.sub(r"\b(?:the|this)\s*slide\s*\w+\b", "", text, flags=re.IGNORECASE)
    clean_content.append(text)
```


```python
for c in clean_content:
    print(c)
    print("\n\n-------------------------------\n\n")
```


```python
# Creating the embeddings
# We'll save to a csv file here for testing purposes but this is where you should load content in your vectorDB.
df = pd.DataFrame(clean_content, columns=['content'])
print(df.shape)
df.head()
```

    (64, 1)





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

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

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>content</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Overview\nRetrieval-Augmented Generationenhanc...</td>
    </tr>
    <tr>
      <th>1</th>
      <td>What is RAG\nRetrieve information to Augment t...</td>
    </tr>
    <tr>
      <th>2</th>
      <td>When to use RAG\nGood for  ✅\nNot good for  ❌\...</td>
    </tr>
    <tr>
      <th>3</th>
      <td>Technical patterns\nData preparation\nInput pr...</td>
    </tr>
    <tr>
      <th>4</th>
      <td>Technical patterns\nData preparation\nchunk do...</td>
    </tr>
  </tbody>
</table>
</div>


key: _node_content
string_value:
{"id_": "98aa3582-52a6-4a1d-b2c7-44ebf3c0114c", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "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": "db6ae619-b33c-4db0-bb24-9433261dcfbc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "230396899f7488cfa57ab447ee2a55fb5918d89b159c2f37bfc35c893a6139c4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d0c538a9-f082-4bc6-8e53-373d2526abf8", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "5aae45d14d3e259780367e4f288784718138492b8697eacd6245d329477de51a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "51d78d66-914d-44fb-9130-148f8faacc9d", "node_type": "1", "metadata": {}, "hash": "3186014fa5e279eac0d2e31db300695c60b087423678dec13e4c0e752fc067a1", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 10472, "end_char_idx": 12106, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
for c in clean_content:
    print(c)
    print("\n\n-------------------------------\n\n")
```


```python
# Creating the embeddings
# We'll save to a csv file here for testing purposes but this is where you should load content in your vectorDB.
df = pd.DataFrame(clean_content, columns=['content'])
print(df.shape)
df.head()
```

    (64, 1)





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

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

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>content</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Overview\nRetrieval-Augmented Generationenhanc...</td>
    </tr>
    <tr>
      <th>1</th>
      <td>What is RAG\nRetrieve information to Augment t...</td>
    </tr>
    <tr>
      <th>2</th>
      <td>When to use RAG\nGood for  ✅\nNot good for  ❌\...</td>
    </tr>
    <tr>
      <th>3</th>
      <td>Technical patterns\nData preparation\nInput pr...</td>
    </tr>
    <tr>
      <th>4</th>
      <td>Technical patterns\nData preparation\nchunk do...</td>
    </tr>
  </tbody>
</table>
</div>




```python
embeddings_model = "text-embedding-3-large"

def get_embeddings(text):
    embeddings = client.embeddings.create(
      model="text-embedding-3-small",
      input=text,
      encoding_format="float"
    )
    return embeddings.data[0].embedding
```


```python
df['embeddings'] = df['content'].apply(lambda x: get_embeddings(x))
df.head()
```


key: _node_content
string_value:
{"id_": "51d78d66-914d-44fb-9130-148f8faacc9d", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "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": "db6ae619-b33c-4db0-bb24-9433261dcfbc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "230396899f7488cfa57ab447ee2a55fb5918d89b159c2f37bfc35c893a6139c4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "98aa3582-52a6-4a1d-b2c7-44ebf3c0114c", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "41f70d70709c4e4a84ff96e9290f1b88a070a417e78346ecf9fb5405c3e823ac", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3cea155c-fb33-4f71-9379-faa2f8e5ca78", "node_type": "1", "metadata": {}, "hash": "c79f64858aa4447d9f6d3e2547146f3f3af408a469a872b10271ce5767cce71b", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 10829, "end_char_idx": 13381, "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>content</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Overview\nRetrieval-Augmented Generationenhanc...</td>
    </tr>
    <tr>
      <th>1</th>
      <td>What is RAG\nRetrieve information to Augment t...</td>
    </tr>
    <tr>
      <th>2</th>
      <td>When to use RAG\nGood for  ✅\nNot good for  ❌\...</td>
    </tr>
    <tr>
      <th>3</th>
      <td>Technical patterns\nData preparation\nInput pr...</td>
    </tr>
    <tr>
      <th>4</th>
      <td>Technical patterns\nData preparation\nchunk do...</td>
    </tr>
  </tbody>
</table>
</div>




```python
embeddings_model = "text-embedding-3-large"

def get_embeddings(text):
    embeddings = client.embeddings.create(
      model="text-embedding-3-small",
      input=text,
      encoding_format="float"
    )
    return embeddings.data[0].embedding
```


```python
df['embeddings'] = df['content'].apply(lambda x: get_embeddings(x))
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>content</th>
      <th>embeddings</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Overview\nRetrieval-Augmented Generationenhanc...</td>
      <td>[-0.014744381, 0.03017278, 0.06353764, 0.02110...</td>
    </tr>
    <tr>
      <th>1</th>
      <td>What is RAG\nRetrieve information to Augment t...</td>
      <td>[-0.024337867, 0.022921458, -0.00971687, 0.010...</td>
    </tr>
    <tr>
      <th>2</th>
      <td>When to use RAG\nGood for  ✅\nNot good for  ❌\...</td>
      <td>[-0.011084231, 0.021158217, -0.00430421, 0.017...</td>
    </tr>
    <tr>
      <th>3</th>
      <td>Technical patterns\nData preparation\nInput pr...</td>
      <td>[-0.0058343858, 0.0408407, 0.054318383, 0.0190...</td>
    </tr>
    <tr>
      <th>4</th>
      <td>Technical patterns\nData preparation\nchunk do...</td>
      <td>[-0.010359385, 0.03736894, 0.052995477, 0.0180...</td>
    </tr>
  </tbody>
</table>
</div>


key: _node_content
string_value:
{"id_": "3cea155c-fb33-4f71-9379-faa2f8e5ca78", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "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": "db6ae619-b33c-4db0-bb24-9433261dcfbc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "230396899f7488cfa57ab447ee2a55fb5918d89b159c2f37bfc35c893a6139c4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "51d78d66-914d-44fb-9130-148f8faacc9d", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "cf5423fa8a210d315ee8331b35318190ff4c4becff773311fdb1a7609d73e145", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6814258f-4a59-497a-8867-79ff02bf2b9c", "node_type": "1", "metadata": {}, "hash": "070101153f482981e2cf37960ce5d0056e0a0a1fb78c08ef2408d4c653157cee", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 13386, "end_char_idx": 16614, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
# Saving locally for later
data_path = "data/parsed_pdf_docs_with_embeddings.csv"
df.to_csv(data_path, index=False)
```


```python
# Optional: load data from saved file
df = pd.read_csv(data_path)
df["embeddings"] = df.embeddings.apply(literal_eval).apply(np.array)
```

## Retrieval-augmented generation

The last step of the process is to generate outputs in response to input queries, after retrieving content as context to reply.


```python
system_prompt = '''
    You will be provided with an input prompt and content as context that can be used to reply to the prompt.
    
    You will do 2 things:
    
    1. First, you will internally assess whether the content provided is relevant to reply to the input prompt. 
    
    2a. If that is the case, answer directly using this content. If the content is relevant, use elements found in the content to craft a reply to the input prompt.

    2b. If the content is not relevant, use your own knowledge to reply or say that you don't know how to respond if your knowledge is not sufficient to answer.
    
    Stay concise with your answer, replying specifically to the input prompt without mentioning additional information provided in the context content.
'''

model="gpt-4-turbo-preview"

def search_content(df, input_text, top_k):
    embedded_value = get_embeddings(input_text)
    df["similarity"] = df.embeddings.apply(lambda x: cosine_similarity(np.array(x).reshape(1,-1), np.array(embedded_value).reshape(1, -1)))
    res = df.sort_values('similarity', ascending=False).head(top_k)
    return res

def get_similarity(row):
    similarity_score = row['similarity']
    if isinstance(similarity_score, np.ndarray):
        similarity_score = similarity_score[0][0]
    return similarity_score

def generate_output(input_prompt, similar_content, threshold = 0.5):
    
    content = similar_content.iloc[0]['content']
    
    # Adding more matching content if the similarity is above threshold
    if len(similar_content) > 1:
        for i, row in similar_content.iterrows():
            similarity_score = get_similarity(row)
            if similarity_score > threshold:
                content += f"\n\n{row['content']}"
            
    prompt = f"INPUT PROMPT:\n{input_prompt}\n-------\nCONTENT:\n{content}"
    
    completion = client.chat.completions.create(
        model=model,
        temperature=0.5,
        messages=[
            {
                "role": "system",
                "content": system_prompt
            },
            {
                "role": "user",
                "content": prompt
            }
        ]
    )

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


```python
# Example user queries related to the content
example_inputs = [
    'What are the main models you offer?',
    'Do you have a speech recognition model?',
    'Which embedding model should I use for non-English use cases?',
    'Can I introduce new knowledge in my LLM app using RAG?',
    'How many examples do I need to fine-tune a model?',
    'Which metric can I use to evaluate a summarization task?',
    'Give me a detailed example for an evaluation process where we are looking for a clear answer to compare to a ground truth.',
]
```


key: _node_content
string_value:
{"id_": "6814258f-4a59-497a-8867-79ff02bf2b9c", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "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": "db6ae619-b33c-4db0-bb24-9433261dcfbc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "230396899f7488cfa57ab447ee2a55fb5918d89b159c2f37bfc35c893a6139c4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3cea155c-fb33-4f71-9379-faa2f8e5ca78", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "7334e2646cb54e251febab08fd51b0d145dc8ef31f44c436491d0ce8c6c96cf5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "cd04f04a-f724-4474-8de6-5de187e44fb5", "node_type": "1", "metadata": {}, "hash": "803323320ba445ff42ded6ac759b8016c07198eac81676108b44bb86bc8b0943", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 16062, "end_char_idx": 18235, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
# Example user queries related to the content
example_inputs = [
    'What are the main models you offer?',
    'Do you have a speech recognition model?',
    'Which embedding model should I use for non-English use cases?',
    'Can I introduce new knowledge in my LLM app using RAG?',
    'How many examples do I need to fine-tune a model?',
    'Which metric can I use to evaluate a summarization task?',
    'Give me a detailed example for an evaluation process where we are looking for a clear answer to compare to a ground truth.',
]
```


```python
# Running the RAG pipeline on each example
for ex in example_inputs:
    print(f"[deep_pink4][bold]QUERY:[/bold] {ex}[/deep_pink4]\n\n")
    matching_content = search_content(df, ex, 3)
    print(f"[grey37][b]Matching content:[/b][/grey37]\n")
    for i, match in matching_content.iterrows():
        print(f"[grey37][i]Similarity: {get_similarity(match):.2f}[/i][/grey37]")
        print(f"[grey37]{match['content'][:100]}{'...' if len(match['content']) > 100 else ''}[/[grey37]]\n\n")
    reply = generate_output(ex, matching_content)
    print(f"[turquoise4][b]REPLY:[/b][/turquoise4]\n\n[spring_green4]{reply}[/spring_green4]\n\n--------------\n\n")
```


<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #af005f; text-decoration-color: #af005f; font-weight: bold">QUERY:</span><span style="color: #af005f; text-decoration-color: #af005f"> What are the main models you offer?</span>


</pre>




<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold">Matching content:</span>

</pre>




<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-style: italic">Similarity: </span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold; font-style: italic">0.43</span>
</pre>


key: _node_content
string_value:
{"id_": "cd04f04a-f724-4474-8de6-5de187e44fb5", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "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": "db6ae619-b33c-4db0-bb24-9433261dcfbc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "230396899f7488cfa57ab447ee2a55fb5918d89b159c2f37bfc35c893a6139c4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6814258f-4a59-497a-8867-79ff02bf2b9c", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "8c0b31ade2f64573be7d2ebbb395821b1c0f48a28e11c5b2108f2aa43469f99f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "128c9d04-b34d-4456-9e18-3e06eb327305", "node_type": "1", "metadata": {}, "hash": "d9048fdececaa50e7bf31eb1efab831215f7983da756c843045a7f33112205b0", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 17287, "end_char_idx": 19292, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #af005f; text-decoration-color: #af005f; font-weight: bold">QUERY:</span><span style="color: #af005f; text-decoration-color: #af005f"> What are the main models you offer?</span>


</pre>




<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold">Matching content:</span>

</pre>




<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-style: italic">Similarity: </span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold; font-style: italic">0.43</span>
</pre>




<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #5f5f5f; text-decoration-color: #5f5f5f">Models - OpenAI API</span>
<span style="color: #5f5f5f; text-decoration-color: #5f5f5f">The content lists various API endpoints and their corresponding latest models:</span>
<span style="color: #5f5f5f; text-decoration-color: #5f5f5f">-...</span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold">[</span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f">/</span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold">]</span>


</pre>




<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-style: italic">Similarity: </span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold; font-style: italic">0.39</span>
</pre>


key: _node_content
string_value:
{"id_": "128c9d04-b34d-4456-9e18-3e06eb327305", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "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": "db6ae619-b33c-4db0-bb24-9433261dcfbc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "230396899f7488cfa57ab447ee2a55fb5918d89b159c2f37bfc35c893a6139c4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "cd04f04a-f724-4474-8de6-5de187e44fb5", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "5dd8c53d7729624cd7c3dfcc0dc25bb1cb016bccf280e54f61e84852c92217e0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a5768f44-0abc-4c63-952e-1682a438f90b", "node_type": "1", "metadata": {}, "hash": "a8d416c1cafe807a705cd70c37f48121dadf80f225fe176f8da6d68cfa99b4a2", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 18240, "end_char_idx": 20467, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #5f5f5f; text-decoration-color: #5f5f5f">Models - OpenAI API</span>
<span style="color: #5f5f5f; text-decoration-color: #5f5f5f">The content lists various API endpoints and their corresponding latest models:</span>
<span style="color: #5f5f5f; text-decoration-color: #5f5f5f">-...</span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold">[</span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f">/</span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold">]</span>


</pre>




<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-style: italic">Similarity: </span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold; font-style: italic">0.39</span>
</pre>




<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold">26</span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f">/</span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold">02</span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f">/</span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold">2024</span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f">, </span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold">17:58</span>
<span style="color: #5f5f5f; text-decoration-color: #5f5f5f">Models - OpenAI API</span>
<span style="color: #5f5f5f; text-decoration-color: #5f5f5f">The Moderation models are designed to check whether content co...</span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold">[</span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f">/</span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold">]</span>


key: _node_content
string_value:
{"id_": "a5768f44-0abc-4c63-952e-1682a438f90b", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "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": "db6ae619-b33c-4db0-bb24-9433261dcfbc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "230396899f7488cfa57ab447ee2a55fb5918d89b159c2f37bfc35c893a6139c4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "128c9d04-b34d-4456-9e18-3e06eb327305", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "9f807c92eee8c783616d32432a350d42b2e3e5688cbe6df5a8f4bc783f3380df", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a9d81add-ec77-4661-abd5-ff106e462175", "node_type": "1", "metadata": {}, "hash": "ac905c9f39fad5867e873d1d1eb6a5f494a4c4c98f3eaa525cc3954e01529303", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 20470, "end_char_idx": 22866, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
</pre>




<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-style: italic">Similarity: </span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold; font-style: italic">0.39</span>
</pre>




<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #5f5f5f; text-decoration-color: #5f5f5f">The content describes various models provided by OpenAI, focusing on moderation models and GPT base ...</span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold">[</span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f">/</span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold">]</span>


</pre>




<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #008787; text-decoration-color: #008787; font-weight: bold">REPLY:</span>

<span style="color: #00875f; text-decoration-color: #00875f">The main models we offer include:</span>
<span style="color: #00875f; text-decoration-color: #00875f">- For completions: gpt-</span><span style="color: #00875f; text-decoration-color: #00875f; font-weight: bold">3.5</span><span style="color: #00875f; text-decoration-color: #00875f">-turbo-instruct, babbage-</span><span style="color: #00875f; text-decoration-color: #00875f; font-weight: bold">002</span><span style="color: #00875f; text-decoration-color: #00875f">, and davinci-</span><span style="color: #00875f; text-decoration-color: #00875f; font-weight: bold">002</span><span style="color: #00875f; text-decoration-color: #00875f">.</span>
<span style="color: #00875f; text-decoration-color: #00875f">- For embeddings: text-embedding-</span><span style="color: #00875f; text-decoration-color: #00875f; font-weight: bold">3</span><span style="color: #00875f; text-decoration-color: #00875f">-small, text-embedding-</span><span style="color: #00875f; text-decoration-color: #00875f; font-weight: bold">3</span><span style="color: #00875f; text-decoration-color: #00875f">-large, and text-embedding-ada-</span><span style="color: #00875f; text-decoration-color: #00875f;


key: _node_content
string_value:
{"id_": "a9d81add-ec77-4661-abd5-ff106e462175", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "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": "db6ae619-b33c-4db0-bb24-9433261dcfbc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "230396899f7488cfa57ab447ee2a55fb5918d89b159c2f37bfc35c893a6139c4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a5768f44-0abc-4c63-952e-1682a438f90b", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "96972a3f3bfae8364f293157e7a22415d8d05b595b3c88b8148a595780820f68", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c02ccffc-786b-4b2f-b114-98cc9239fc74", "node_type": "1", "metadata": {}, "hash": "7a094f28bf2fcaa6a66a30c57cb265a28a20b4ac815915c71ac8b1f4a317b489", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 21597, "end_char_idx": 24044, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
font-weight: bold">REPLY:</span>

<span style="color: #00875f; text-decoration-color: #00875f">The main models we offer include:</span>
<span style="color: #00875f; text-decoration-color: #00875f">- For completions: gpt-</span><span style="color: #00875f; text-decoration-color: #00875f; font-weight: bold">3.5</span><span style="color: #00875f; text-decoration-color: #00875f">-turbo-instruct, babbage-</span><span style="color: #00875f; text-decoration-color: #00875f; font-weight: bold">002</span><span style="color: #00875f; text-decoration-color: #00875f">, and davinci-</span><span style="color: #00875f; text-decoration-color: #00875f; font-weight: bold">002</span><span style="color: #00875f; text-decoration-color: #00875f">.</span>
<span style="color: #00875f; text-decoration-color: #00875f">- For embeddings: text-embedding-</span><span style="color: #00875f; text-decoration-color: #00875f; font-weight: bold">3</span><span style="color: #00875f; text-decoration-color: #00875f">-small, text-embedding-</span><span style="color: #00875f; text-decoration-color: #00875f; font-weight: bold">3</span><span style="color: #00875f; text-decoration-color: #00875f">-large, and text-embedding-ada-</span><span style="color: #00875f; text-decoration-color: #00875f; font-weight: bold">002</span><span style="color: #00875f; text-decoration-color: #00875f">.</span>
<span style="color: #00875f; text-decoration-color: #00875f">- For fine-tuning jobs: gpt-</span><span style="color: #00875f; text-decoration-color: #00875f; font-weight: bold">3.5</span><span style="color: #00875f; text-decoration-color: #00875f">-turbo, babbage-</span><span style="color: #00875f; text-decoration-color: #00875f; font-weight: bold">002</span><span style="color: #00875f; text-decoration-color: #00875f">, and davinci-</span><span style="color: #00875f; text-decoration-color: #00875f; font-weight: bold">002</span><span style="color: #00875f; text-decoration-color: #00875f">.</span>
<span style="color: #00875f; text-decoration-color: #00875f">- For moderations: text-moderation-stable and text-moderation.</span>
<span style="color: #00875f; text-decoration-color: #00875f">Additionally, we have the latest models like gpt-</span><span style="color: #00875f; text-decoration-color: #00875f; font-weight: bold">3.5</span><span style="color: #00875f; text-decoration-color: #00875f">-turbo-16k and fine-tuned versions of gpt-</span><span style="color: #00875f;


key: _node_content
string_value:
{"id_": "c02ccffc-786b-4b2f-b114-98cc9239fc74", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "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": "db6ae619-b33c-4db0-bb24-9433261dcfbc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "230396899f7488cfa57ab447ee2a55fb5918d89b159c2f37bfc35c893a6139c4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a9d81add-ec77-4661-abd5-ff106e462175", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "b38daaa445f3249e38553be69062faf8a4a84eaf5b252c6765ef8956e93bd469", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3f1816d9-abcc-4257-94e4-c37ba5b2d8bd", "node_type": "1", "metadata": {}, "hash": "e5be8d308086f9a8a5de4522146e583bf1481aeaa0abd179ddca9daaef9a213c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 22835, "end_char_idx": 25163, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
text-decoration-color: #00875f; font-weight: bold">002</span><span style="color: #00875f; text-decoration-color: #00875f">.</span>
<span style="color: #00875f; text-decoration-color: #00875f">- For fine-tuning jobs: gpt-</span><span style="color: #00875f; text-decoration-color: #00875f; font-weight: bold">3.5</span><span style="color: #00875f; text-decoration-color: #00875f">-turbo, babbage-</span><span style="color: #00875f; text-decoration-color: #00875f; font-weight: bold">002</span><span style="color: #00875f; text-decoration-color: #00875f">, and davinci-</span><span style="color: #00875f; text-decoration-color: #00875f; font-weight: bold">002</span><span style="color: #00875f; text-decoration-color: #00875f">.</span>
<span style="color: #00875f; text-decoration-color: #00875f">- For moderations: text-moderation-stable and text-moderation.</span>
<span style="color: #00875f; text-decoration-color: #00875f">Additionally, we have the latest models like gpt-</span><span style="color: #00875f; text-decoration-color: #00875f; font-weight: bold">3.5</span><span style="color: #00875f; text-decoration-color: #00875f">-turbo-16k and fine-tuned versions of gpt-</span><span style="color: #00875f; text-decoration-color: #00875f; font-weight: bold">3.5</span><span style="color: #00875f; text-decoration-color: #00875f">-turbo.</span>

--------------


</pre>




<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #af005f; text-decoration-color: #af005f; font-weight: bold">QUERY:</span><span style="color: #af005f; text-decoration-color: #af005f"> Do you have a speech recognition model?</span>


</pre>




<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold">Matching content:</span>

</pre>




<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-style: italic">Similarity: </span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold; font-style: italic">0.53</span>
</pre>


key: _node_content
string_value:
{"id_": "3f1816d9-abcc-4257-94e4-c37ba5b2d8bd", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "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": "db6ae619-b33c-4db0-bb24-9433261dcfbc", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "230396899f7488cfa57ab447ee2a55fb5918d89b159c2f37bfc35c893a6139c4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c02ccffc-786b-4b2f-b114-98cc9239fc74", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Parse_PDF_docs_for_RAG.ipynb", "title": "Parsing PDF documents for RAG applications", "tokens": 17715, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "7b48f8aecf4df586c9d6a84263f022bffea000636cecd596ef95d507bd7bc724", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6f024d8c-b62d-495c-9132-f2332822c0ba", "node_type": "1", "metadata": {}, "hash": "de9f03a23d21939c8ee51742c77a36155acdc90fa6b6d8975f05fb7400d31c9c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 23877, "end_char_idx": 26084, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
font-weight: bold">3.5</span><span style="color: #00875f; text-decoration-color: #00875f">-turbo-16k and fine-tuned versions of gpt-</span><span style="color: #00875f; text-decoration-color: #00875f; font-weight: bold">3.5</span><span style="color: #00875f; text-decoration-color: #00875f">-turbo.</span>

--------------


</pre>




<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #af005f; text-decoration-color: #af005f; font-weight: bold">QUERY:</span><span style="color: #af005f; text-decoration-color: #af005f"> Do you have a speech recognition model?</span>


</pre>




<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold">Matching content:</span>

</pre>




<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-style: italic">Similarity: </span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold; font-style: italic">0.53</span>
</pre>




<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #5f5f5f; text-decoration-color: #5f5f5f">The content describes various models related to text-to-speech, speech recognition, embeddings, and ...</span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold">[</span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f">/</span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold">]</span>


</pre>




<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-style: italic">Similarity: </span><span style="color: #5f5f5f; text-decoration-color: #5f5f5f; font-weight: bold; font-style: italic">0.50</span>
</pre>


