# embedding_metadata

key: _node_content
string_value:
{"id_": "1c57a679-2f0e-4b78-9d24-0952df264da1", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "84e7d788-bc35-4697-bcd2-598aeb949f82", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "e7203445d110bcbacf51d06c8ef28bd985a8230fe676af76206449f3d5f1ccf6", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "913de36b-d722-44ce-b1c0-b110e6609aa8", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "54a2c2cd78734027c33fa9c5239bcdb1ad45e1cb8d7e38292e5b562a23e2a515", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "744b9e01-6dcc-4e0a-836f-e8997d96fd0b", "node_type": "1", "metadata": {}, "hash": "61efe661b3f18cafd128455f96308ba73a221d00e569e918893fd90d7a125caf", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2051, "end_char_idx": 3671, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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


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

```

## 2. Load and process input data


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

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

# view data
df.head()

```

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


key: _node_content
string_value:
{"id_": "744b9e01-6dcc-4e0a-836f-e8997d96fd0b", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "84e7d788-bc35-4697-bcd2-598aeb949f82", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "e7203445d110bcbacf51d06c8ef28bd985a8230fe676af76206449f3d5f1ccf6", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1c57a679-2f0e-4b78-9d24-0952df264da1", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "c60272a4947f71f163371c04bc6c9c368b5cad0fdddc73e31db390aab63c8860", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "cafee84b-90fc-46f4-81dc-d4ac25139826", "node_type": "1", "metadata": {}, "hash": "de2b487346747393ec31512bb5ae7fe22c336b63e0ea6b96bbf62ef9fed28345", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2384, "end_char_idx": 4943, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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

```

## 2. Load and process input data


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

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

# view data
df.head()

```

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





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

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

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


key: _node_content
string_value:
{"id_": "cafee84b-90fc-46f4-81dc-d4ac25139826", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "84e7d788-bc35-4697-bcd2-598aeb949f82", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "e7203445d110bcbacf51d06c8ef28bd985a8230fe676af76206449f3d5f1ccf6", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "744b9e01-6dcc-4e0a-836f-e8997d96fd0b", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "7a937fba3872b8f1361d2d57ec5890a51f92390be1e6186f99ec9716bb9983c6", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8af12ab1-e151-4baf-b549-09339da21059", "node_type": "1", "metadata": {}, "hash": "712d25e4a4a44479f4d192dac9ed45c8e5c821be93bcff44ca6debef160ff2dc", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 4947, "end_char_idx": 8002, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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

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


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

```

## 4. Generate synthetic negatives

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

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

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

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

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


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

```


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

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

```

## 5. Calculate embeddings and cosine similarities

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


key: _node_content
string_value:
{"id_": "8af12ab1-e151-4baf-b549-09339da21059", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "84e7d788-bc35-4697-bcd2-598aeb949f82", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "e7203445d110bcbacf51d06c8ef28bd985a8230fe676af76206449f3d5f1ccf6", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "cafee84b-90fc-46f4-81dc-d4ac25139826", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "1061ea08f26604e5455f16c97f2387ed62e9f48508cac24c7b5bba143c32980e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e0bd4b40-d86e-402b-ac5b-5922afdf860a", "node_type": "1", "metadata": {}, "hash": "32d10cff9e34cfe24ef59c4e238b8aa40d5f44759d2b6b2234841854f793e8b1", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 7000, "end_char_idx": 10214, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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

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

```

## 5. Calculate embeddings and cosine similarities

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


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


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


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

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

```

## 6. Plot distribution of cosine similarity

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

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

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


key: _node_content
string_value:
{"id_": "e0bd4b40-d86e-402b-ac5b-5922afdf860a", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "84e7d788-bc35-4697-bcd2-598aeb949f82", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "e7203445d110bcbacf51d06c8ef28bd985a8230fe676af76206449f3d5f1ccf6", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8af12ab1-e151-4baf-b549-09339da21059", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "5a95ffbaab6bea56c4527bad834cf2bfea5604acbb0cdb02dee731bd639669e6", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ee6faec0-a734-4777-99d7-d3a8bac71977", "node_type": "1", "metadata": {}, "hash": "2d1c48c3c078f08a4c903c1b6f58c8f32a8461e688509c6467e3dc7fb2dbae0c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 8426, "end_char_idx": 11646, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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


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

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

```

## 6. Plot distribution of cosine similarity

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

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

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


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


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

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

```



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


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


key: _node_content
string_value:
{"id_": "ee6faec0-a734-4777-99d7-d3a8bac71977", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "84e7d788-bc35-4697-bcd2-598aeb949f82", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "e7203445d110bcbacf51d06c8ef28bd985a8230fe676af76206449f3d5f1ccf6", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e0bd4b40-d86e-402b-ac5b-5922afdf860a", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "ded3f2271a88d2f58fb170d986db2abbcbfb5be5ccd78f39f4059a1c55700149", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8c59e858-0a47-445f-b1db-647d964c0897", "node_type": "1", "metadata": {}, "hash": "4ad13287483ae83e9fa045d0447069ef883826b1d2ed4a0f48bdf5081ac695b7", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 10217, "end_char_idx": 13261, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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


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

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

```



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


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


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


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

```


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


key: _node_content
string_value:
{"id_": "8c59e858-0a47-445f-b1db-647d964c0897", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "84e7d788-bc35-4697-bcd2-598aeb949f82", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "e7203445d110bcbacf51d06c8ef28bd985a8230fe676af76206449f3d5f1ccf6", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ee6faec0-a734-4777-99d7-d3a8bac71977", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "205590afc262242470c8243ab6d888f8bcfe205ca968e9c635e823f0650e6b1f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "dc44cda4-a1bf-49d1-b3d2-c0360eb1afb5", "node_type": "1", "metadata": {}, "hash": "832f50598869350d9fed1fc8b8af62bcab0ea233d6c829281dba770bdb6aca6c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 11588, "end_char_idx": 14616, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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


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


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

```


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

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

        return e1, e2, s

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

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

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


key: _node_content
string_value:
{"id_": "dc44cda4-a1bf-49d1-b3d2-c0360eb1afb5", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "84e7d788-bc35-4697-bcd2-598aeb949f82", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "e7203445d110bcbacf51d06c8ef28bd985a8230fe676af76206449f3d5f1ccf6", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8c59e858-0a47-445f-b1db-647d964c0897", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "e12968aba896d6533772f7936f1b5bae9f57c226e64d20b44fb8f3434aafd9b8", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a7f8a91c-6421-4be1-ab9f-e53c231b7b4e", "node_type": "1", "metadata": {}, "hash": "0a8bef462b8ea870f53cc28b92714b917ef002ef1baaee54e393bf4abacf9e39", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 13262, "end_char_idx": 16563, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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

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

        return e1, e2, s

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

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

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

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

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

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

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

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

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


key: _node_content
string_value:
{"id_": "a7f8a91c-6421-4be1-ab9f-e53c231b7b4e", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "84e7d788-bc35-4697-bcd2-598aeb949f82", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "e7203445d110bcbacf51d06c8ef28bd985a8230fe676af76206449f3d5f1ccf6", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "dc44cda4-a1bf-49d1-b3d2-c0360eb1afb5", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "189d3a016f33ef76b5f58f2663a76d0c97e1da10ca6a48b0e6f0838979c5e606", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7e4c3c76-1ce3-41c9-a684-fd247531c2ac", "node_type": "1", "metadata": {}, "hash": "8bc06622347a2f28ae6cf7811f5a8492f371d43392ad4d201fd646fb133b06ee", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 14780, "end_char_idx": 18126, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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

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

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

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

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

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

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

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

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

    return data

```


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

```

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


key: _node_content
string_value:
{"id_": "7e4c3c76-1ce3-41c9-a684-fd247531c2ac", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "84e7d788-bc35-4697-bcd2-598aeb949f82", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "e7203445d110bcbacf51d06c8ef28bd985a8230fe676af76206449f3d5f1ccf6", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a7f8a91c-6421-4be1-ab9f-e53c231b7b4e", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "a4cd34ff5681f1f6b15bac5cc0598a3f61f3ea98221a3f90070d7b5f0c667309", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "78431243-fc41-4403-9ace-2a1ae1822630", "node_type": "1", "metadata": {}, "hash": "7dab543ded95c0e726236dbcb003a36e0f5e5de17756fc0e02c53744090e70f2", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 16607, "end_char_idx": 18891, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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

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

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

    return data

```


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

```

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


key: _node_content
string_value:
{"id_": "78431243-fc41-4403-9ace-2a1ae1822630", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "84e7d788-bc35-4697-bcd2-598aeb949f82", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "e7203445d110bcbacf51d06c8ef28bd985a8230fe676af76206449f3d5f1ccf6", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7e4c3c76-1ce3-41c9-a684-fd247531c2ac", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "bc51577765872c1ddd007a27835ef6d66d3175ea56d0837675b2e7e3d3994dcb", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b04cd45d-d77a-419b-9c27-37dcf7a85125", "node_type": "1", "metadata": {}, "hash": "bd3302f74fb7d1d159862e481630eeee78f2c5ec454cff3f4bb78998baf6a503", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 18044, "end_char_idx": 19710, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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


key: _node_content
string_value:
{"id_": "b04cd45d-d77a-419b-9c27-37dcf7a85125", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "84e7d788-bc35-4697-bcd2-598aeb949f82", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "e7203445d110bcbacf51d06c8ef28bd985a8230fe676af76206449f3d5f1ccf6", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "78431243-fc41-4403-9ace-2a1ae1822630", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "3b0e8e63b94d353a38ada4bf8a0342a48c30b30d64db3154a5545e8ea15987b3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c139eec8-bf81-4d07-9404-561903bed49f", "node_type": "1", "metadata": {}, "hash": "e94cd5ad363918e2b3c0bcf82305c0c9a6388adb4b35742adf24c7e71aa78dc2", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 18846, "end_char_idx": 20529, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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


key: _node_content
string_value:
{"id_": "c139eec8-bf81-4d07-9404-561903bed49f", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "84e7d788-bc35-4697-bcd2-598aeb949f82", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "e7203445d110bcbacf51d06c8ef28bd985a8230fe676af76206449f3d5f1ccf6", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b04cd45d-d77a-419b-9c27-37dcf7a85125", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "5fc9d300bf8aea48ca1ecf9c0682ffd9c6c5d15e804d22373371ab1de4073ad9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "376ce533-21c7-44e9-be1c-42d37784547a", "node_type": "1", "metadata": {}, "hash": "b0eca73acf4938d0ce44a9ceec072905f7350a1103e55093a560e63841d67f7b", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 19665, "end_char_idx": 21334, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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


key: _node_content
string_value:
{"id_": "376ce533-21c7-44e9-be1c-42d37784547a", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "84e7d788-bc35-4697-bcd2-598aeb949f82", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "e7203445d110bcbacf51d06c8ef28bd985a8230fe676af76206449f3d5f1ccf6", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c139eec8-bf81-4d07-9404-561903bed49f", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "2c1adcb5f4a8d3a04309a7d68ff581d25bc8de32c3de8d1344b160815cff7bff", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9a8e4afa-9f2b-4c12-9674-56663187cc79", "node_type": "1", "metadata": {}, "hash": "669da3f0e145d80a690a7375cc3143d1f430be5d6baa03bc01d0ff08ce999ac9", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 20484, "end_char_idx": 22149, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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


key: _node_content
string_value:
{"id_": "9a8e4afa-9f2b-4c12-9674-56663187cc79", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "84e7d788-bc35-4697-bcd2-598aeb949f82", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "e7203445d110bcbacf51d06c8ef28bd985a8230fe676af76206449f3d5f1ccf6", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "376ce533-21c7-44e9-be1c-42d37784547a", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "ce854f0a2a2869424dc8e282dd186d515a2a4d5648474477542857ab72c1cca7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "116289a4-d08b-42b9-a8b4-e96ed5749446", "node_type": "1", "metadata": {}, "hash": "3b64af1bbb481e55920f1f726d1fd7d935ae3be27495763e0e69b7438cdfd79a", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 21290, "end_char_idx": 22968, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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


key: _node_content
string_value:
{"id_": "116289a4-d08b-42b9-a8b4-e96ed5749446", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "84e7d788-bc35-4697-bcd2-598aeb949f82", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "e7203445d110bcbacf51d06c8ef28bd985a8230fe676af76206449f3d5f1ccf6", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9a8e4afa-9f2b-4c12-9674-56663187cc79", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "2e439d277ff9892c12ef6f40889c292efde901a19708cbfa607c435cdd206f5b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a5283d3e-a463-4b9b-ab64-aab69edb68a5", "node_type": "1", "metadata": {}, "hash": "488abbe0d4090c75449bec40ade5f24e4e5bae1a1aa9513d76903222d1aabff3", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 22104, "end_char_idx": 23779, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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


key: _node_content
string_value:
{"id_": "a5283d3e-a463-4b9b-ab64-aab69edb68a5", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "84e7d788-bc35-4697-bcd2-598aeb949f82", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "e7203445d110bcbacf51d06c8ef28bd985a8230fe676af76206449f3d5f1ccf6", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "116289a4-d08b-42b9-a8b4-e96ed5749446", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "bc0bfa368680cfab2a2ac9f5a492f02772d24f845ffa37e3e778af68e51a9243", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ddd8d73e-bae5-424c-b2f2-630892811934", "node_type": "1", "metadata": {}, "hash": "0054eba0f3e90877392c604cdd9bb99da2f9d1c16b77379b7df145009dde73a1", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 22923, "end_char_idx": 24588, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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


key: _node_content
string_value:
{"id_": "ddd8d73e-bae5-424c-b2f2-630892811934", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "84e7d788-bc35-4697-bcd2-598aeb949f82", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "e7203445d110bcbacf51d06c8ef28bd985a8230fe676af76206449f3d5f1ccf6", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a5283d3e-a463-4b9b-ab64-aab69edb68a5", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "677aa83d3afbb74c7990b5224a4cc9805a5b797e43e2091db08d5657b7c0ba47", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7d1d5b31-0204-4c20-a14b-446bdf5946eb", "node_type": "1", "metadata": {}, "hash": "b76d3adb2c023e94972d9bddffa2071993ee481ea38b5c46814e6f89a4a6c4cd", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 23735, "end_char_idx": 25407, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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


key: _node_content
string_value:
{"id_": "7d1d5b31-0204-4c20-a14b-446bdf5946eb", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "84e7d788-bc35-4697-bcd2-598aeb949f82", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "e7203445d110bcbacf51d06c8ef28bd985a8230fe676af76206449f3d5f1ccf6", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ddd8d73e-bae5-424c-b2f2-630892811934", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "65cb0c9eb2de499a781969cb643acfc7562ed0b71620b5c2812cfdac006f64a1", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9c13ebf4-3ea9-4d40-a764-afb2b83ed714", "node_type": "1", "metadata": {}, "hash": "83b5b354a8895a2cde7b302aa1e69a9a9c7437598efeab6fb2a6d2c24fda27a2", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 24543, "end_char_idx": 26137, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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


key: _node_content
string_value:
{"id_": "9c13ebf4-3ea9-4d40-a764-afb2b83ed714", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "84e7d788-bc35-4697-bcd2-598aeb949f82", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "e7203445d110bcbacf51d06c8ef28bd985a8230fe676af76206449f3d5f1ccf6", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7d1d5b31-0204-4c20-a14b-446bdf5946eb", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "31ad949db4cf3662d9fc590018b542627b2a670ef8d2752a18e6945087364f7d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "0c1690e6-acdc-413c-9fe7-3a266bb1b352", "node_type": "1", "metadata": {}, "hash": "331a281f80f8f7f16f667e3db7575f60f3b11de9c94e1ea6e90d47dbba9446f1", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 25309, "end_char_idx": 27162, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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



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

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

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

```





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

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


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

```


key: _node_content
string_value:
{"id_": "0c1690e6-acdc-413c-9fe7-3a266bb1b352", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "84e7d788-bc35-4697-bcd2-598aeb949f82", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "e7203445d110bcbacf51d06c8ef28bd985a8230fe676af76206449f3d5f1ccf6", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9c13ebf4-3ea9-4d40-a764-afb2b83ed714", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "70af99ff9b3783cb30e046e5236723a31ea1cb696c1e3f3d68f47761746f917e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1e7ffef2-ec54-4744-bc62-c86b09c8ad92", "node_type": "1", "metadata": {}, "hash": "129840b964943852d050669f6e8682d9c804487de3d3eb61f04cfbc4ebdbd367", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 25855, "end_char_idx": 28060, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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



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

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

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

```





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

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


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

```


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

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

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

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

```



    Test accuracy: 88.8% ± 2.4%




    Test accuracy after customization: 93.6% ± 1.9%



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

```


key: _node_content
string_value:
{"id_": "1e7ffef2-ec54-4744-bc62-c86b09c8ad92", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "84e7d788-bc35-4697-bcd2-598aeb949f82", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "e7203445d110bcbacf51d06c8ef28bd985a8230fe676af76206449f3d5f1ccf6", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "0c1690e6-acdc-413c-9fe7-3a266bb1b352", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb", "title": "Customizing embeddings", "tokens": 9055, "retrieve_doc": false, "source": "openai_cookbooks"}, "hash": "ddad124d670ce24c87cf5f435ea5512a7820729b141de9ad1cd7f68e67d46cf9", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 26757, "end_char_idx": 28871, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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

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


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

```


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

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

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

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

```



    Test accuracy: 88.8% ± 2.4%




    Test accuracy after customization: 93.6% ± 1.9%



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

```




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




```python

```


key: _node_content
string_value:
{"id_": "632cce23-9ae5-4028-a2a8-6fbad1628a72", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "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": "0f8ad10f-0d8c-4e3d-8815-d40cce7a9577", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "fe1af06febe25208ec0c4afc1b80b6117753c8e698e0a38b78ab9c14c19a6c43", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c3d0bbaa-429f-4c92-bd3c-34e9690bec95", "node_type": "1", "metadata": {}, "hash": "d809f2107bb6924dc5ed3cf6f7df424e131e8cde283dc883f314017c07a4080a", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3197, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Structured Outputs for Multi-Agent Systems

In this cookbook, we will explore how to use Structured Outputs to build multi-agent systems.

Structured Outputs is a new capability that builds upon JSON mode and function calling to enforce a strict schema in a model output.

By using the new parameter `strict: true`, we are able to guarantee the response abides by a provided schema.

To demonstrate the power of this feature, we will use it to build a multi-agent system.

### Why build a Multi-Agent System?

When using function calling, if the number of functions (or tools) increases, the performance may suffer.

To mitigate this, we can logically group the tools together and have specialized "agents" that are able to solve specific tasks or sub-tasks, which will increase the overall system performance.

## Environment set up


```python
from openai import OpenAI
from IPython.display import Image
import json
import pandas as pd
import matplotlib.pyplot as plt
from io import StringIO
import numpy as np
client = OpenAI()
```


```python
MODEL = "gpt-4o-2024-08-06"
```

## Agents set up

The use case we will tackle is a data analysis task.

Let's first set up our 4-agents system:

1.   **Triaging agent:** Decides which agent(s) to call
2.   **Data pre-processing Agent:** Prepares data for analysis - for example by cleaning it up
3.   **Data Analysis Agent:** Performs analysis on the data
4.   **Data Visualization Agent:** Visualizes the output of the analysis to extract insights

We will start by defining the system prompts for each of these agents.


```python
triaging_system_prompt = """You are a Triaging Agent. Your role is to assess the user's query and route it to the relevant agents. The agents available are:
- Data Processing Agent: Cleans, transforms, and aggregates data.
- Analysis Agent: Performs statistical, correlation, and regression analysis.
- Visualization Agent: Creates bar charts, line charts, and pie charts.

Use the send_query_to_agents tool to forward the user's query to the relevant agents. Also, use the speak_to_user tool to get more information from the user if needed."""

processing_system_prompt = """You are a Data Processing Agent. Your role is to clean, transform, and aggregate data using the following tools:
- clean_data
- transform_data
- aggregate_data"""

analysis_system_prompt = """You are an Analysis Agent. Your role is to perform statistical, correlation, and regression analysis using the following tools:
- stat_analysis
- correlation_analysis
- regression_analysis"""

visualization_system_prompt = """You are a Visualization Agent. Your role is to create bar charts, line charts, and pie charts using the following tools:
- create_bar_chart
- create_line_chart
- create_pie_chart"""
```

We will then define the tools for each agent.

Apart from the triaging agent, each agent will be equipped with tools specific to their role:

#### Data pre-processing agent


1.   Clean data
2.   Transform data
3.   Aggregate data

#### Data analysis agent

1.   Statistical analysis
2.   Correlation analysis
3.   Regression Analysis

#### Data visualization agent

1.   Create bar chart
2.   Create line chart
3.   Create pie chart


key: _node_content
string_value:
{"id_": "c3d0bbaa-429f-4c92-bd3c-34e9690bec95", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "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": "0f8ad10f-0d8c-4e3d-8815-d40cce7a9577", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "fe1af06febe25208ec0c4afc1b80b6117753c8e698e0a38b78ab9c14c19a6c43", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "632cce23-9ae5-4028-a2a8-6fbad1628a72", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "bed32c377055d4d77b4b9010a16d9c86dca4cdcbdf8b291d64d380232cbd4c01", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "73780b93-1629-4eaf-8221-46311a72fcba", "node_type": "1", "metadata": {}, "hash": "3e4db69d3eec8ec03e8a4091a871d73fe71b07eb27c1396e89f088f86d24e6fd", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1573, "end_char_idx": 6648, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
triaging_system_prompt = """You are a Triaging Agent. Your role is to assess the user's query and route it to the relevant agents. The agents available are:
- Data Processing Agent: Cleans, transforms, and aggregates data.
- Analysis Agent: Performs statistical, correlation, and regression analysis.
- Visualization Agent: Creates bar charts, line charts, and pie charts.

Use the send_query_to_agents tool to forward the user's query to the relevant agents. Also, use the speak_to_user tool to get more information from the user if needed."""

processing_system_prompt = """You are a Data Processing Agent. Your role is to clean, transform, and aggregate data using the following tools:
- clean_data
- transform_data
- aggregate_data"""

analysis_system_prompt = """You are an Analysis Agent. Your role is to perform statistical, correlation, and regression analysis using the following tools:
- stat_analysis
- correlation_analysis
- regression_analysis"""

visualization_system_prompt = """You are a Visualization Agent. Your role is to create bar charts, line charts, and pie charts using the following tools:
- create_bar_chart
- create_line_chart
- create_pie_chart"""
```

We will then define the tools for each agent.

Apart from the triaging agent, each agent will be equipped with tools specific to their role:

#### Data pre-processing agent


1.   Clean data
2.   Transform data
3.   Aggregate data

#### Data analysis agent

1.   Statistical analysis
2.   Correlation analysis
3.   Regression Analysis

#### Data visualization agent

1.   Create bar chart
2.   Create line chart
3.   Create pie chart


```python
triage_tools = [
    {
        "type": "function",
        "function": {
            "name": "send_query_to_agents",
            "description": "Sends the user query to relevant agents based on their capabilities.",
            "parameters": {
                "type": "object",
                "properties": {
                    "agents": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "An array of agent names to send the query to."
                    },
                    "query": {
                        "type": "string",
                        "description": "The user query to send."
                    }
                },
                "required": ["agents", "query"]
            }
        },
        "strict": True
    }
]

preprocess_tools = [
    {
        "type": "function",
        "function": {
            "name": "clean_data",
            "description": "Cleans the provided data by removing duplicates and handling missing values.",
            "parameters": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "string",
                        "description": "The dataset to clean. Should be in a suitable format such as JSON or CSV."
                    }
                },
                "required": ["data"],
                "additionalProperties": False
            }
        },
        "strict": True
    },
    {
        "type": "function",
        "function": {
            "name": "transform_data",
            "description": "Transforms data based on specified rules.",
            "parameters": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "string",
                        "description": "The data to transform. Should be in a suitable format such as JSON or CSV."
                    },
                    "rules": {
                        "type": "string",
                        "description": "Transformation rules to apply, specified in a structured format."
                    }
                },
                "required": ["data", "rules"],
                "additionalProperties": False
            }
        },
        "strict": True

    },
    {
        "type": "function",
        "function": {
            "name": "aggregate_data",
            "description": "Aggregates data by specified columns and operations.",
            "parameters": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "string",
                        "description": "The data to aggregate. Should be in a suitable format such as JSON or CSV."
                    },
                    "group_by": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "Columns to group by."
                    },
                    "operations": {
                        "type": "string",
                        "description": "Aggregation operations to perform, specified in a structured format."
                    }
                },
                "required": ["data", "group_by", "operations"],
                "additionalProperties": False
            }
        },
        "strict": True
    }
]


key: _node_content
string_value:
{"id_": "73780b93-1629-4eaf-8221-46311a72fcba", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "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": "0f8ad10f-0d8c-4e3d-8815-d40cce7a9577", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "fe1af06febe25208ec0c4afc1b80b6117753c8e698e0a38b78ab9c14c19a6c43", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c3d0bbaa-429f-4c92-bd3c-34e9690bec95", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "a7eabf4cf9cbeded760990d8af567dff80997e89c42ca9cb12609f8a7cc5d08d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "67d360be-5c25-45d2-bd18-c7e07f1fba7a", "node_type": "1", "metadata": {}, "hash": "26e7d86c8a6c7c030fe8fcaa797039b80c8576c114959d4d6bb832f2f62f4fa5", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 6651, "end_char_idx": 10915, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
analysis_tools = [
    {
        "type": "function",
        "function": {
            "name": "stat_analysis",
            "description": "Performs statistical analysis on the given dataset.",
            "parameters": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "string",
                        "description": "The dataset to analyze. Should be in a suitable format such as JSON or CSV."
                    }
                },
                "required": ["data"],
                "additionalProperties": False
            }
        },
        "strict": True
    },
    {
        "type": "function",
        "function": {
            "name": "correlation_analysis",
            "description": "Calculates correlation coefficients between variables in the dataset.",
            "parameters": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "string",
                        "description": "The dataset to analyze. Should be in a suitable format such as JSON or CSV."
                    },
                    "variables": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "List of variables to calculate correlations for."
                    }
                },
                "required": ["data", "variables"],
                "additionalProperties": False
            }
        },
        "strict": True
    },
    {
        "type": "function",
        "function": {
            "name": "regression_analysis",
            "description": "Performs regression analysis on the dataset.",
            "parameters": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "string",
                        "description": "The dataset to analyze. Should be in a suitable format such as JSON or CSV."
                    },
                    "dependent_var": {
                        "type": "string",
                        "description": "The dependent variable for regression."
                    },
                    "independent_vars": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "List of independent variables."
                    }
                },
                "required": ["data", "dependent_var", "independent_vars"],
                "additionalProperties": False
            }
        },
        "strict": True
    }
]

visualization_tools = [
    {
        "type": "function",
        "function": {
            "name": "create_bar_chart",
            "description": "Creates a bar chart from the provided data.",
            "parameters": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "string",
                        "description": "The data for the bar chart. Should be in a suitable format such as JSON or CSV."
                    },
                    "x": {
                        "type": "string",
                        "description": "Column for the x-axis."
                    },
                    "y": {
                        "type": "string",
                        "description": "Column for the y-axis."
                    }
                },
                "required": ["data", "x", "y"],
                "additionalProperties": False
            }
        },
        "strict": True
    },
    {
        "type": "function",
        "function": {
            "name": "create_line_chart",
            "description": "Creates a line chart from the provided data.",
            "parameters": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "string",
                        "description": "The data for the line chart. Should be in a suitable format such as JSON or CSV."
                    },
                    "x": {
                        "type": "string",
                        "description": "Column for the x-axis."


key: _node_content
string_value:
{"id_": "67d360be-5c25-45d2-bd18-c7e07f1fba7a", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "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": "0f8ad10f-0d8c-4e3d-8815-d40cce7a9577", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "fe1af06febe25208ec0c4afc1b80b6117753c8e698e0a38b78ab9c14c19a6c43", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "73780b93-1629-4eaf-8221-46311a72fcba", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "ec58e342585d45498286c058ec46075ee6c498d881def16aa52ef796b87b1829", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6b0d6c2f-32c2-43a7-b92b-f46d74b33122", "node_type": "1", "metadata": {}, "hash": "e4bd970472ad9ee97c0e7ec20b0dea2cf15805759029ab60734160b548039198", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 8887, "end_char_idx": 12544, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
},
                    "independent_vars": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "List of independent variables."
                    }
                },
                "required": ["data", "dependent_var", "independent_vars"],
                "additionalProperties": False
            }
        },
        "strict": True
    }
]

visualization_tools = [
    {
        "type": "function",
        "function": {
            "name": "create_bar_chart",
            "description": "Creates a bar chart from the provided data.",
            "parameters": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "string",
                        "description": "The data for the bar chart. Should be in a suitable format such as JSON or CSV."
                    },
                    "x": {
                        "type": "string",
                        "description": "Column for the x-axis."
                    },
                    "y": {
                        "type": "string",
                        "description": "Column for the y-axis."
                    }
                },
                "required": ["data", "x", "y"],
                "additionalProperties": False
            }
        },
        "strict": True
    },
    {
        "type": "function",
        "function": {
            "name": "create_line_chart",
            "description": "Creates a line chart from the provided data.",
            "parameters": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "string",
                        "description": "The data for the line chart. Should be in a suitable format such as JSON or CSV."
                    },
                    "x": {
                        "type": "string",
                        "description": "Column for the x-axis."
                    },
                    "y": {
                        "type": "string",
                        "description": "Column for the y-axis."
                    }
                },
                "required": ["data", "x", "y"],
                "additionalProperties": False
            }
        },
        "strict": True
    },
    {
        "type": "function",
        "function": {
            "name": "create_pie_chart",
            "description": "Creates a pie chart from the provided data.",
            "parameters": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "string",
                        "description": "The data for the pie chart. Should be in a suitable format such as JSON or CSV."
                    },
                    "labels": {
                        "type": "string",
                        "description": "Column for the labels."
                    },
                    "values": {
                        "type": "string",
                        "description": "Column for the values."
                    }
                },
                "required": ["data", "labels", "values"],
                "additionalProperties": False
            }
        },
        "strict": True
    }
]
```

## Tool execution

We need to write the code logic to:
- handle passing the user query to the multi-agent system
- handle the internal workings of the multi-agent system
- execute the tool calls

For the sake of brevity, we will only define the logic for tools that are relevant to the user query.


key: _node_content
string_value:
{"id_": "6b0d6c2f-32c2-43a7-b92b-f46d74b33122", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "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": "0f8ad10f-0d8c-4e3d-8815-d40cce7a9577", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "fe1af06febe25208ec0c4afc1b80b6117753c8e698e0a38b78ab9c14c19a6c43", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "67d360be-5c25-45d2-bd18-c7e07f1fba7a", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "4efc46ebb233dbdc98a505379ef7ac348c9db822033238667c496853c1b1bd39", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "76ae0eb6-adfc-4474-aadf-eb49f870c33c", "node_type": "1", "metadata": {}, "hash": "4b05f21717db7857605a1144b4c9c396bf682503565ce7cbb2dd3d49e3c8ec45", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 10469, "end_char_idx": 13952, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
",
            "parameters": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "string",
                        "description": "The data for the line chart. Should be in a suitable format such as JSON or CSV."
                    },
                    "x": {
                        "type": "string",
                        "description": "Column for the x-axis."
                    },
                    "y": {
                        "type": "string",
                        "description": "Column for the y-axis."
                    }
                },
                "required": ["data", "x", "y"],
                "additionalProperties": False
            }
        },
        "strict": True
    },
    {
        "type": "function",
        "function": {
            "name": "create_pie_chart",
            "description": "Creates a pie chart from the provided data.",
            "parameters": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "string",
                        "description": "The data for the pie chart. Should be in a suitable format such as JSON or CSV."
                    },
                    "labels": {
                        "type": "string",
                        "description": "Column for the labels."
                    },
                    "values": {
                        "type": "string",
                        "description": "Column for the values."
                    }
                },
                "required": ["data", "labels", "values"],
                "additionalProperties": False
            }
        },
        "strict": True
    }
]
```

## Tool execution

We need to write the code logic to:
- handle passing the user query to the multi-agent system
- handle the internal workings of the multi-agent system
- execute the tool calls

For the sake of brevity, we will only define the logic for tools that are relevant to the user query.


```python
# Example query

user_query = """
Below is some data. I want you to first remove the duplicates then analyze the statistics of the data as well as plot a line chart.

house_size (m3), house_price ($)
90, 100
80, 90
100, 120
90, 100
"""

```

From the user query, we can infer that the tools we would need to call are `clean_data`, `start_analysis` and `use_line_chart`.

We will first define the execution function which runs tool calls.

This maps a tool call to the corresponding function. It then appends the output of the function to the conversation history.


```python
def clean_data(data):
    data_io = StringIO(data)
    df = pd.read_csv(data_io, sep=",")
    df_deduplicated = df.drop_duplicates()
    return df_deduplicated

def stat_analysis(data):
    data_io = StringIO(data)
    df = pd.read_csv(data_io, sep=",")
    return df.describe()

def plot_line_chart(data):
    data_io = StringIO(data)
    df = pd.read_csv(data_io, sep=",")
    
    x = df.iloc[:, 0]
    y = df.iloc[:, 1]
    
    coefficients = np.polyfit(x, y, 1)
    polynomial = np.poly1d(coefficients)
    y_fit = polynomial(x)
    
    plt.figure(figsize=(10, 6))
    plt.plot(x, y, 'o', label='Data Points')
    plt.plot(x, y_fit, '-', label='Best Fit Line')
    plt.title('Line Chart with Best Fit Line')
    plt.xlabel(df.columns[0])
    plt.ylabel(df.columns[1])
    plt.legend()
    plt.grid(True)
    plt.


key: _node_content
string_value:
{"id_": "76ae0eb6-adfc-4474-aadf-eb49f870c33c", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "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": "0f8ad10f-0d8c-4e3d-8815-d40cce7a9577", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "fe1af06febe25208ec0c4afc1b80b6117753c8e698e0a38b78ab9c14c19a6c43", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6b0d6c2f-32c2-43a7-b92b-f46d74b33122", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "b340e7f352cd54c3c071ef2906c1ff6527231192c61ecedef1c9a5041fca6d7f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "75ca3f91-ab78-4010-b9b2-8d1fcd2d2aba", "node_type": "1", "metadata": {}, "hash": "8a9b73fdf95bbefe86d0eaac4e51e7566eda84e6159afdd6cc69dc035444d864", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 12547, "end_char_idx": 15663, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
# Example query

user_query = """
Below is some data. I want you to first remove the duplicates then analyze the statistics of the data as well as plot a line chart.

house_size (m3), house_price ($)
90, 100
80, 90
100, 120
90, 100
"""

```

From the user query, we can infer that the tools we would need to call are `clean_data`, `start_analysis` and `use_line_chart`.

We will first define the execution function which runs tool calls.

This maps a tool call to the corresponding function. It then appends the output of the function to the conversation history.


```python
def clean_data(data):
    data_io = StringIO(data)
    df = pd.read_csv(data_io, sep=",")
    df_deduplicated = df.drop_duplicates()
    return df_deduplicated

def stat_analysis(data):
    data_io = StringIO(data)
    df = pd.read_csv(data_io, sep=",")
    return df.describe()

def plot_line_chart(data):
    data_io = StringIO(data)
    df = pd.read_csv(data_io, sep=",")
    
    x = df.iloc[:, 0]
    y = df.iloc[:, 1]
    
    coefficients = np.polyfit(x, y, 1)
    polynomial = np.poly1d(coefficients)
    y_fit = polynomial(x)
    
    plt.figure(figsize=(10, 6))
    plt.plot(x, y, 'o', label='Data Points')
    plt.plot(x, y_fit, '-', label='Best Fit Line')
    plt.title('Line Chart with Best Fit Line')
    plt.xlabel(df.columns[0])
    plt.ylabel(df.columns[1])
    plt.legend()
    plt.grid(True)
    plt.show()

# Define the function to execute the tools
def execute_tool(tool_calls, messages):
    for tool_call in tool_calls:
        tool_name = tool_call.function.name
        tool_arguments = json.loads(tool_call.function.arguments)

        if tool_name == 'clean_data':
            # Simulate data cleaning
            cleaned_df = clean_data(tool_arguments['data'])
            cleaned_data = {"cleaned_data": cleaned_df.to_dict()}
            messages.append({"role": "tool", "name": tool_name, "content": json.dumps(cleaned_data)})
            print('Cleaned data: ', cleaned_df)
        elif tool_name == 'transform_data':
            # Simulate data transformation
            transformed_data = {"transformed_data": "sample_transformed_data"}
            messages.append({"role": "tool", "name": tool_name, "content": json.dumps(transformed_data)})
        elif tool_name == 'aggregate_data':
            # Simulate data aggregation
            aggregated_data = {"aggregated_data": "sample_aggregated_data"}
            messages.append({"role": "tool", "name": tool_name, "content": json.dumps(aggregated_data)})
        elif tool_name == 'stat_analysis':
            # Simulate statistical analysis
            stats_df = stat_analysis(tool_arguments['data'])
            stats = {"stats": stats_df.to_dict()}
            messages.append({"role": "tool", "name": tool_name, "content": json.dumps(stats)})
            print('Statistical Analysis: ', stats_df)
        elif tool_name == 'correlation_analysis':
            # Simulate correlation analysis
            correlations = {"correlations": "sample_correlations"}
            messages.append({"role": "tool", "name": tool_name, "content": json.


key: _node_content
string_value:
{"id_": "75ca3f91-ab78-4010-b9b2-8d1fcd2d2aba", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "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": "0f8ad10f-0d8c-4e3d-8815-d40cce7a9577", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "fe1af06febe25208ec0c4afc1b80b6117753c8e698e0a38b78ab9c14c19a6c43", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "76ae0eb6-adfc-4474-aadf-eb49f870c33c", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "0a1e44f216f366a9c022b54f91a6f94e4d9e5549fc360e427a3201a2f5c002c7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d40cf797-4328-4b59-9c99-5ae0aa63a3f5", "node_type": "1", "metadata": {}, "hash": "4cc000034029137f549cbc037f3bbd0a2c0b159db48b69d5228f97f09ee18065", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 13886, "end_char_idx": 17059, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
ylabel(df.columns[1])
    plt.legend()
    plt.grid(True)
    plt.show()

# Define the function to execute the tools
def execute_tool(tool_calls, messages):
    for tool_call in tool_calls:
        tool_name = tool_call.function.name
        tool_arguments = json.loads(tool_call.function.arguments)

        if tool_name == 'clean_data':
            # Simulate data cleaning
            cleaned_df = clean_data(tool_arguments['data'])
            cleaned_data = {"cleaned_data": cleaned_df.to_dict()}
            messages.append({"role": "tool", "name": tool_name, "content": json.dumps(cleaned_data)})
            print('Cleaned data: ', cleaned_df)
        elif tool_name == 'transform_data':
            # Simulate data transformation
            transformed_data = {"transformed_data": "sample_transformed_data"}
            messages.append({"role": "tool", "name": tool_name, "content": json.dumps(transformed_data)})
        elif tool_name == 'aggregate_data':
            # Simulate data aggregation
            aggregated_data = {"aggregated_data": "sample_aggregated_data"}
            messages.append({"role": "tool", "name": tool_name, "content": json.dumps(aggregated_data)})
        elif tool_name == 'stat_analysis':
            # Simulate statistical analysis
            stats_df = stat_analysis(tool_arguments['data'])
            stats = {"stats": stats_df.to_dict()}
            messages.append({"role": "tool", "name": tool_name, "content": json.dumps(stats)})
            print('Statistical Analysis: ', stats_df)
        elif tool_name == 'correlation_analysis':
            # Simulate correlation analysis
            correlations = {"correlations": "sample_correlations"}
            messages.append({"role": "tool", "name": tool_name, "content": json.dumps(correlations)})
        elif tool_name == 'regression_analysis':
            # Simulate regression analysis
            regression_results = {"regression_results": "sample_regression_results"}
            messages.append({"role": "tool", "name": tool_name, "content": json.dumps(regression_results)})
        elif tool_name == 'create_bar_chart':
            # Simulate bar chart creation
            bar_chart = {"bar_chart": "sample_bar_chart"}
            messages.append({"role": "tool", "name": tool_name, "content": json.dumps(bar_chart)})
        elif tool_name == 'create_line_chart':
            # Simulate line chart creation
            line_chart = {"line_chart": "sample_line_chart"}
            messages.append({"role": "tool", "name": tool_name, "content": json.dumps(line_chart)})
            plot_line_chart(tool_arguments['data'])
        elif tool_name == 'create_pie_chart':
            # Simulate pie chart creation
            pie_chart = {"pie_chart": "sample_pie_chart"}
            messages.append({"role": "tool", "name": tool_name, "content": json.dumps(pie_chart)})
    return messages
```

Next, we will create the tool handlers for each of the sub-agents.

These have a unique prompt and tool set passed to the model. 

The output is then passed to an execution function which runs the tool calls.

We will also append the messages to the conversation history.


key: _node_content
string_value:
{"id_": "d40cf797-4328-4b59-9c99-5ae0aa63a3f5", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "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": "0f8ad10f-0d8c-4e3d-8815-d40cce7a9577", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "fe1af06febe25208ec0c4afc1b80b6117753c8e698e0a38b78ab9c14c19a6c43", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "75ca3f91-ab78-4010-b9b2-8d1fcd2d2aba", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "4ec9d12f2be7ff8b7cc54bc2b9f09717ca7b393b092f928b0d8a0d1dab4967dc", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "77c52cac-e291-4ac6-a22c-f1eb56581575", "node_type": "1", "metadata": {}, "hash": "b44890ff91be8ed1f6ca738a51286a228e425876a42ee184485e6e985cd46d9a", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 15262, "end_char_idx": 19028, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
to_dict()}
            messages.append({"role": "tool", "name": tool_name, "content": json.dumps(stats)})
            print('Statistical Analysis: ', stats_df)
        elif tool_name == 'correlation_analysis':
            # Simulate correlation analysis
            correlations = {"correlations": "sample_correlations"}
            messages.append({"role": "tool", "name": tool_name, "content": json.dumps(correlations)})
        elif tool_name == 'regression_analysis':
            # Simulate regression analysis
            regression_results = {"regression_results": "sample_regression_results"}
            messages.append({"role": "tool", "name": tool_name, "content": json.dumps(regression_results)})
        elif tool_name == 'create_bar_chart':
            # Simulate bar chart creation
            bar_chart = {"bar_chart": "sample_bar_chart"}
            messages.append({"role": "tool", "name": tool_name, "content": json.dumps(bar_chart)})
        elif tool_name == 'create_line_chart':
            # Simulate line chart creation
            line_chart = {"line_chart": "sample_line_chart"}
            messages.append({"role": "tool", "name": tool_name, "content": json.dumps(line_chart)})
            plot_line_chart(tool_arguments['data'])
        elif tool_name == 'create_pie_chart':
            # Simulate pie chart creation
            pie_chart = {"pie_chart": "sample_pie_chart"}
            messages.append({"role": "tool", "name": tool_name, "content": json.dumps(pie_chart)})
    return messages
```

Next, we will create the tool handlers for each of the sub-agents.

These have a unique prompt and tool set passed to the model. 

The output is then passed to an execution function which runs the tool calls.

We will also append the messages to the conversation history.


```python
# Define the functions to handle each agent's processing
def handle_data_processing_agent(query, conversation_messages):
    messages = [{"role": "system", "content": processing_system_prompt}]
    messages.append({"role": "user", "content": query})

    response = client.chat.completions.create(
        model=MODEL,
        messages=messages,
        temperature=0,
        tools=preprocess_tools,
    )

    conversation_messages.append([tool_call.function for tool_call in response.choices[0].message.tool_calls])
    execute_tool(response.choices[0].message.tool_calls, conversation_messages)

def handle_analysis_agent(query, conversation_messages):
    messages = [{"role": "system", "content": analysis_system_prompt}]
    messages.append({"role": "user", "content": query})

    response = client.chat.completions.create(
        model=MODEL,
        messages=messages,
        temperature=0,
        tools=analysis_tools,
    )

    conversation_messages.append([tool_call.function for tool_call in response.choices[0].message.tool_calls])
    execute_tool(response.choices[0].message.tool_calls, conversation_messages)

def handle_visualization_agent(query, conversation_messages):
    messages = [{"role": "system", "content": visualization_system_prompt}]
    messages.append({"role": "user", "content": query})

    response = client.chat.completions.create(
        model=MODEL,
        messages=messages,
        temperature=0,
        tools=visualization_tools,
    )

    conversation_messages.append([tool_call.function for tool_call in response.choices[0].message.tool_calls])
    execute_tool(response.choices[0].message.tool_calls, conversation_messages)

```

Finally, we create the overarching tool to handle processing the user query.

This function takes the user query, gets a response from the model and handles passing it to the other agents to execute. In addition to this, we will keep the state of the ongoing conversation.


key: _node_content
string_value:
{"id_": "77c52cac-e291-4ac6-a22c-f1eb56581575", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "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": "0f8ad10f-0d8c-4e3d-8815-d40cce7a9577", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "fe1af06febe25208ec0c4afc1b80b6117753c8e698e0a38b78ab9c14c19a6c43", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d40cf797-4328-4b59-9c99-5ae0aa63a3f5", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "ff7d5f9065f06b2cb843b69aeed6c4bd01bcd9595d3855e45c929d898b0ce115", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "295ef027-c032-4a7e-8aac-6e739f9993c9", "node_type": "1", "metadata": {}, "hash": "3b8ef1fd6e774006ad1bf052b1104c5a123c609b42b6d3b5aba4bb146569adcd", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 17062, "end_char_idx": 20490, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
# Define the functions to handle each agent's processing
def handle_data_processing_agent(query, conversation_messages):
    messages = [{"role": "system", "content": processing_system_prompt}]
    messages.append({"role": "user", "content": query})

    response = client.chat.completions.create(
        model=MODEL,
        messages=messages,
        temperature=0,
        tools=preprocess_tools,
    )

    conversation_messages.append([tool_call.function for tool_call in response.choices[0].message.tool_calls])
    execute_tool(response.choices[0].message.tool_calls, conversation_messages)

def handle_analysis_agent(query, conversation_messages):
    messages = [{"role": "system", "content": analysis_system_prompt}]
    messages.append({"role": "user", "content": query})

    response = client.chat.completions.create(
        model=MODEL,
        messages=messages,
        temperature=0,
        tools=analysis_tools,
    )

    conversation_messages.append([tool_call.function for tool_call in response.choices[0].message.tool_calls])
    execute_tool(response.choices[0].message.tool_calls, conversation_messages)

def handle_visualization_agent(query, conversation_messages):
    messages = [{"role": "system", "content": visualization_system_prompt}]
    messages.append({"role": "user", "content": query})

    response = client.chat.completions.create(
        model=MODEL,
        messages=messages,
        temperature=0,
        tools=visualization_tools,
    )

    conversation_messages.append([tool_call.function for tool_call in response.choices[0].message.tool_calls])
    execute_tool(response.choices[0].message.tool_calls, conversation_messages)

```

Finally, we create the overarching tool to handle processing the user query.

This function takes the user query, gets a response from the model and handles passing it to the other agents to execute. In addition to this, we will keep the state of the ongoing conversation.


```python
# Function to handle user input and triaging
def handle_user_message(user_query, conversation_messages=[]):
    user_message = {"role": "user", "content": user_query}
    conversation_messages.append(user_message)


    messages = [{"role": "system", "content": triaging_system_prompt}]
    messages.extend(conversation_messages)

    response = client.chat.completions.create(
        model=MODEL,
        messages=messages,
        temperature=0,
        tools=triage_tools,
    )

    conversation_messages.append([tool_call.function for tool_call in response.choices[0].message.tool_calls])

    for tool_call in response.choices[0].message.tool_calls:
        if tool_call.function.name == 'send_query_to_agents':
            agents = json.loads(tool_call.function.arguments)['agents']
            query = json.loads(tool_call.function.arguments)['query']
            for agent in agents:
                if agent == "Data Processing Agent":
                    handle_data_processing_agent(query, conversation_messages)
                elif agent == "Analysis Agent":
                    handle_analysis_agent(query, conversation_messages)
                elif agent == "Visualization Agent":
                    handle_visualization_agent(query, conversation_messages)

    return conversation_messages
```

## Multi-agent system execution

Finally, we run the overarching `handle_user_message` function on the user query and view the output.


key: _node_content
string_value:
{"id_": "295ef027-c032-4a7e-8aac-6e739f9993c9", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "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": "0f8ad10f-0d8c-4e3d-8815-d40cce7a9577", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "fe1af06febe25208ec0c4afc1b80b6117753c8e698e0a38b78ab9c14c19a6c43", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "77c52cac-e291-4ac6-a22c-f1eb56581575", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "190bc8473940e526922a57451748e1cc1a14c06d5509f16f5c4bfc9597368850", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6ff46108-c4e9-432f-b12c-84a64d064c6b", "node_type": "1", "metadata": {}, "hash": "5ec02275156366d6b7c66296637a6ff174890163a1addd5f836beda85027ac16", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 19031, "end_char_idx": 21088, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
# Function to handle user input and triaging
def handle_user_message(user_query, conversation_messages=[]):
    user_message = {"role": "user", "content": user_query}
    conversation_messages.append(user_message)


    messages = [{"role": "system", "content": triaging_system_prompt}]
    messages.extend(conversation_messages)

    response = client.chat.completions.create(
        model=MODEL,
        messages=messages,
        temperature=0,
        tools=triage_tools,
    )

    conversation_messages.append([tool_call.function for tool_call in response.choices[0].message.tool_calls])

    for tool_call in response.choices[0].message.tool_calls:
        if tool_call.function.name == 'send_query_to_agents':
            agents = json.loads(tool_call.function.arguments)['agents']
            query = json.loads(tool_call.function.arguments)['query']
            for agent in agents:
                if agent == "Data Processing Agent":
                    handle_data_processing_agent(query, conversation_messages)
                elif agent == "Analysis Agent":
                    handle_analysis_agent(query, conversation_messages)
                elif agent == "Visualization Agent":
                    handle_visualization_agent(query, conversation_messages)

    return conversation_messages
```

## Multi-agent system execution

Finally, we run the overarching `handle_user_message` function on the user query and view the output.


```python
handle_user_message(user_query)
```

    Cleaned data:     house_size (m3)   house_price ($)
    0               90               100
    1               80                90
    2              100               120
    Statistical Analysis:         house_size  house_price
    count    4.000000     4.000000
    mean    90.000000   102.500000
    std      8.164966    12.583057
    min     80.000000    90.000000
    25%     87.500000    97.500000
    50%     90.000000   100.000000
    75%     92.500000   105.000000
    max    100.000000   120.000000



    
![png](output_17_1.png)


key: _node_content
string_value:
{"id_": "6ff46108-c4e9-432f-b12c-84a64d064c6b", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "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": "0f8ad10f-0d8c-4e3d-8815-d40cce7a9577", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "fe1af06febe25208ec0c4afc1b80b6117753c8e698e0a38b78ab9c14c19a6c43", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "295ef027-c032-4a7e-8aac-6e739f9993c9", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "66a7451b5a182a76f26fc5ac656b7a8254e4e2151053b0b608868e881e713b76", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "170f50b0-b87b-41cd-be29-4029dbe8f6af", "node_type": "1", "metadata": {}, "hash": "3ca26a10fac99412b4e4e60a583b3b4eb32c7e214f8ebb623ecd1fd4178f4cfc", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 20493, "end_char_idx": 23067, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
handle_user_message(user_query)
```

    Cleaned data:     house_size (m3)   house_price ($)
    0               90               100
    1               80                90
    2              100               120
    Statistical Analysis:         house_size  house_price
    count    4.000000     4.000000
    mean    90.000000   102.500000
    std      8.164966    12.583057
    min     80.000000    90.000000
    25%     87.500000    97.500000
    50%     90.000000   100.000000
    75%     92.500000   105.000000
    max    100.000000   120.000000



    
![png](output_17_1.png)
    





    [{'role': 'user',
      'content': '\nBelow is some data. I want you to first remove the duplicates then analyze the statistics of the data as well as plot a line chart.\n\nhouse_size (m3), house_price ($)\n90, 100\n80, 90\n100, 120\n90, 100\n'},
     [Function(arguments='{"agents": ["Data Processing Agent"], "query": "Remove duplicates from the data: house_size (m3), house_price ($)\\n90, 100\\n80, 90\\n100, 120\\n90, 100"}', name='send_query_to_agents'),
      Function(arguments='{"agents": ["Analysis Agent"], "query": "Analyze the statistics of the data: house_size (m3), house_price ($)\\n90, 100\\n80, 90\\n100, 120\\n90, 100"}', name='send_query_to_agents'),
      Function(arguments='{"agents": ["Visualization Agent"], "query": "Plot a line chart for the data: house_size (m3), house_price ($)\\n90, 100\\n80, 90\\n100, 120\\n90, 100"}', name='send_query_to_agents')],
     [Function(arguments='{"data":"house_size (m3), house_price ($)\\n90, 100\\n80, 90\\n100, 120\\n90, 100"}', name='clean_data')],
     {'role': 'tool',
      'name': 'clean_data',
      'content': '{"cleaned_data": {"house_size (m3)": {"0": 90, "1": 80, "2": 100}, " house_price ($)": {"0": 100, "1": 90, "2": 120}}}'},
     [Function(arguments='{"data":"house_size,house_price\\n90,100\\n80,90\\n100,120\\n90,100"}', name='stat_analysis')],
     {'role': 'tool',
      'name': 'stat_analysis',
      'content': '{"stats": {"house_size": {"count": 4.0, "mean": 90.0, "std": 8.16496580927726, "min": 80.0, "25%": 87.5, "50%": 90.0, "75%": 92.5, "max": 100.0}, "house_price": {"count": 4.0, "mean": 102.5, "std": 12.583057392117917, "min": 90.0, "25%": 97.5, "50%": 100.0, "75%": 105.0, "max": 120.0}}}'},
     [Function(arguments='{"data":"house_size,house_price\\n90,100\\n80,90\\n100,120\\n90,100","x":"house_size","y":"house_price"}', name='create_line_chart')],
     {'role': 'tool',
      'name': 'create_line_chart',
      'content': '{"line_chart": "sample_line_chart"}'}]


key: _node_content
string_value:
{"id_": "170f50b0-b87b-41cd-be29-4029dbe8f6af", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "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": "0f8ad10f-0d8c-4e3d-8815-d40cce7a9577", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "fe1af06febe25208ec0c4afc1b80b6117753c8e698e0a38b78ab9c14c19a6c43", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6ff46108-c4e9-432f-b12c-84a64d064c6b", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Structured_outputs_multi_agent.ipynb", "title": "Structured Outputs for Multi-Agent Systems", "tokens": 5044, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "f7664ccb0e6e4ac5ec835a7b0b5c2125a76c7f3fef661c6252a9506312f30a59", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 23071, "end_char_idx": 23478, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
## Conclusion

In this cookbook, we've explored how to leverage Structured Outputs to build more robust multi-agent systems.

Using this new feature allows to make sure that tool calls follow the specified schema and avoids having to handle edge cases or validate arguments on your side.

This can be applied to many more use cases, and we hope you can take inspiration from this to build your own use case!


key: _node_content
string_value:
{"id_": "f4a011d0-35fe-4a63-9e47-5338f8520f9b", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Get_embeddings_from_dataset.ipynb", "title": "Get embeddings from dataset", "tokens": 1039, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "5baa0f2c-2841-40b8-8dfc-f63f9cf03b37", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Get_embeddings_from_dataset.ipynb", "title": "Get embeddings from dataset", "tokens": 1039, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "49be16cfb23af57242bf7423ac38d296ea745d86ade8881c11652b3cdc713d2c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b4d5d5f6-f33b-45c6-9c87-42a1707bb516", "node_type": "1", "metadata": {}, "hash": "846db94890969d02b511b6b0563485df3f45fcfc0e81948dad0f947efa431353", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 1585, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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

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


## 1. Load the dataset

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

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

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


```python
import pandas as pd
import tiktoken

from utils.embeddings_utils import get_embedding
```


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


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


key: _node_content
string_value:
{"id_": "b4d5d5f6-f33b-45c6-9c87-42a1707bb516", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Get_embeddings_from_dataset.ipynb", "title": "Get embeddings from dataset", "tokens": 1039, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "5baa0f2c-2841-40b8-8dfc-f63f9cf03b37", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Get_embeddings_from_dataset.ipynb", "title": "Get embeddings from dataset", "tokens": 1039, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "49be16cfb23af57242bf7423ac38d296ea745d86ade8881c11652b3cdc713d2c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f4a011d0-35fe-4a63-9e47-5338f8520f9b", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Get_embeddings_from_dataset.ipynb", "title": "Get embeddings from dataset", "tokens": 1039, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "73341300812797c473f5aba64de2386509a5fabdfaa92ff5b7e3ae0badd17c48", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "46d75d4e-de03-4a57-a70e-08997748a292", "node_type": "1", "metadata": {}, "hash": "4aab987284a9b930ef5bcf5c4684f53c7a0f43edcb39020b2294aefd9f02f97b", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2764, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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

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


## 1. Load the dataset

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

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

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


```python
import pandas as pd
import tiktoken

from utils.embeddings_utils import get_embedding
```


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


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




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

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

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Time</th>
      <th>ProductId</th>
      <th>UserId</th>
      <th>Score</th>
      <th>Summary</th>
      <th>Text</th>
      <th>combined</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>1351123200</td>
      <td>B003XPF9BO</td>
      <td>A3R7JR3FMEBXQB</td>
      <td>5</td>
      <td>where does one  start...and stop... with a tre...</td>
      <td>Wanted to save some to bring to my Chicago fam...</td>
      <td>Title: where does one  start...and stop... wit...</td>
    </tr>
    <tr>
      <th>1</th>
      <td>1351123200</td>
      <td>B003JK537S</td>
      <td>A3JBPC3WFUT5ZP</td>
      <td>1</td>
      <td>Arrived in pieces</td>
      <td>Not pleased at all. When I opened the box, mos...</td>
      <td>Title: Arrived in pieces; Content: Not pleased...</td>
    </tr>
  </tbody>
</table>
</div>


key: _node_content
string_value:
{"id_": "46d75d4e-de03-4a57-a70e-08997748a292", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Get_embeddings_from_dataset.ipynb", "title": "Get embeddings from dataset", "tokens": 1039, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "5baa0f2c-2841-40b8-8dfc-f63f9cf03b37", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Get_embeddings_from_dataset.ipynb", "title": "Get embeddings from dataset", "tokens": 1039, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "49be16cfb23af57242bf7423ac38d296ea745d86ade8881c11652b3cdc713d2c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b4d5d5f6-f33b-45c6-9c87-42a1707bb516", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/Get_embeddings_from_dataset.ipynb", "title": "Get embeddings from dataset", "tokens": 1039, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "9b4a5a36de072f523644ee0cedc53a67c01b22faea8c7e94b36be40a9a157642", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1590, "end_char_idx": 3694, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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

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

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Time</th>
      <th>ProductId</th>
      <th>UserId</th>
      <th>Score</th>
      <th>Summary</th>
      <th>Text</th>
      <th>combined</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>1351123200</td>
      <td>B003XPF9BO</td>
      <td>A3R7JR3FMEBXQB</td>
      <td>5</td>
      <td>where does one  start...and stop... with a tre...</td>
      <td>Wanted to save some to bring to my Chicago fam...</td>
      <td>Title: where does one  start...and stop... wit...</td>
    </tr>
    <tr>
      <th>1</th>
      <td>1351123200</td>
      <td>B003JK537S</td>
      <td>A3JBPC3WFUT5ZP</td>
      <td>1</td>
      <td>Arrived in pieces</td>
      <td>Not pleased at all. When I opened the box, mos...</td>
      <td>Title: Arrived in pieces; Content: Not pleased...</td>
    </tr>
  </tbody>
</table>
</div>




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

encoding = tiktoken.get_encoding(embedding_encoding)

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




    1000



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


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

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


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


key: _node_content
string_value:
{"id_": "d740bf66-0d08-4fa9-b194-3354cb49672b", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "904079d1-adc5-4f31-b8ac-2a4759cc9131", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "55b917d4c2d8323320d7e68745831f44c180a3437acb783f6d700c109f0e666a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "13b71fe6-71a2-4f31-abe3-0b69b001dbeb", "node_type": "1", "metadata": {}, "hash": "35728e63cdd5b2305dcccd2a26134c575d0591fecbb6474b2eb63040d81a3ab2", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3340, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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

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

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

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

## Why rate limits exist

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

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

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

## Default rate limits

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

### Other rate limit resources

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

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

### Requesting a rate limit increase

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



```python
import openai
import os

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

## Example rate limit error

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

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

Below is example code for triggering a rate limit error.


key: _node_content
string_value:
{"id_": "13b71fe6-71a2-4f31-abe3-0b69b001dbeb", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "904079d1-adc5-4f31-b8ac-2a4759cc9131", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "55b917d4c2d8323320d7e68745831f44c180a3437acb783f6d700c109f0e666a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d740bf66-0d08-4fa9-b194-3354cb49672b", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "8855150a11bb97552ac55d2f317d12574e4ceb53e562e01b1ef3819f50d26ad6", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "fb9d1da1-4f6b-4fb9-a6d3-51b0cc6710cc", "node_type": "1", "metadata": {}, "hash": "9b6983d9c479972d804521dedbdfb4111e4acb446dea7d958ff0b908de43e817", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2708, "end_char_idx": 5921, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
import openai
import os

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

## Example rate limit error

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

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

Below is example code for triggering a rate limit error.


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

## How to avoid rate limit errors

### Retrying with exponential backoff

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

This approach has many benefits:

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

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

Below are a few example solutions.

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

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

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

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


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

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


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




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


key: _node_content
string_value:
{"id_": "fb9d1da1-4f6b-4fb9-a6d3-51b0cc6710cc", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "904079d1-adc5-4f31-b8ac-2a4759cc9131", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "55b917d4c2d8323320d7e68745831f44c180a3437acb783f6d700c109f0e666a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "13b71fe6-71a2-4f31-abe3-0b69b001dbeb", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "bbca2abb06e0ea071c0dac9bbe6c0a0117de2be0475579ed269de9ada2f19e43", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "64bec6a0-f6e1-418c-889f-2bd88cd77711", "node_type": "1", "metadata": {}, "hash": "9fe11423660d31ddac67a28aa64dbd5bf5e5e8f76bfe4e852ecef2dae0e6f0ad", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5229, "end_char_idx": 8557, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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

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


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




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


key: _node_content
string_value:
{"id_": "64bec6a0-f6e1-418c-889f-2bd88cd77711", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "904079d1-adc5-4f31-b8ac-2a4759cc9131", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "55b917d4c2d8323320d7e68745831f44c180a3437acb783f6d700c109f0e666a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "fb9d1da1-4f6b-4fb9-a6d3-51b0cc6710cc", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "9e6283fbaa3299fcf9375a59407747ae2688c6319a3702ee0c09950fcdffd851", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "337b39eb-d4b6-4996-a6cd-6973aa6cd5f1", "node_type": "1", "metadata": {}, "hash": "bf4efd6c34417f98e9b916b0076e7aa24fad6bfe439826b58fa66fadee359a92", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 6875, "end_char_idx": 9966, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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



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

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

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


```python
import backoff  # for exponential backoff

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


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

```


key: _node_content
string_value:
{"id_": "337b39eb-d4b6-4996-a6cd-6973aa6cd5f1", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "904079d1-adc5-4f31-b8ac-2a4759cc9131", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "55b917d4c2d8323320d7e68745831f44c180a3437acb783f6d700c109f0e666a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "64bec6a0-f6e1-418c-889f-2bd88cd77711", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "bbeacc8a26cf3589e79afe9de7303e7091c96470400fb8b88a5dcc351cddbd77", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "07742532-d883-47be-a4c2-f8e97b44069b", "node_type": "1", "metadata": {}, "hash": "537d34ecc6186471d0c52531761f49a5b68e23ca3e918f1350f155dcd6cf1603", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 8261, "end_char_idx": 13467, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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



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

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

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


```python
import backoff  # for exponential backoff

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


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

```




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


key: _node_content
string_value:
{"id_": "07742532-d883-47be-a4c2-f8e97b44069b", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "904079d1-adc5-4f31-b8ac-2a4759cc9131", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "55b917d4c2d8323320d7e68745831f44c180a3437acb783f6d700c109f0e666a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "337b39eb-d4b6-4996-a6cd-6973aa6cd5f1", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "58033f86422576871083ddde4e8efbd58a8570a3021dd7ca9e04d760725431df", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9877ec09-81c2-476a-8f2d-c678ed3accb0", "node_type": "1", "metadata": {}, "hash": "7267226ee460535ff9c9811b0eae4e6c60e8321cff1587ee8915312e2858dc7f", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 13471, "end_char_idx": 16703, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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

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


```python
# imports
import random
import time

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

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

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

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

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

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

                # Sleep for the delay
                time.sleep(delay)

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

    return wrapper


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


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




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


key: _node_content
string_value:
{"id_": "9877ec09-81c2-476a-8f2d-c678ed3accb0", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "904079d1-adc5-4f31-b8ac-2a4759cc9131", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "55b917d4c2d8323320d7e68745831f44c180a3437acb783f6d700c109f0e666a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "07742532-d883-47be-a4c2-f8e97b44069b", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "84a56d3138017bc5b9939a89f6c8de68d3f48e3e740fe9a68aa60f39ba56d030", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b2642784-a38d-4ed6-aae7-032b1d0f9c0d", "node_type": "1", "metadata": {}, "hash": "64b108d9d8feb330c4d84724a0f79c593ae5f53329717247ca8408646192eb2c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 15079, "end_char_idx": 18425, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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




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


key: _node_content
string_value:
{"id_": "b2642784-a38d-4ed6-aae7-032b1d0f9c0d", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "904079d1-adc5-4f31-b8ac-2a4759cc9131", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "55b917d4c2d8323320d7e68745831f44c180a3437acb783f6d700c109f0e666a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9877ec09-81c2-476a-8f2d-c678ed3accb0", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "827beb52d89702135d84cb1e3b41cd1070387a1ef68cbc4bd23f25d835c1c3a0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "15656396-f565-465c-a54e-55a54558b19e", "node_type": "1", "metadata": {}, "hash": "f1fe2b7959918290beee8a6c208d1372a0f1923ce07809a92b8da5047de3fa3f", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 16568, "end_char_idx": 20023, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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



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

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

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

### Proactively adding delay between requests

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

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

#### Example of adding delay to a request


key: _node_content
string_value:
{"id_": "15656396-f565-465c-a54e-55a54558b19e", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "904079d1-adc5-4f31-b8ac-2a4759cc9131", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "55b917d4c2d8323320d7e68745831f44c180a3437acb783f6d700c109f0e666a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b2642784-a38d-4ed6-aae7-032b1d0f9c0d", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "124cb3399cace2c48e7dcc860e86e2b316ead670db236573754a1452678051ed", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9c775e8e-7968-4254-a3c3-bc335cab4189", "node_type": "1", "metadata": {}, "hash": "fedecaa6618c0f18aaf11abe09af9f01e562209cb03667c099a57553da69eed6", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 18234, "end_char_idx": 20669, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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



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

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

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

### Proactively adding delay between requests

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

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

#### Example of adding delay to a request


```python
# imports
import time

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

    # Sleep for the delay
    time.sleep(delay_in_seconds)

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


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

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

```


key: _node_content
string_value:
{"id_": "9c775e8e-7968-4254-a3c3-bc335cab4189", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "904079d1-adc5-4f31-b8ac-2a4759cc9131", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "55b917d4c2d8323320d7e68745831f44c180a3437acb783f6d700c109f0e666a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "15656396-f565-465c-a54e-55a54558b19e", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "9caa849bac6af6182f6d28f4f6baa1413ee2323bc05564925aadad4bdd5039c0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "0de33293-36c9-43c8-a432-3aa0ff3eeba6", "node_type": "1", "metadata": {}, "hash": "58f91675f6169c705361f303d47ac1296375c425637d7b2a8d74512023d08b02", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 18940, "end_char_idx": 23658, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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

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

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

### Proactively adding delay between requests

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

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

#### Example of adding delay to a request


```python
# imports
import time

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

    # Sleep for the delay
    time.sleep(delay_in_seconds)

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


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

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

```




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


key: _node_content
string_value:
{"id_": "0de33293-36c9-43c8-a432-3aa0ff3eeba6", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "904079d1-adc5-4f31-b8ac-2a4759cc9131", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "55b917d4c2d8323320d7e68745831f44c180a3437acb783f6d700c109f0e666a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9c775e8e-7968-4254-a3c3-bc335cab4189", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "ebeb5de97e7c7d6d05b788d65b9c88cc6cb42e86a299986c13e23d4266e56a29", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ca631a01-14af-462e-a2a5-9b131a2195db", "node_type": "1", "metadata": {}, "hash": "3c80f4ea0cec491cdd1f824575e0395b80c79d37bdc434d547af9f1fa0eb80aa", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 23664, "end_char_idx": 25967, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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

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

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

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

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

#### Example without batching


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

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

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

```

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


#### Example with batching


key: _node_content
string_value:
{"id_": "ca631a01-14af-462e-a2a5-9b131a2195db", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "904079d1-adc5-4f31-b8ac-2a4759cc9131", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "55b917d4c2d8323320d7e68745831f44c180a3437acb783f6d700c109f0e666a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "0de33293-36c9-43c8-a432-3aa0ff3eeba6", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "f8ab38ada62646c0b105dcb02d9e4c0720741d031976988cc684c4cbb57bca68", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b936a6b4-c644-4f32-baa1-16e08cd1a2f9", "node_type": "1", "metadata": {}, "hash": "89523fd07a6f446bffe166ff8716348f24ee073c1f8eab5fd981e50d77ebdee2", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 24398, "end_char_idx": 27544, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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

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

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

```

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


#### Example with batching


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

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

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

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

```

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


key: _node_content
string_value:
{"id_": "b936a6b4-c644-4f32-baa1-16e08cd1a2f9", "embedding": null, "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "904079d1-adc5-4f31-b8ac-2a4759cc9131", "node_type": "4", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "55b917d4c2d8323320d7e68745831f44c180a3437acb783f6d700c109f0e666a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ca631a01-14af-462e-a2a5-9b131a2195db", "node_type": "1", "metadata": {"url": "https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb", "title": "How to handle rate limits", "tokens": 6170, "retrieve_doc": true, "source": "openai_cookbooks"}, "hash": "7004b8024869c4f7d9b9f1d60024d7af1c6a2a5c750570dce7e1781b50507384", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 25941, "end_char_idx": 28207, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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


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

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

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

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

```

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


## Example parallel processing script

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

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

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


key: _node_content
string_value:
{"id_": "e6c1a9db-d579-4680-8885-e04a09eab2ae", "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"}, "3": {"node_id": "f25d4c29-ec07-4992-9685-f00f0d6d9e88", "node_type": "1", "metadata": {}, "hash": "1747f5921bc46dde0c5f7e7b639c7bb27eb4ede64085ab49aed3e8eff375bd7a", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3162, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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


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


For context, from the function calling notebook above:

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


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

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

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

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


### Overview


This notebook contains three sections

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


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


# Getting baseline function calling performance



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


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

%load_ext dotenv
%dotenv

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

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


### Utilities


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


key: _node_content
string_value:
{"id_": "f25d4c29-ec07-4992-9685-f00f0d6d9e88", "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": "e6c1a9db-d579-4680-8885-e04a09eab2ae", "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": "e243fe126a4284cb6153a51a100efafe11fda7a10aa4de0fcb6904c287e7108c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "86128f8a-fcdc-40ae-b0ce-2ebadc106d91", "node_type": "1", "metadata": {}, "hash": "865f52d0f9dde2ddde3c8d5d431f521823465ff8e1de903f782a8fd30aea8370", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1552, "end_char_idx": 3832, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
### Overview


This notebook contains three sections

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


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


# Getting baseline function calling performance



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


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

%load_ext dotenv
%dotenv

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

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


### Utilities


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



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

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


key: _node_content
string_value:
{"id_": "86128f8a-fcdc-40ae-b0ce-2ebadc106d91", "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": "f25d4c29-ec07-4992-9685-f00f0d6d9e88", "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": "7d26657b99aee6852163903a5e06d54f1b19957d016aed3bb29c466e24b83246", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "741483b1-e93e-4851-9092-14ce3ae44500", "node_type": "1", "metadata": {}, "hash": "b248981f55ee65a98d4c1c123c6035a1dc0c796a67c346a4505c8a2caa3c72c7", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2348, "end_char_idx": 7078, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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



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


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

%load_ext dotenv
%dotenv

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

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


### Utilities


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



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

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


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

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

    Returns:
        None
    """

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

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

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

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

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

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

    total_prompts = len(prompts_to_expected_tool_name)

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

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

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

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

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

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

    # Display the DataFrame as a table
    display(styled_results_df)

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

### Baseline testing


key: _node_content
string_value:
{"id_": "741483b1-e93e-4851-9092-14ce3ae44500", "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": "86128f8a-fcdc-40ae-b0ce-2ebadc106d91", "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": "80e8a570c33b9f4dcc1e4bb0f4e3668e3c9d18af1c7185fedc2fbc7e7fb296e4", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "36428875-7ba9-44e0-b291-c920d984e0e4", "node_type": "1", "metadata": {}, "hash": "12cccbb7ddb2be23b222f06c2701073aa081abd7ba0a083f9208a8fa23f9f1de", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 7081, "end_char_idx": 11119, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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



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

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



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


key: _node_content
string_value:
{"id_": "36428875-7ba9-44e0-b291-c920d984e0e4", "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": "741483b1-e93e-4851-9092-14ce3ae44500", "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": "09466794b0383d64925779e04118f830945e2ef88003e2575596342bc02daf75", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8f0f5468-6078-4b1f-8776-afe7e36caf30", "node_type": "1", "metadata": {}, "hash": "2b4fcf61169a9574d2c73712c8121d77457867a0a09fed3fd68c5fb0cea42ea6", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 9043, "end_char_idx": 12956, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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


key: _node_content
string_value:
{"id_": "8f0f5468-6078-4b1f-8776-afe7e36caf30", "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": "36428875-7ba9-44e0-b291-c920d984e0e4", "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": "081c2b0b3d162a0c5b86108f5544db0f7881f4b032d19d03afcd419ab7068655", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7193e2ef-187c-443e-a605-efa6f486257e", "node_type": "1", "metadata": {}, "hash": "f3c62e1d2a36b331f737a623b9cb6837e3f7ec8b2074c6922f9cc6fc953fddb1", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 11119, "end_char_idx": 14898, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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


key: _node_content
string_value:
{"id_": "7193e2ef-187c-443e-a605-efa6f486257e", "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": "8f0f5468-6078-4b1f-8776-afe7e36caf30", "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": "acf36dbd1c2b75718cc58b70b6a0af1e63c82322530345545b514fad95699f45", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6c04c5ae-3ae1-41c8-afc3-d6d36965d996", "node_type": "1", "metadata": {}, "hash": "b16b6cebacf9682aa9326005a9e0493cdf650a1a1d7a7ac6b1043232912886c5", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 12956, "end_char_idx": 16852, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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


key: _node_content
string_value:
{"id_": "6c04c5ae-3ae1-41c8-afc3-d6d36965d996", "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": "7193e2ef-187c-443e-a605-efa6f486257e", "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": "4a44457f4460d87f0f6dd4e0e785bc89d2f261ca774eef3caae386336f4ad081", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "cc9eb089-06b8-4839-826e-431fb1e6d6f5", "node_type": "1", "metadata": {}, "hash": "7e7406058e1abf87bcc40bbdebff9f242dbca6b236d25883f144cf11a3c4ff55", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 14898, "end_char_idx": 18412, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


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

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



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


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


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


key: _node_content
string_value:
{"id_": "cc9eb089-06b8-4839-826e-431fb1e6d6f5", "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": "6c04c5ae-3ae1-41c8-afc3-d6d36965d996", "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": "09f009171bcf8517dde97b8c0c4d16580b5fb9a7c0b51f9e8cf1bce0d489ab1b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "cbeb5b95-ef6e-496a-8978-53d5e13cc0f2", "node_type": "1", "metadata": {}, "hash": "7a71d7dd56e8801497d666ea8787e657c7d9207cc7e6c539915a061aa92bfa56", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 16852, "end_char_idx": 19092, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
",
                    }
                },
                "required": ["coordinates"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "reject_request",
            "description": "Use this function if the request is not possible.",
            "parameters": {"type": "object", "properties": {}},
        },
    },
]
```

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



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


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


<style type="text/css">
#T_b01a0_row0_col0, #T_b01a0_row0_col1, #T_b01a0_row0_col2, #T_b01a0_row0_col3, #T_b01a0_row1_col0, #T_b01a0_row1_col1, #T_b01a0_row1_col2, #T_b01a0_row1_col3, #T_b01a0_row2_col0, #T_b01a0_row2_col1, #T_b01a0_row2_col2, #T_b01a0_row2_col3, #T_b01a0_row3_col0, #T_b01a0_row3_col1, #T_b01a0_row3_col2, #T_b01a0_row3_col3, #T_b01a0_row4_col0, #T_b01a0_row4_col1, #T_b01a0_row4_col2, #T_b01a0_row4_col3, #T_b01a0_row5_col0, #T_b01a0_row5_col1, #T_b01a0_row5_col2, #T_b01a0_row5_col3, #T_b01a0_row6_col0, #T_b01a0_row6_col1, #T_b01a0_row6_col2, #T_b01a0_row6_col3, #T_b01a0_row7_col0, #T_b01a0_row7_col1, #T_b01a0_row7_col2, #T_b01a0_row7_col3, #T_b01a0_row8_col0, #T_b01a0_row8_col1, #T_b01a0_row8_col2, #T_b01a0_row8_col3, #T_b01a0_row9_col0, #T_b01a0_row9_col1, #T_b01a0_row9_col2,


key: _node_content
string_value:
{"id_": "cbeb5b95-ef6e-496a-8978-53d5e13cc0f2", "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": "cc9eb089-06b8-4839-826e-431fb1e6d6f5", "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": "59199e6d5552719234c7dc11427a8d5e820cc61d46e544fdf9774f2d2a20fdf6", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "585dd9db-c94b-43e8-9e9b-3807c4d4cdc0", "node_type": "1", "metadata": {}, "hash": "8fb98215835a62423081338fd157865f2ac4aec2f2398a4cca63e43bbe0bcc94", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 18373, "end_char_idx": 19977, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
#T_b01a0_row0_col3, #T_b01a0_row1_col0, #T_b01a0_row1_col1, #T_b01a0_row1_col2, #T_b01a0_row1_col3, #T_b01a0_row2_col0, #T_b01a0_row2_col1, #T_b01a0_row2_col2, #T_b01a0_row2_col3, #T_b01a0_row3_col0, #T_b01a0_row3_col1, #T_b01a0_row3_col2, #T_b01a0_row3_col3, #T_b01a0_row4_col0, #T_b01a0_row4_col1, #T_b01a0_row4_col2, #T_b01a0_row4_col3, #T_b01a0_row5_col0, #T_b01a0_row5_col1, #T_b01a0_row5_col2, #T_b01a0_row5_col3, #T_b01a0_row6_col0, #T_b01a0_row6_col1, #T_b01a0_row6_col2, #T_b01a0_row6_col3, #T_b01a0_row7_col0, #T_b01a0_row7_col1, #T_b01a0_row7_col2, #T_b01a0_row7_col3, #T_b01a0_row8_col0, #T_b01a0_row8_col1, #T_b01a0_row8_col2, #T_b01a0_row8_col3, #T_b01a0_row9_col0, #T_b01a0_row9_col1, #T_b01a0_row9_col2, #T_b01a0_row9_col3 {
  background-color: white;
  color: black;
}
</style>
<table id="T_b01a0">
  <thead>
    <tr>
      <th class="blank level0" >&nbsp;</th>
      <th id="T_b01a0_level0_col0" class="col_heading level0 col0" >Prompt</th>
      <th id="T_b01a0_level0_col1" class="col_heading level0 col1" >Actual</th>
      <th id="T_b01a0_level0_col2" class="col_heading level0 col2" >Expected</th>
      <th id="T_b01a0_level0_col3" class="col_heading level0 col3" >Match</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th id="T_b01a0_level0_row0" class="row_heading level0 row0" >0</th>
      <td id="T_b01a0_row0_col0" class="data row0 col0" >Land the drone at the home base</td>
      <td id="T_b01a0_row0_col1" class="data row0 col1" >land_drone</td>
      <td id="T_b01a0_row0_col2" class="data row0 col2" >land_drone</td>
      <td id="T_b01a0_row0_col3" class="data row0


key: _node_content
string_value:
{"id_": "585dd9db-c94b-43e8-9e9b-3807c4d4cdc0", "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": "cbeb5b95-ef6e-496a-8978-53d5e13cc0f2", "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": "35f5e14537a0ec958d37a125b6d915925c971d994f8a6215bb4248417ca9c4a5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a7316417-1f51-4bc7-b271-f62699a9216b", "node_type": "1", "metadata": {}, "hash": "1911d06797c0c5a89e9f69dd933499ad41e3c337eeb6fb78ddc4e0d6e741bb57", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 19053, "end_char_idx": 20806, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
#T_b01a0_row9_col1, #T_b01a0_row9_col2, #T_b01a0_row9_col3 {
  background-color: white;
  color: black;
}
</style>
<table id="T_b01a0">
  <thead>
    <tr>
      <th class="blank level0" >&nbsp;</th>
      <th id="T_b01a0_level0_col0" class="col_heading level0 col0" >Prompt</th>
      <th id="T_b01a0_level0_col1" class="col_heading level0 col1" >Actual</th>
      <th id="T_b01a0_level0_col2" class="col_heading level0 col2" >Expected</th>
      <th id="T_b01a0_level0_col3" class="col_heading level0 col3" >Match</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th id="T_b01a0_level0_row0" class="row_heading level0 row0" >0</th>
      <td id="T_b01a0_row0_col0" class="data row0 col0" >Land the drone at the home base</td>
      <td id="T_b01a0_row0_col1" class="data row0 col1" >land_drone</td>
      <td id="T_b01a0_row0_col2" class="data row0 col2" >land_drone</td>
      <td id="T_b01a0_row0_col3" class="data row0 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_b01a0_level0_row1" class="row_heading level0 row1" >1</th>
      <td id="T_b01a0_row1_col0" class="data row1 col0" >Take off the drone to 50 meters</td>
      <td id="T_b01a0_row1_col1" class="data row1 col1" >takeoff_drone</td>
      <td id="T_b01a0_row1_col2" class="data row1 col2" >takeoff_drone</td>
      <td id="T_b01a0_row1_col3" class="data row1 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_b01a0_level0_row2" class="row_heading level0 row2" >2</th>
      <td id="T_b01a0_row2_col0" class="data row2 col0" >Change speed to 15 kilometers per hour</td>
      <td id="T_b01a0_row2_col1" class="data row2 col1" >set_drone_speed</td>
      <td id="T_b01a0_row2_col2" class="data row2 col2" >set_drone_speed</td>
      <td id="T_b01a0_row2_col3" class="data row2 col3"


key: _node_content
string_value:
{"id_": "a7316417-1f51-4bc7-b271-f62699a9216b", "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": "585dd9db-c94b-43e8-9e9b-3807c4d4cdc0", "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": "1b7b50c1010b3278077e2acb2021ff57feddb5700be1114e8360322bb2e8b0eb", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d7b9747f-7306-4941-b9f5-cd002a3c69d5", "node_type": "1", "metadata": {}, "hash": "5df8c3895d9755ade5293d712eac46cbf30442e3ed3ab1351f82c3ae31a3e69e", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 19934, "end_char_idx": 21643, "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_b01a0_row0_col3" class="data row0 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_b01a0_level0_row1" class="row_heading level0 row1" >1</th>
      <td id="T_b01a0_row1_col0" class="data row1 col0" >Take off the drone to 50 meters</td>
      <td id="T_b01a0_row1_col1" class="data row1 col1" >takeoff_drone</td>
      <td id="T_b01a0_row1_col2" class="data row1 col2" >takeoff_drone</td>
      <td id="T_b01a0_row1_col3" class="data row1 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_b01a0_level0_row2" class="row_heading level0 row2" >2</th>
      <td id="T_b01a0_row2_col0" class="data row2 col0" >Change speed to 15 kilometers per hour</td>
      <td id="T_b01a0_row2_col1" class="data row2 col1" >set_drone_speed</td>
      <td id="T_b01a0_row2_col2" class="data row2 col2" >set_drone_speed</td>
      <td id="T_b01a0_row2_col3" class="data row2 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_b01a0_level0_row3" class="row_heading level0 row3" >3</th>
      <td id="T_b01a0_row3_col0" class="data row3 col0" >Turn into an elephant!</td>
      <td id="T_b01a0_row3_col1" class="data row3 col1" >reject_request</td>
      <td id="T_b01a0_row3_col2" class="data row3 col2" >reject_request</td>
      <td id="T_b01a0_row3_col3" class="data row3 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_b01a0_level0_row4" class="row_heading level0 row4" >4</th>
      <td id="T_b01a0_row4_col0" class="data row4 col0" >Move the drone forward by 10 meters</td>
      <td id="T_b01a0_row4_col1" class="data row4 col1" >control_drone_movement</td>
      <td id="T_b01a0_row4_col2" class="data row4 col2" >control_drone_movement</td>
      <td id="T_b01a0_row4_col3" class="data row4 col3" >Yes</td>


key: _node_content
string_value:
{"id_": "d7b9747f-7306-4941-b9f5-cd002a3c69d5", "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": "a7316417-1f51-4bc7-b271-f62699a9216b", "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": "7903cfc3bc97eb9e516fa519b031ee6a994b81eb545b1a38ddba66a6aeb6b880", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ffddb6c9-42ff-444b-ae4e-a8aa13ef471f", "node_type": "1", "metadata": {}, "hash": "aa0fc8b144e319bf640d4ff196dc7dfbfa42b1a31f654da7ddc681cf69e0d940", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 20757, "end_char_idx": 22489, "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_b01a0_row2_col3" class="data row2 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_b01a0_level0_row3" class="row_heading level0 row3" >3</th>
      <td id="T_b01a0_row3_col0" class="data row3 col0" >Turn into an elephant!</td>
      <td id="T_b01a0_row3_col1" class="data row3 col1" >reject_request</td>
      <td id="T_b01a0_row3_col2" class="data row3 col2" >reject_request</td>
      <td id="T_b01a0_row3_col3" class="data row3 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_b01a0_level0_row4" class="row_heading level0 row4" >4</th>
      <td id="T_b01a0_row4_col0" class="data row4 col0" >Move the drone forward by 10 meters</td>
      <td id="T_b01a0_row4_col1" class="data row4 col1" >control_drone_movement</td>
      <td id="T_b01a0_row4_col2" class="data row4 col2" >control_drone_movement</td>
      <td id="T_b01a0_row4_col3" class="data row4 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_b01a0_level0_row5" class="row_heading level0 row5" >5</th>
      <td id="T_b01a0_row5_col0" class="data row5 col0" >I want the LED display to blink in red</td>
      <td id="T_b01a0_row5_col1" class="data row5 col1" >configure_led_display</td>
      <td id="T_b01a0_row5_col2" class="data row5 col2" >configure_led_display</td>
      <td id="T_b01a0_row5_col3" class="data row5 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_b01a0_level0_row6" class="row_heading level0 row6" >6</th>
      <td id="T_b01a0_row6_col0" class="data row6 col0" >Can you take a photo?</td>
      <td id="T_b01a0_row6_col1" class="data row6 col1" >control_camera</td>
      <td id="T_b01a0_row6_col2" class="data row6 col2" >control_camera</td>
      <td id="T_b01a0_row6_col3" class="data row6 col3" >Yes</td>
    </tr>
    <tr>


key: _node_content
string_value:
{"id_": "ffddb6c9-42ff-444b-ae4e-a8aa13ef471f", "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": "d7b9747f-7306-4941-b9f5-cd002a3c69d5", "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": "6bd069f32e7bdc2705cab8b6f2938799e37e39d79703866f461b739bcd47572a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "df224231-770c-44c6-bf3b-ec8b93059d33", "node_type": "1", "metadata": {}, "hash": "4ad821a896ad716de7bcc5fa03c178fe35bf57796cac05acbca1250db3a88c30", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 21611, "end_char_idx": 23340, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
class="data row4 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_b01a0_level0_row5" class="row_heading level0 row5" >5</th>
      <td id="T_b01a0_row5_col0" class="data row5 col0" >I want the LED display to blink in red</td>
      <td id="T_b01a0_row5_col1" class="data row5 col1" >configure_led_display</td>
      <td id="T_b01a0_row5_col2" class="data row5 col2" >configure_led_display</td>
      <td id="T_b01a0_row5_col3" class="data row5 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_b01a0_level0_row6" class="row_heading level0 row6" >6</th>
      <td id="T_b01a0_row6_col0" class="data row6 col0" >Can you take a photo?</td>
      <td id="T_b01a0_row6_col1" class="data row6 col1" >control_camera</td>
      <td id="T_b01a0_row6_col2" class="data row6 col2" >control_camera</td>
      <td id="T_b01a0_row6_col3" class="data row6 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_b01a0_level0_row7" class="row_heading level0 row7" >7</th>
      <td id="T_b01a0_row7_col0" class="data row7 col0" >Can you detect obstacles?</td>
      <td id="T_b01a0_row7_col1" class="data row7 col1" >set_obstacle_avoidance</td>
      <td id="T_b01a0_row7_col2" class="data row7 col2" >set_obstacle_avoidance</td>
      <td id="T_b01a0_row7_col3" class="data row7 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_b01a0_level0_row8" class="row_heading level0 row8" >8</th>
      <td id="T_b01a0_row8_col0" class="data row8 col0" >Can you dance for me?</td>
      <td id="T_b01a0_row8_col1" class="data row8 col1" >reject_request</td>
      <td id="T_b01a0_row8_col2" class="data row8 col2" >reject_request</td>
      <td id="T_b01a0_row8_col3" class="data row8 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_b01a0_level0_row9"


key: _node_content
string_value:
{"id_": "df224231-770c-44c6-bf3b-ec8b93059d33", "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": "ffddb6c9-42ff-444b-ae4e-a8aa13ef471f", "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": "181912c5b078da0a038b8514e196f3ffa99e49689aa50769dc638e52f5bb7cda", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "934a289d-3097-453a-b032-b06cc58da996", "node_type": "1", "metadata": {}, "hash": "ca0a30934681d4f01a9f388d711abaf886f2efd88cf5d7ca716aea6ed8d47c50", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 22475, "end_char_idx": 24085, "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_b01a0_level0_row7" class="row_heading level0 row7" >7</th>
      <td id="T_b01a0_row7_col0" class="data row7 col0" >Can you detect obstacles?</td>
      <td id="T_b01a0_row7_col1" class="data row7 col1" >set_obstacle_avoidance</td>
      <td id="T_b01a0_row7_col2" class="data row7 col2" >set_obstacle_avoidance</td>
      <td id="T_b01a0_row7_col3" class="data row7 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_b01a0_level0_row8" class="row_heading level0 row8" >8</th>
      <td id="T_b01a0_row8_col0" class="data row8 col0" >Can you dance for me?</td>
      <td id="T_b01a0_row8_col1" class="data row8 col1" >reject_request</td>
      <td id="T_b01a0_row8_col2" class="data row8 col2" >reject_request</td>
      <td id="T_b01a0_row8_col3" class="data row8 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_b01a0_level0_row9" class="row_heading level0 row9" >9</th>
      <td id="T_b01a0_row9_col0" class="data row9 col0" >Can you follow me?</td>
      <td id="T_b01a0_row9_col1" class="data row9 col1" >set_follow_me_mode</td>
      <td id="T_b01a0_row9_col2" class="data row9 col2" >set_follow_me_mode</td>
      <td id="T_b01a0_row9_col3" class="data row9 col3" >Yes</td>
    </tr>
  </tbody>
</table>



    Number of matches: 10 out of 10 (100.00%)
    Average latency per request: 826.81 ms
    Average tokens used per request: 796.20


Nice! The model performs quite well with these requests. Now let's try some more difficult requests: requests that are _almost_ feasible and are drone-related, but that the drone cannot actually do, and the pilot should reject.


key: _node_content
string_value:
{"id_": "934a289d-3097-453a-b032-b06cc58da996", "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": "df224231-770c-44c6-bf3b-ec8b93059d33", "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": "a7275c60449b36aa36443bf2243a5481e78443657d97dacb1aab0ce83dfdac6a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7550d121-d865-4638-8916-aa36501da9e9", "node_type": "1", "metadata": {}, "hash": "5ae6de274178b7a35d3c1c613f406eeb967b80877c973ee33f493144861b36f2", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 23016, "end_char_idx": 25255, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
class="data row8 col0" >Can you dance for me?</td>
      <td id="T_b01a0_row8_col1" class="data row8 col1" >reject_request</td>
      <td id="T_b01a0_row8_col2" class="data row8 col2" >reject_request</td>
      <td id="T_b01a0_row8_col3" class="data row8 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_b01a0_level0_row9" class="row_heading level0 row9" >9</th>
      <td id="T_b01a0_row9_col0" class="data row9 col0" >Can you follow me?</td>
      <td id="T_b01a0_row9_col1" class="data row9 col1" >set_follow_me_mode</td>
      <td id="T_b01a0_row9_col2" class="data row9 col2" >set_follow_me_mode</td>
      <td id="T_b01a0_row9_col3" class="data row9 col3" >Yes</td>
    </tr>
  </tbody>
</table>



    Number of matches: 10 out of 10 (100.00%)
    Average latency per request: 826.81 ms
    Average tokens used per request: 796.20


Nice! The model performs quite well with these requests. Now let's try some more difficult requests: requests that are _almost_ feasible and are drone-related, but that the drone cannot actually do, and the pilot should reject.



```python
challenging_prompts_to_expected = {
    "Play pre-recorded audio message": "reject_request",
    "Initiate following on social media": "reject_request",
    "Scan environment for heat signatures": "reject_request",
    "Bump into obstacles": "reject_request",
    "Change drone's paint job color": "reject_request",
    "Coordinate with nearby drones": "reject_request",
    "Change speed to negative 120 km/h": "reject_request",
    "Detect a person": "reject_request",
    "Please enable night vision": "reject_request",
    "Report on humidity levels around you": "reject_request",
}
```


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


<style type="text/css">
#T_99c20_row0_col0, #T_99c20_row0_col1, #T_99c20_row0_col2, #T_99c20_row0_col3, #T_99c20_row2_col0, #T_99c20_row2_col1, #T_99c20_row2_col2, #T_99c20_row2_col3, #T_99c20_row4_col0, #T_99c20_row4_col1, #T_99c20_row4_col2, #T_99c20_row4_col3, #T_99c20_row5_col0, #T_99c20_row5_col1, #T_99c20_row5_col2,


key: _node_content
string_value:
{"id_": "7550d121-d865-4638-8916-aa36501da9e9", "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": "934a289d-3097-453a-b032-b06cc58da996", "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": "0452174a0659522784d7946f1cb32a69727587589aa49f5f6137a7798cd9195b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "17b33714-fb2d-44e9-a3a4-eeb2f34feab9", "node_type": "1", "metadata": {}, "hash": "03af495ea6d16222415a155b5a22aa29d095af25d4a6dea5c466621c95e78345", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 24089, "end_char_idx": 26085, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
challenging_prompts_to_expected = {
    "Play pre-recorded audio message": "reject_request",
    "Initiate following on social media": "reject_request",
    "Scan environment for heat signatures": "reject_request",
    "Bump into obstacles": "reject_request",
    "Change drone's paint job color": "reject_request",
    "Coordinate with nearby drones": "reject_request",
    "Change speed to negative 120 km/h": "reject_request",
    "Detect a person": "reject_request",
    "Please enable night vision": "reject_request",
    "Report on humidity levels around you": "reject_request",
}
```


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


<style type="text/css">
#T_99c20_row0_col0, #T_99c20_row0_col1, #T_99c20_row0_col2, #T_99c20_row0_col3, #T_99c20_row2_col0, #T_99c20_row2_col1, #T_99c20_row2_col2, #T_99c20_row2_col3, #T_99c20_row4_col0, #T_99c20_row4_col1, #T_99c20_row4_col2, #T_99c20_row4_col3, #T_99c20_row5_col0, #T_99c20_row5_col1, #T_99c20_row5_col2, #T_99c20_row5_col3, #T_99c20_row7_col0, #T_99c20_row7_col1, #T_99c20_row7_col2, #T_99c20_row7_col3, #T_99c20_row9_col0, #T_99c20_row9_col1, #T_99c20_row9_col2, #T_99c20_row9_col3 {
  background-color: white;
  color: black;
}
#T_99c20_row1_col0, #T_99c20_row1_col1, #T_99c20_row1_col2, #T_99c20_row1_col3, #T_99c20_row3_col0, #T_99c20_row3_col1, #T_99c20_row3_col2, #T_99c20_row3_col3, #T_99c20_row6_col0, #T_99c20_row6_col1, #T_99c20_row6_col2, #T_99c20_row6_col3, #T_99c20_row8_col0, #T_99c20_row8_col1, #T_99c20_row8_col2, #T_99c20_row8_col3 {
  background-color: red;
  color: black;
}
</style>
<table id="T_99c20">
  <thead>
    <tr>
      <th class="blank level0" >&nbsp;</th>
      <th id="T_99c20_level0_col0" class="col_heading level0 col0" >Prompt</th>
      <th id="T_99c20_level0_col1" class="col_heading level0 col1"


key: _node_content
string_value:
{"id_": "17b33714-fb2d-44e9-a3a4-eeb2f34feab9", "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": "7550d121-d865-4638-8916-aa36501da9e9", "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": "8d956fc19d4ca539a592671574560ab1a784bd72106841594f979757e0b438ec", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a3ecd328-3fad-4263-948e-51d21bc271f4", "node_type": "1", "metadata": {}, "hash": "af1bc7b99b966e5828a08ad1bb375d0eb7b9fd40274c92e444b476e6af707589", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 25256, "end_char_idx": 26935, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
#T_99c20_row5_col3, #T_99c20_row7_col0, #T_99c20_row7_col1, #T_99c20_row7_col2, #T_99c20_row7_col3, #T_99c20_row9_col0, #T_99c20_row9_col1, #T_99c20_row9_col2, #T_99c20_row9_col3 {
  background-color: white;
  color: black;
}
#T_99c20_row1_col0, #T_99c20_row1_col1, #T_99c20_row1_col2, #T_99c20_row1_col3, #T_99c20_row3_col0, #T_99c20_row3_col1, #T_99c20_row3_col2, #T_99c20_row3_col3, #T_99c20_row6_col0, #T_99c20_row6_col1, #T_99c20_row6_col2, #T_99c20_row6_col3, #T_99c20_row8_col0, #T_99c20_row8_col1, #T_99c20_row8_col2, #T_99c20_row8_col3 {
  background-color: red;
  color: black;
}
</style>
<table id="T_99c20">
  <thead>
    <tr>
      <th class="blank level0" >&nbsp;</th>
      <th id="T_99c20_level0_col0" class="col_heading level0 col0" >Prompt</th>
      <th id="T_99c20_level0_col1" class="col_heading level0 col1" >Actual</th>
      <th id="T_99c20_level0_col2" class="col_heading level0 col2" >Expected</th>
      <th id="T_99c20_level0_col3" class="col_heading level0 col3" >Match</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th id="T_99c20_level0_row0" class="row_heading level0 row0" >0</th>
      <td id="T_99c20_row0_col0" class="data row0 col0" >Play pre-recorded audio message</td>
      <td id="T_99c20_row0_col1" class="data row0 col1" >reject_request</td>
      <td id="T_99c20_row0_col2" class="data row0 col2" >reject_request</td>
      <td id="T_99c20_row0_col3" class="data row0 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_99c20_level0_row1" class="row_heading level0 row1" >1</th>
      <td id="T_99c20_row1_col0" class="data row1 col0" >Initiate following on social media</td>
      <td id="T_99c20_row1_col1" class="data row1 col1"


key: _node_content
string_value:
{"id_": "a3ecd328-3fad-4263-948e-51d21bc271f4", "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": "17b33714-fb2d-44e9-a3a4-eeb2f34feab9", "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": "327528862e86521b2867cdd982cfcd3b842b423384b1083a3ea33480bd8797fc", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f7457166-baee-406c-a8f1-4919d42985b4", "node_type": "1", "metadata": {}, "hash": "2dab33f6d940bf817ce791cd8e35166c8f37ccccf1df387c4733152144a00ada", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 26025, "end_char_idx": 27786, "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_99c20_level0_col1" class="col_heading level0 col1" >Actual</th>
      <th id="T_99c20_level0_col2" class="col_heading level0 col2" >Expected</th>
      <th id="T_99c20_level0_col3" class="col_heading level0 col3" >Match</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th id="T_99c20_level0_row0" class="row_heading level0 row0" >0</th>
      <td id="T_99c20_row0_col0" class="data row0 col0" >Play pre-recorded audio message</td>
      <td id="T_99c20_row0_col1" class="data row0 col1" >reject_request</td>
      <td id="T_99c20_row0_col2" class="data row0 col2" >reject_request</td>
      <td id="T_99c20_row0_col3" class="data row0 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_99c20_level0_row1" class="row_heading level0 row1" >1</th>
      <td id="T_99c20_row1_col0" class="data row1 col0" >Initiate following on social media</td>
      <td id="T_99c20_row1_col1" class="data row1 col1" >set_follow_me_mode</td>
      <td id="T_99c20_row1_col2" class="data row1 col2" >reject_request</td>
      <td id="T_99c20_row1_col3" class="data row1 col3" >No</td>
    </tr>
    <tr>
      <th id="T_99c20_level0_row2" class="row_heading level0 row2" >2</th>
      <td id="T_99c20_row2_col0" class="data row2 col0" >Scan environment for heat signatures</td>
      <td id="T_99c20_row2_col1" class="data row2 col1" >reject_request</td>
      <td id="T_99c20_row2_col2" class="data row2 col2" >reject_request</td>
      <td id="T_99c20_row2_col3" class="data row2 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_99c20_level0_row3" class="row_heading level0 row3" >3</th>
      <td id="T_99c20_row3_col0" class="data row3 col0" >Bump into obstacles</td>
      <td id="T_99c20_row3_col1" class="data row3 col1" >set_obstacle_avoidance</td>
      <td


key: _node_content
string_value:
{"id_": "f7457166-baee-406c-a8f1-4919d42985b4", "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": "a3ecd328-3fad-4263-948e-51d21bc271f4", "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": "6ce1e7897a4a19e0f1cebe41919ac4a660fe99f53d8144e45bac502695a98655", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5c17690f-650b-4650-a77d-60eefbec271d", "node_type": "1", "metadata": {}, "hash": "533ba1fa91c68ed807c404625ba14c81fc56e53430eb4c8484e9bc13a3389901", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 26886, "end_char_idx": 28633, "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_99c20_row1_col1" class="data row1 col1" >set_follow_me_mode</td>
      <td id="T_99c20_row1_col2" class="data row1 col2" >reject_request</td>
      <td id="T_99c20_row1_col3" class="data row1 col3" >No</td>
    </tr>
    <tr>
      <th id="T_99c20_level0_row2" class="row_heading level0 row2" >2</th>
      <td id="T_99c20_row2_col0" class="data row2 col0" >Scan environment for heat signatures</td>
      <td id="T_99c20_row2_col1" class="data row2 col1" >reject_request</td>
      <td id="T_99c20_row2_col2" class="data row2 col2" >reject_request</td>
      <td id="T_99c20_row2_col3" class="data row2 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_99c20_level0_row3" class="row_heading level0 row3" >3</th>
      <td id="T_99c20_row3_col0" class="data row3 col0" >Bump into obstacles</td>
      <td id="T_99c20_row3_col1" class="data row3 col1" >set_obstacle_avoidance</td>
      <td id="T_99c20_row3_col2" class="data row3 col2" >reject_request</td>
      <td id="T_99c20_row3_col3" class="data row3 col3" >No</td>
    </tr>
    <tr>
      <th id="T_99c20_level0_row4" class="row_heading level0 row4" >4</th>
      <td id="T_99c20_row4_col0" class="data row4 col0" >Change drone's paint job color</td>
      <td id="T_99c20_row4_col1" class="data row4 col1" >reject_request</td>
      <td id="T_99c20_row4_col2" class="data row4 col2" >reject_request</td>
      <td id="T_99c20_row4_col3" class="data row4 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_99c20_level0_row5" class="row_heading level0 row5" >5</th>
      <td id="T_99c20_row5_col0" class="data row5 col0" >Coordinate with nearby drones</td>
      <td id="T_99c20_row5_col1" class="data row5 col1" >reject_request</td>
      <td id="T_99c20_row5_col2" class="data


key: _node_content
string_value:
{"id_": "5c17690f-650b-4650-a77d-60eefbec271d", "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": "f7457166-baee-406c-a8f1-4919d42985b4", "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": "614ba95529fc5cbb28096cc57baa7a399460aa33a1e9d3a68e86fe4a130777fb", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b029c671-3ef8-4fec-9e3b-553235110c51", "node_type": "1", "metadata": {}, "hash": "1eeb26238f8dec1ced8908ddf5e8c315638e008826587755e963360436c0b798", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 27725, "end_char_idx": 29467, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
class="data row3 col1" >set_obstacle_avoidance</td>
      <td id="T_99c20_row3_col2" class="data row3 col2" >reject_request</td>
      <td id="T_99c20_row3_col3" class="data row3 col3" >No</td>
    </tr>
    <tr>
      <th id="T_99c20_level0_row4" class="row_heading level0 row4" >4</th>
      <td id="T_99c20_row4_col0" class="data row4 col0" >Change drone's paint job color</td>
      <td id="T_99c20_row4_col1" class="data row4 col1" >reject_request</td>
      <td id="T_99c20_row4_col2" class="data row4 col2" >reject_request</td>
      <td id="T_99c20_row4_col3" class="data row4 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_99c20_level0_row5" class="row_heading level0 row5" >5</th>
      <td id="T_99c20_row5_col0" class="data row5 col0" >Coordinate with nearby drones</td>
      <td id="T_99c20_row5_col1" class="data row5 col1" >reject_request</td>
      <td id="T_99c20_row5_col2" class="data row5 col2" >reject_request</td>
      <td id="T_99c20_row5_col3" class="data row5 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_99c20_level0_row6" class="row_heading level0 row6" >6</th>
      <td id="T_99c20_row6_col0" class="data row6 col0" >Change speed to negative 120 km/h</td>
      <td id="T_99c20_row6_col1" class="data row6 col1" >set_drone_speed</td>
      <td id="T_99c20_row6_col2" class="data row6 col2" >reject_request</td>
      <td id="T_99c20_row6_col3" class="data row6 col3" >No</td>
    </tr>
    <tr>
      <th id="T_99c20_level0_row7" class="row_heading level0 row7" >7</th>
      <td id="T_99c20_row7_col0" class="data row7 col0" >Detect a person</td>
      <td id="T_99c20_row7_col1" class="data row7 col1" >reject_request</td>
      <td id="T_99c20_row7_col2" class="data row7 col2" >reject_request</td>


key: _node_content
string_value:
{"id_": "b029c671-3ef8-4fec-9e3b-553235110c51", "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": "5c17690f-650b-4650-a77d-60eefbec271d", "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": "fdbae09f9a3daa588c0c0d94b1ab2d14c9d08d0ac7001d5c48c5dfc2e0e88cf0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "da28f872-ba51-47da-be43-233a1983689f", "node_type": "1", "metadata": {}, "hash": "0dda9a47d6099a5e419e46c1004c5654aac18507d2f806789c136402ca2fa325", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 28595, "end_char_idx": 30296, "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_99c20_row5_col2" class="data row5 col2" >reject_request</td>
      <td id="T_99c20_row5_col3" class="data row5 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_99c20_level0_row6" class="row_heading level0 row6" >6</th>
      <td id="T_99c20_row6_col0" class="data row6 col0" >Change speed to negative 120 km/h</td>
      <td id="T_99c20_row6_col1" class="data row6 col1" >set_drone_speed</td>
      <td id="T_99c20_row6_col2" class="data row6 col2" >reject_request</td>
      <td id="T_99c20_row6_col3" class="data row6 col3" >No</td>
    </tr>
    <tr>
      <th id="T_99c20_level0_row7" class="row_heading level0 row7" >7</th>
      <td id="T_99c20_row7_col0" class="data row7 col0" >Detect a person</td>
      <td id="T_99c20_row7_col1" class="data row7 col1" >reject_request</td>
      <td id="T_99c20_row7_col2" class="data row7 col2" >reject_request</td>
      <td id="T_99c20_row7_col3" class="data row7 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_99c20_level0_row8" class="row_heading level0 row8" >8</th>
      <td id="T_99c20_row8_col0" class="data row8 col0" >Please enable night vision</td>
      <td id="T_99c20_row8_col1" class="data row8 col1" >set_drone_lighting</td>
      <td id="T_99c20_row8_col2" class="data row8 col2" >reject_request</td>
      <td id="T_99c20_row8_col3" class="data row8 col3" >No</td>
    </tr>
    <tr>
      <th id="T_99c20_level0_row9" class="row_heading level0 row9" >9</th>
      <td id="T_99c20_row9_col0" class="data row9 col0" >Report on humidity levels around you</td>
      <td id="T_99c20_row9_col1" class="data row9 col1" >reject_request</td>
      <td id="T_99c20_row9_col2" class="data row9 col2" >reject_request</td>
      <td


key: _node_content
string_value:
{"id_": "da28f872-ba51-47da-be43-233a1983689f", "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": "b029c671-3ef8-4fec-9e3b-553235110c51", "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": "5a2b532ae65617ee3c9dd975e152d7b7354f60d53fbd30ee1419c6c63b2bda71", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "dfe14c26-f6bc-49b4-a200-8887070ba5d9", "node_type": "1", "metadata": {}, "hash": "e929d6833418b0c3ac4cb65ebfb1329b88059ea2806617bd3fe5f6c182161f64", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 29397, "end_char_idx": 31942, "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_99c20_row7_col2" class="data row7 col2" >reject_request</td>
      <td id="T_99c20_row7_col3" class="data row7 col3" >Yes</td>
    </tr>
    <tr>
      <th id="T_99c20_level0_row8" class="row_heading level0 row8" >8</th>
      <td id="T_99c20_row8_col0" class="data row8 col0" >Please enable night vision</td>
      <td id="T_99c20_row8_col1" class="data row8 col1" >set_drone_lighting</td>
      <td id="T_99c20_row8_col2" class="data row8 col2" >reject_request</td>
      <td id="T_99c20_row8_col3" class="data row8 col3" >No</td>
    </tr>
    <tr>
      <th id="T_99c20_level0_row9" class="row_heading level0 row9" >9</th>
      <td id="T_99c20_row9_col0" class="data row9 col0" >Report on humidity levels around you</td>
      <td id="T_99c20_row9_col1" class="data row9 col1" >reject_request</td>
      <td id="T_99c20_row9_col2" class="data row9 col2" >reject_request</td>
      <td id="T_99c20_row9_col3" class="data row9 col3" >Yes</td>
    </tr>
  </tbody>
</table>



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


Now we run into some problems.
The model here should reject all of these requests, as they are impossible/conflicting/ambiguous given the functions, however instead the model calls functions that are somewhat related to the request, but incorrect. For example, the model sets follow_me_mode when asked to initiate following on social media.

<br>
In this simple case, more prompt engineering may resolve some of these issues, but for the purpose of this example we will demonstrate how fine tuning can be used to improve performance. Additionally, while this case is relatively straightforward, as the number of and complexity of the functions increases, fine tuning becomes more and more impactful.

Again, our goal here is to improve performance and use less tokens, so fine-tuning allows us to:

- Omit function and parameter descriptions: remove the description field from function and parameters
- Omit parameters: remove the entire properties field from the parameters object
- Omit function entirely: remove the entire function object from the functions array


# Generating synthetic data


### Helper functions


We want to generate every invocation of every function, so that we have
full coverage of all potential invocations to create synthetic data for. Then, we will use `gpt-4o` to come up with prompts that would call each invocation, and we will use that prompt - function invocation pair as training data.


key: _node_content
string_value:
{"id_": "dfe14c26-f6bc-49b4-a200-8887070ba5d9", "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": "da28f872-ba51-47da-be43-233a1983689f", "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": "fb5c5a2b1e3527a7ba47e7d575126e9947afcd8bd93c2a3d0b541569bb028fd1", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f4ca57c5-4d4a-40b9-9f0d-ad761aa11851", "node_type": "1", "metadata": {}, "hash": "edc60e07775f0fecace101e6faa2dc2387528bf4072d4b8fd85b8747821d105d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 30189, "end_char_idx": 33378, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
>reject_request</td>
      <td id="T_99c20_row9_col2" class="data row9 col2" >reject_request</td>
      <td id="T_99c20_row9_col3" class="data row9 col3" >Yes</td>
    </tr>
  </tbody>
</table>



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


Now we run into some problems.
The model here should reject all of these requests, as they are impossible/conflicting/ambiguous given the functions, however instead the model calls functions that are somewhat related to the request, but incorrect. For example, the model sets follow_me_mode when asked to initiate following on social media.

<br>
In this simple case, more prompt engineering may resolve some of these issues, but for the purpose of this example we will demonstrate how fine tuning can be used to improve performance. Additionally, while this case is relatively straightforward, as the number of and complexity of the functions increases, fine tuning becomes more and more impactful.

Again, our goal here is to improve performance and use less tokens, so fine-tuning allows us to:

- Omit function and parameter descriptions: remove the description field from function and parameters
- Omit parameters: remove the entire properties field from the parameters object
- Omit function entirely: remove the entire function object from the functions array


# Generating synthetic data


### Helper functions


We want to generate every invocation of every function, so that we have
full coverage of all potential invocations to create synthetic data for. Then, we will use `gpt-4o` to come up with prompts that would call each invocation, and we will use that prompt - function invocation pair as training data.


Generating every invocation for a function with fixed enums is more simple, but for a function such as
`control_gimbal` we need to set the `tilt` and `pan` integer values, so to generate those synthetic invocations we will first set a placeholder, and then later use `gpt-4o` to come up with reasonable values.



```python
placeholder_int = "fill_in_int"
placeholder_string = "fill_in_string"
```

The functions below take in all the functions from the function list, and look
at all the potential invocations of those functions given each function's parameters.
The functions also account for `required` parameters, so that all the invocations
are actually feasible.



```python
def generate_permutations(
    params: Dict[str, Dict[str, Any]]
) -> Generator[Dict[str, Any], None, None]:
    """
    Generates all possible permutations for given parameters.

    :param params: Parameter dictionary containing required and optional fields.
    :return: A generator yielding each permutation.
    """

    # Extract the required fields from the parameters
    required_fields = params.get("required", [])

    # Generate permutations for required fields
    required_permutations = generate_required_permutations(params, required_fields)

    # Generate optional permutations based on each required permutation
    for required_perm in required_permutations:
        yield from generate_optional_permutations(params, required_perm)


key: _node_content
string_value:
{"id_": "f4ca57c5-4d4a-40b9-9f0d-ad761aa11851", "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": "dfe14c26-f6bc-49b4-a200-8887070ba5d9", "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": "2168a568d6327f4254aaf24b76760e2e644736d55be744fede6aadb952fd2f2c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b4307cad-b5b4-4737-8a0c-a496265b20de", "node_type": "1", "metadata": {}, "hash": "0936691a0f4e7bbb6a8a0669b6e1810241cc3ae7a52d47f7672469ca732468ee", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 31588, "end_char_idx": 35246, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Generating synthetic data


### Helper functions


We want to generate every invocation of every function, so that we have
full coverage of all potential invocations to create synthetic data for. Then, we will use `gpt-4o` to come up with prompts that would call each invocation, and we will use that prompt - function invocation pair as training data.


Generating every invocation for a function with fixed enums is more simple, but for a function such as
`control_gimbal` we need to set the `tilt` and `pan` integer values, so to generate those synthetic invocations we will first set a placeholder, and then later use `gpt-4o` to come up with reasonable values.



```python
placeholder_int = "fill_in_int"
placeholder_string = "fill_in_string"
```

The functions below take in all the functions from the function list, and look
at all the potential invocations of those functions given each function's parameters.
The functions also account for `required` parameters, so that all the invocations
are actually feasible.



```python
def generate_permutations(
    params: Dict[str, Dict[str, Any]]
) -> Generator[Dict[str, Any], None, None]:
    """
    Generates all possible permutations for given parameters.

    :param params: Parameter dictionary containing required and optional fields.
    :return: A generator yielding each permutation.
    """

    # Extract the required fields from the parameters
    required_fields = params.get("required", [])

    # Generate permutations for required fields
    required_permutations = generate_required_permutations(params, required_fields)

    # Generate optional permutations based on each required permutation
    for required_perm in required_permutations:
        yield from generate_optional_permutations(params, required_perm)


def generate_required_permutations(
    params: Dict[str, Dict[str, Any]], required_fields: List[str]
) -> List[Dict[str, Any]]:
    """
    Generates permutations for the required fields.

    :param params: Parameter dictionary.
    :param required_fields: List of required fields.
    :return: A list of permutations for required fields.
    """

    # Get all possible values for each required field
    required_values = [get_possible_values(params, field) for field in required_fields]

    # Generate permutations from possible values
    return [
        dict(zip(required_fields, values))
        for values in itertools.product(*required_values)
    ]


def generate_optional_permutations(
    params: Dict[str, Dict[str, Any]], base_perm: Dict[str, Any]
) -> Generator[Dict[str, Any], None, None]:
    """
    Generates permutations for optional fields based on a base permutation.

    :param params: Parameter dictionary.
    :param base_perm: Base permutation dictionary.
    :return: A generator yielding each permutation for optional fields.
    """

    # Determine the fields that are optional by subtracting the base permutation's fields from all properties
    optional_fields = set(params["properties"]) - set(base_perm)

    # Iterate through all combinations of optional fields
    for field_subset in itertools.chain.from_iterable(
        itertools.combinations(optional_fields, r)
        for r in range(len(optional_fields) + 1)
    ):

        # Generate product of possible values for the current subset of fields
        for values in itertools.product(
            *(get_possible_values(params, field) for field in field_subset)
        ):

            # Create a new permutation by combining base permutation and current field values
            new_perm = {**base_perm, **dict(zip(field_subset, values))}

            yield new_perm


key: _node_content
string_value:
{"id_": "b4307cad-b5b4-4737-8a0c-a496265b20de", "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": "f4ca57c5-4d4a-40b9-9f0d-ad761aa11851", "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": "7d26730f425b2b6d020fe2d329e4946d25785add171a35e4a5bb994e30825f28", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a43fc809-886c-467f-8b00-b204c500cac6", "node_type": "1", "metadata": {}, "hash": "9ae34d082576d9658dcf480809ba14cfa083c7531ab1b609a59c8979c2f4d6a5", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 33381, "end_char_idx": 36449, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
def generate_required_permutations(
    params: Dict[str, Dict[str, Any]], required_fields: List[str]
) -> List[Dict[str, Any]]:
    """
    Generates permutations for the required fields.

    :param params: Parameter dictionary.
    :param required_fields: List of required fields.
    :return: A list of permutations for required fields.
    """

    # Get all possible values for each required field
    required_values = [get_possible_values(params, field) for field in required_fields]

    # Generate permutations from possible values
    return [
        dict(zip(required_fields, values))
        for values in itertools.product(*required_values)
    ]


def generate_optional_permutations(
    params: Dict[str, Dict[str, Any]], base_perm: Dict[str, Any]
) -> Generator[Dict[str, Any], None, None]:
    """
    Generates permutations for optional fields based on a base permutation.

    :param params: Parameter dictionary.
    :param base_perm: Base permutation dictionary.
    :return: A generator yielding each permutation for optional fields.
    """

    # Determine the fields that are optional by subtracting the base permutation's fields from all properties
    optional_fields = set(params["properties"]) - set(base_perm)

    # Iterate through all combinations of optional fields
    for field_subset in itertools.chain.from_iterable(
        itertools.combinations(optional_fields, r)
        for r in range(len(optional_fields) + 1)
    ):

        # Generate product of possible values for the current subset of fields
        for values in itertools.product(
            *(get_possible_values(params, field) for field in field_subset)
        ):

            # Create a new permutation by combining base permutation and current field values
            new_perm = {**base_perm, **dict(zip(field_subset, values))}

            yield new_perm


def get_possible_values(params: Dict[str, Dict[str, Any]], field: str) -> List[Any]:
    """
    Retrieves possible values for a given field.

    :param params: Parameter dictionary.
    :param field: The field for which to get possible values.
    :return: A list of possible values.
    """

    # Extract field information from the parameters
    field_info = params["properties"][field]

    # Based on the field's type or presence of 'enum', determine and return the possible values
    if "enum" in field_info:
        return field_info["enum"]
    elif field_info["type"] == "integer":
        return [placeholder_int]
    elif field_info["type"] == "string":
        return [placeholder_string]
    elif field_info["type"] == "boolean":
        return [True, False]
    elif field_info["type"] == "array" and "enum" in field_info["items"]:
        enum_values = field_info["items"]["enum"]
        all_combinations = [
            list(combo)
            for i in range(1, len(enum_values) + 1)
            for combo in itertools.combinations(enum_values, i)
        ]
        return all_combinations
    return []
```

### Let's generate every invocation for every function first


Prompts:


key: _node_content
string_value:
{"id_": "a43fc809-886c-467f-8b00-b204c500cac6", "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": "b4307cad-b5b4-4737-8a0c-a496265b20de", "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": "03b9bae3866dfa324ce544f89d49d620fb536d746c4b5c0281425d7a2197e7ed", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "007e1a29-7ba7-4c31-9ebb-64f1326a3580", "node_type": "1", "metadata": {}, "hash": "e405244e7d1b5bf45c3de5391ab1c59e1542ccf86725cedafd2bf158f8583767", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 35249, "end_char_idx": 37219, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
def get_possible_values(params: Dict[str, Dict[str, Any]], field: str) -> List[Any]:
    """
    Retrieves possible values for a given field.

    :param params: Parameter dictionary.
    :param field: The field for which to get possible values.
    :return: A list of possible values.
    """

    # Extract field information from the parameters
    field_info = params["properties"][field]

    # Based on the field's type or presence of 'enum', determine and return the possible values
    if "enum" in field_info:
        return field_info["enum"]
    elif field_info["type"] == "integer":
        return [placeholder_int]
    elif field_info["type"] == "string":
        return [placeholder_string]
    elif field_info["type"] == "boolean":
        return [True, False]
    elif field_info["type"] == "array" and "enum" in field_info["items"]:
        enum_values = field_info["items"]["enum"]
        all_combinations = [
            list(combo)
            for i in range(1, len(enum_values) + 1)
            for combo in itertools.combinations(enum_values, i)
        ]
        return all_combinations
    return []
```

### Let's generate every invocation for every function first


Prompts:



```python
INVOCATION_FILLER_PROMPT = """
1) Input reasonable values for 'fill_in_string' and 'fill_in_int' in the invocation here: {invocation}. Reasonable values are determined by the function definition. Use the
the entire function provided here :{function} to get context over what proper fill_in_string and fill_in_int values would be.
Example:

Input: invocation: {{
    "name": "control_camera",
    "arguments": {{
      "mode":"video",
      "duration":"fill_in_int"
    }}
}},
function:{function}

Output: invocation: {{
    "name": "control_camera",
    "arguments": {{
      "mode":"video",
      "duration": 30
    }}
}}


MAKE SURE output is just a dictionary with keys 'name' and 'arguments', no other text or response.

Input: {invocation}
Output:
"""


key: _node_content
string_value:
{"id_": "007e1a29-7ba7-4c31-9ebb-64f1326a3580", "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": "a43fc809-886c-467f-8b00-b204c500cac6", "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": "ba6247c89332040bfd095e595099b41d5e7e8648e13210fb28ae19f2d0c316de", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "327dd5f0-db96-4fbc-a639-d10a06d4bbf4", "node_type": "1", "metadata": {}, "hash": "27808f73badd61967c9fdf7f853e4e71bf6186e93700ed7e139d3891994dd25b", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 36441, "end_char_idx": 39018, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Prompts:



```python
INVOCATION_FILLER_PROMPT = """
1) Input reasonable values for 'fill_in_string' and 'fill_in_int' in the invocation here: {invocation}. Reasonable values are determined by the function definition. Use the
the entire function provided here :{function} to get context over what proper fill_in_string and fill_in_int values would be.
Example:

Input: invocation: {{
    "name": "control_camera",
    "arguments": {{
      "mode":"video",
      "duration":"fill_in_int"
    }}
}},
function:{function}

Output: invocation: {{
    "name": "control_camera",
    "arguments": {{
      "mode":"video",
      "duration": 30
    }}
}}


MAKE SURE output is just a dictionary with keys 'name' and 'arguments', no other text or response.

Input: {invocation}
Output:
"""


COMMAND_GENERATION_PROMPT = """
You are to output 2 commands, questions or statements that would generate the inputted function and parameters.
Please make the commands or questions natural, as a person would ask, and the command or questions should be varied and not repetitive.
It should not always mirror the exact technical terminology used in the function and parameters, rather reflect a conversational and intuitive request.
For instance, the prompt should not be 'turn on the dome light', as that is too technical, but rather 'turn on the inside lights'.
Another example, is the prompt should not be 'turn on the HVAC', but rather 'turn on the air conditioning'. Use language a normal driver would use, even if
it is technically incorrect but colloquially used.

RULES: ALWAYS put a backwards slash before an apostrophe or single quote '. For example, do not say don't but say don\'t.
Prompts MUST be in double quotes as well.

Example

Input: {{'name': 'calibrate_sensors','arguments': {{}}'' }}
Prompt: ["The sensors are out of whack, can you reset them", "The calibration of the drone is off, fix it please!"]

Input: {{'name': 'set_autopilot','arguments': {{'status': 'off'}}}}
Prompt: ["OK, I want to take back pilot control now","Turn off the automatic pilot I'm ready control it"]

Input: {invocation}
Prompt:
"""
```

In the below snippet, we generate the invocation of each function except for the `reject_request` function.

To perform effective fine-tuning we need correctly labeled data. We could manually come up with examples and label the data,\
or we can generate synthetic data with the help of `gpt-4o` <br>

Empirically, `gpt-4o` needs a bit more help to get good realistic examples of prompts that would generate the `reject_request` function, so we'll do that next...


key: _node_content
string_value:
{"id_": "327dd5f0-db96-4fbc-a639-d10a06d4bbf4", "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": "007e1a29-7ba7-4c31-9ebb-64f1326a3580", "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": "1b10ea48a70e1d61c53569911575e83d08dad64ceb539bd4787c028211640748", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "da14ca42-3a4e-42ae-8792-6f39c46d50ea", "node_type": "1", "metadata": {}, "hash": "c91e70ffb9d8ebcf471eeede5800b903e6d6b946e0ecfdb58cfd9d92c9a1948e", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 39022, "end_char_idx": 42152, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
input_objects = []
all_but_reject = [f for f in function_list if f.get("name") != "reject_request"]

for function in all_but_reject:
    func_name = function["function"]["name"]
    params = function["function"]["parameters"]
    for arguments in generate_permutations(params):
        if any(val in arguments.values() for val in ["fill_in_int", "fill_in_str"]):
            input_object = {"name": func_name, "arguments": arguments}
            messages = [
                {
                    "role": "user",
                    "content": INVOCATION_FILLER_PROMPT.format(
                        invocation=str(input_object), function=function
                    ),
                }
            ]
            input_object, usage = get_chat_completion(
                model="gpt-4o", messages=messages, max_tokens=200, temperature=0.1
            ).content
        else:
            input_object = {"name": func_name, "arguments": arguments}

        input_objects.append(input_object)
```

Now that we have all the invocations, let's use `gpt-4o` to generate prompts that would result in those invocations



```python
def remove_sequences(input_string):
    # Replace the specific sequences with an empty string
    cleaned_string = input_string.replace("```json", "")  # Remove "```json" first
    cleaned_string = cleaned_string.replace("```", "")  # Then remove "```"
    return json.loads(cleaned_string)
```


```python
def create_commands(invocation_list):
    example_list = []
    for i, invocation in enumerate(invocation_list):
        if i < 100:
            print(
                f"\033[34m{np.round(100*i/len(invocation_list),1)}% complete\033[0m")
            if type(invocation) == str or "json" in invocation:
                invocation = remove_sequences(invocation)
            print(invocation)

        # Format the prompt with the invocation string
        request_prompt = COMMAND_GENERATION_PROMPT.format(
            invocation=invocation)

        messages = [{"role": "user", "content": f"{request_prompt}"}]
        completion, usage = get_chat_completion(messages, temperature=0.8)
        command_dict = {"Input": invocation, "Prompt": completion.content}
        example_list.append(command_dict)
    return example_list
```


```python
# Only printing the first 10 rows
training_examples_unformatted = create_commands(input_objects)
```

    [34m0.0% complete[0m
    {'name': 'takeoff_drone', 'arguments': {'altitude': 100}}
    [34m1.8% complete[0m
    {'name': 'land_drone', 'arguments': {'location': 'current'}}
    [34m3.5% complete[0m
    {'name': 'land_drone', 'arguments': {'location': 'home_base'}}
    [34m5.3% complete[0m
    {'name': 'land_drone', 'arguments': {'location': 'custom'}}
    [34m7.0% complete[0m
    {'name': 'control_drone_movement', 'arguments': {'direction': 'forward', 'distance': 100}}
    [34m8.8% complete[0m
    {'name': 'control_drone_movement', 'arguments': {'direction': 'backward', 'distance': 50}}
    [34m10.5% complete[0m
    {'name': 'control_drone_movement', 'arguments': {'direction': 'left', 'distance': 10}}
    [34m12.


key: _node_content
string_value:
{"id_": "da14ca42-3a4e-42ae-8792-6f39c46d50ea", "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": "327dd5f0-db96-4fbc-a639-d10a06d4bbf4", "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": "a5c40e32e4d954b6b1b2a58ce307c105de01089f5d2b04a01b96399c798d7986", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "72bd030a-0ef6-4a6a-b183-b08a654900c4", "node_type": "1", "metadata": {}, "hash": "43d820f3573b22bb1ff0913f29f2469154782b2720148138ce6014135eb6a2fc", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 41299, "end_char_idx": 43528, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
# Only printing the first 10 rows
training_examples_unformatted = create_commands(input_objects)
```

    [34m0.0% complete[0m
    {'name': 'takeoff_drone', 'arguments': {'altitude': 100}}
    [34m1.8% complete[0m
    {'name': 'land_drone', 'arguments': {'location': 'current'}}
    [34m3.5% complete[0m
    {'name': 'land_drone', 'arguments': {'location': 'home_base'}}
    [34m5.3% complete[0m
    {'name': 'land_drone', 'arguments': {'location': 'custom'}}
    [34m7.0% complete[0m
    {'name': 'control_drone_movement', 'arguments': {'direction': 'forward', 'distance': 100}}
    [34m8.8% complete[0m
    {'name': 'control_drone_movement', 'arguments': {'direction': 'backward', 'distance': 50}}
    [34m10.5% complete[0m
    {'name': 'control_drone_movement', 'arguments': {'direction': 'left', 'distance': 10}}
    [34m12.3% complete[0m
    {'name': 'control_drone_movement', 'arguments': {'direction': 'right', 'distance': 10}}
    [34m14.0% complete[0m
    {'name': 'control_drone_movement', 'arguments': {'direction': 'up', 'distance': 10}}
    [34m15.8% complete[0m
    {'name': 'control_drone_movement', 'arguments': {'direction': 'down', 'distance': 10}}
    [34m17.5% complete[0m
    {'name': 'set_drone_speed', 'arguments': {'speed': 10}}
    [34m19.3% complete[0m
    {'name': 'control_camera', 'arguments': {'mode': 'photo'}}
    [34m21.1% complete[0m
    {'name': 'control_camera', 'arguments': {'mode': 'photo', 'duration': 10}}
    [34m22.8% complete[0m
    {'name': 'control_camera', 'arguments': {'mode': 'video'}}
    [34m24.6% complete[0m
    {'name': 'control_camera', 'arguments': {'mode': 'video', 'duration': 60}}
    [34m26.3% complete[0m
    {'name': 'control_camera', 'arguments': {'mode': 'panorama'}}
    [34m28.1% complete[0m
    {'name': 'control_camera', 'arguments': {'mode': 'panorama', 'duration': 60}}
    [34m29.8% complete[0m
    {'name': 'control_gimbal', 'arguments': {'tilt': 45, 'pan': 90}}
    [34m31.6% complete[0m
    {'name': 'set_drone_lighting', 'arguments': {'mode': 'on'}}
    [34m33.3% complete[0m
    {'name': 'set_drone_lighting', 'arguments': {'mode': 'off'}}
    [34m35.1% complete[0m
    {'name': 'set_drone_lighting',


key: _node_content
string_value:
{"id_": "72bd030a-0ef6-4a6a-b183-b08a654900c4", "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": "da14ca42-3a4e-42ae-8792-6f39c46d50ea", "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": "5b01f7528d7cc94fd22c5ff07905d975d79c80780ce6450f2046967ab5e14230", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "61cb2203-1dee-4d29-b70d-d969208fa932", "node_type": "1", "metadata": {}, "hash": "008e2e7517cc10270fed48e49c79476a09012fc2428b66838e9d5c8ded11f1c7", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 42444, "end_char_idx": 44579, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
'arguments': {'direction': 'down', 'distance': 10}}
    [34m17.5% complete[0m
    {'name': 'set_drone_speed', 'arguments': {'speed': 10}}
    [34m19.3% complete[0m
    {'name': 'control_camera', 'arguments': {'mode': 'photo'}}
    [34m21.1% complete[0m
    {'name': 'control_camera', 'arguments': {'mode': 'photo', 'duration': 10}}
    [34m22.8% complete[0m
    {'name': 'control_camera', 'arguments': {'mode': 'video'}}
    [34m24.6% complete[0m
    {'name': 'control_camera', 'arguments': {'mode': 'video', 'duration': 60}}
    [34m26.3% complete[0m
    {'name': 'control_camera', 'arguments': {'mode': 'panorama'}}
    [34m28.1% complete[0m
    {'name': 'control_camera', 'arguments': {'mode': 'panorama', 'duration': 60}}
    [34m29.8% complete[0m
    {'name': 'control_gimbal', 'arguments': {'tilt': 45, 'pan': 90}}
    [34m31.6% complete[0m
    {'name': 'set_drone_lighting', 'arguments': {'mode': 'on'}}
    [34m33.3% complete[0m
    {'name': 'set_drone_lighting', 'arguments': {'mode': 'off'}}
    [34m35.1% complete[0m
    {'name': 'set_drone_lighting', 'arguments': {'mode': 'blink'}}
    [34m36.8% complete[0m
    {'name': 'set_drone_lighting', 'arguments': {'mode': 'sos'}}
    [34m38.6% complete[0m
    {'name': 'return_to_home', 'arguments': {}}
    [34m40.4% complete[0m
    {'name': 'set_battery_saver_mode', 'arguments': {'status': 'on'}}
    [34m42.1% complete[0m
    {'name': 'set_battery_saver_mode', 'arguments': {'status': 'off'}}
    [34m43.9% complete[0m
    {'name': 'set_obstacle_avoidance', 'arguments': {'mode': 'on'}}
    [34m45.6% complete[0m
    {'name': 'set_obstacle_avoidance', 'arguments': {'mode': 'off'}}
    [34m47.4% complete[0m
    {'name': 'set_follow_me_mode', 'arguments': {'status': 'on'}}
    [34m49.1% complete[0m
    {'name': 'set_follow_me_mode', 'arguments': {'status': 'off'}}
    [34m50.9% complete[0m
    {'name': 'calibrate_sensors', 'arguments': {}}
    [34m52.6% complete[0m
    {'name': 'set_autopilot', 'arguments': {'status': 'on'}}
    [34m54.4% complete[0m
    {'name': 'set_autopilot', 'arguments': {'status': 'off'}}
    [34m56.


key: _node_content
string_value:
{"id_": "61cb2203-1dee-4d29-b70d-d969208fa932", "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": "72bd030a-0ef6-4a6a-b183-b08a654900c4", "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": "9f79594e61c04c1be453ac4aec2694497bd3b221f81a419ee74db19a5312efda", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "549300d3-47ba-4a18-81b1-fb60c9b6b735", "node_type": "1", "metadata": {}, "hash": "a9b039c718520255cf42e17c97fd0db5a63ff2066ec9a34fecdb98cebfccca4b", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 43478, "end_char_idx": 45728, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
1% complete[0m
    {'name': 'set_drone_lighting', 'arguments': {'mode': 'blink'}}
    [34m36.8% complete[0m
    {'name': 'set_drone_lighting', 'arguments': {'mode': 'sos'}}
    [34m38.6% complete[0m
    {'name': 'return_to_home', 'arguments': {}}
    [34m40.4% complete[0m
    {'name': 'set_battery_saver_mode', 'arguments': {'status': 'on'}}
    [34m42.1% complete[0m
    {'name': 'set_battery_saver_mode', 'arguments': {'status': 'off'}}
    [34m43.9% complete[0m
    {'name': 'set_obstacle_avoidance', 'arguments': {'mode': 'on'}}
    [34m45.6% complete[0m
    {'name': 'set_obstacle_avoidance', 'arguments': {'mode': 'off'}}
    [34m47.4% complete[0m
    {'name': 'set_follow_me_mode', 'arguments': {'status': 'on'}}
    [34m49.1% complete[0m
    {'name': 'set_follow_me_mode', 'arguments': {'status': 'off'}}
    [34m50.9% complete[0m
    {'name': 'calibrate_sensors', 'arguments': {}}
    [34m52.6% complete[0m
    {'name': 'set_autopilot', 'arguments': {'status': 'on'}}
    [34m54.4% complete[0m
    {'name': 'set_autopilot', 'arguments': {'status': 'off'}}
    [34m56.1% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'solid'}}
    [34m57.9% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'solid', 'color': 'red'}}
    [34m59.6% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'solid', 'color': 'blue'}}
    [34m61.4% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'solid', 'color': 'green'}}
    [34m63.2% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'solid', 'color': 'yellow'}}
    [34m64.9% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'solid', 'color': 'white'}}
    [34m66.7% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'blink'}}
    [34m68.4% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'blink', 'color': 'red'}}
    [34m70.2% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'blink', 'color': 'blue'}}
    [34m71.9% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'blink', 'color': 'green'}}
    [34m73.


key: _node_content
string_value:
{"id_": "549300d3-47ba-4a18-81b1-fb60c9b6b735", "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": "61cb2203-1dee-4d29-b70d-d969208fa932", "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": "150863ead67c39afc0a904a39d4e07ad3db774606b3c0307dcf4fe8ea9579d6a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9cb6bf0f-b5fa-458d-949f-1474fa5ba1da", "node_type": "1", "metadata": {}, "hash": "adbecc63de3ee9606026b33cbd9ab150059511c5047693c9cfefdb1b971dde8d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 44535, "end_char_idx": 46936, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
'arguments': {'status': 'off'}}
    [34m56.1% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'solid'}}
    [34m57.9% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'solid', 'color': 'red'}}
    [34m59.6% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'solid', 'color': 'blue'}}
    [34m61.4% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'solid', 'color': 'green'}}
    [34m63.2% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'solid', 'color': 'yellow'}}
    [34m64.9% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'solid', 'color': 'white'}}
    [34m66.7% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'blink'}}
    [34m68.4% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'blink', 'color': 'red'}}
    [34m70.2% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'blink', 'color': 'blue'}}
    [34m71.9% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'blink', 'color': 'green'}}
    [34m73.7% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'blink', 'color': 'yellow'}}
    [34m75.4% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'blink', 'color': 'white'}}
    [34m77.2% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'pulse'}}
    [34m78.9% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'pulse', 'color': 'red'}}
    [34m80.7% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'pulse', 'color': 'blue'}}
    [34m82.5% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'pulse', 'color': 'green'}}
    [34m84.2% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'pulse', 'color': 'yellow'}}
    [34m86.0% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'pulse', 'color': 'white'}}
    [34m87.7% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'rainbow'}}
    [34m89.5% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'rainbow', 'color': 'red'}}
    [34m91.2% complete[0m
    {'name': 'configure_led_display',


key: _node_content
string_value:
{"id_": "9cb6bf0f-b5fa-458d-949f-1474fa5ba1da", "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": "549300d3-47ba-4a18-81b1-fb60c9b6b735", "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": "8deef10ca98e40f2b79ac9849ac393ba6c948b463bdda4505f561292e26515d7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1de3a32d-a035-498d-91cd-92e7266f03d1", "node_type": "1", "metadata": {}, "hash": "8816ecb32fa8870585f9ae01f9369a628ae8caf4197d7a08a01f86b9eb4a220e", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 45697, "end_char_idx": 48166, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
'color': 'green'}}
    [34m73.7% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'blink', 'color': 'yellow'}}
    [34m75.4% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'blink', 'color': 'white'}}
    [34m77.2% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'pulse'}}
    [34m78.9% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'pulse', 'color': 'red'}}
    [34m80.7% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'pulse', 'color': 'blue'}}
    [34m82.5% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'pulse', 'color': 'green'}}
    [34m84.2% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'pulse', 'color': 'yellow'}}
    [34m86.0% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'pulse', 'color': 'white'}}
    [34m87.7% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'rainbow'}}
    [34m89.5% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'rainbow', 'color': 'red'}}
    [34m91.2% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'rainbow', 'color': 'blue'}}
    [34m93.0% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'rainbow', 'color': 'green'}}
    [34m94.7% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'rainbow', 'color': 'yellow'}}
    [34m96.5% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'rainbow', 'color': 'white'}}
    [34m98.2% complete[0m
    {'name': 'reject_request', 'arguments': {}}


Now let's format the training examples properly. For more documentation on the proper training data formatting for fine tuning for function calling, see here: https://platform.openai.com/docs/guides/fine-tuning/fine-tuning-examples



```python
def remove_descriptions(function_list):
    for function in function_list:
        func = function["function"]
        if "description" in func:
            del func["description"]

        params = func["parameters"]
        if "properties" in params:
            for param in params["properties"].values():
                if "description" in param:
                    del param["description"]

    return function_list


modified_function_list = remove_descriptions(function_list)
```


key: _node_content
string_value:
{"id_": "1de3a32d-a035-498d-91cd-92e7266f03d1", "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": "9cb6bf0f-b5fa-458d-949f-1474fa5ba1da", "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": "f3cc724786c0981a97bbb1f497a6c19ca984c0c5d4087114259594039d6fa128", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8d42d487-7afd-4684-b6ee-2938a9411f35", "node_type": "1", "metadata": {}, "hash": "e716f43a2271a9d0f3910f33377ed82f424b99ca1657d32865f5fd208b79489f", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 46661, "end_char_idx": 49501, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
7% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'rainbow'}}
    [34m89.5% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'rainbow', 'color': 'red'}}
    [34m91.2% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'rainbow', 'color': 'blue'}}
    [34m93.0% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'rainbow', 'color': 'green'}}
    [34m94.7% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'rainbow', 'color': 'yellow'}}
    [34m96.5% complete[0m
    {'name': 'configure_led_display', 'arguments': {'pattern': 'rainbow', 'color': 'white'}}
    [34m98.2% complete[0m
    {'name': 'reject_request', 'arguments': {}}


Now let's format the training examples properly. For more documentation on the proper training data formatting for fine tuning for function calling, see here: https://platform.openai.com/docs/guides/fine-tuning/fine-tuning-examples



```python
def remove_descriptions(function_list):
    for function in function_list:
        func = function["function"]
        if "description" in func:
            del func["description"]

        params = func["parameters"]
        if "properties" in params:
            for param in params["properties"].values():
                if "description" in param:
                    del param["description"]

    return function_list


modified_function_list = remove_descriptions(function_list)
```


```python
training_examples = []

for prompt in training_examples_unformatted:
    # adjust formatting for training data specs

    # if its not a dict, convert to dict
    if type(prompt["Input"]) != dict:
        prompt["Input"] = ast.literal_eval(prompt["Input"])
    prompt["Input"]["arguments"] = json.dumps(prompt["Input"]["arguments"])
    try:
        prompt["Prompt"] = json.loads(prompt["Prompt"])
    except:
        continue
    for p in prompt["Prompt"]:
        print(p)
        print(prompt["Input"])
        tool_calls = [
            {"id": "call_id", "type": "function", "function": prompt["Input"]}
        ]
        training_examples.append(
            {
                "messages": [
                    {"role": "system", "content": DRONE_SYSTEM_PROMPT},
                    {"role": "user", "content": p},
                    {"role": "assistant", "tool_calls": tool_calls},
                ],
                "parallel_tool_calls": False,
                "tools": modified_function_list,
            }
        )
```

    Let's get the drone in the air, how high should it go?
    {'name': 'takeoff_drone', 'arguments': '{"altitude": 100}'}
    Ready for takeoff, how high should the drone fly?
    {'name': 'takeoff_drone', 'arguments': '{"altitude": 100}'}
    Can you bring the drone down to where we are?


key: _node_content
string_value:
{"id_": "8d42d487-7afd-4684-b6ee-2938a9411f35", "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": "1de3a32d-a035-498d-91cd-92e7266f03d1", "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": "9fc07e958e885016e928c458333a84d0f45e72c0f13ee375702af084a81f4ec7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "985ec7ad-e8e1-4f63-88ad-09efcc0fba49", "node_type": "1", "metadata": {}, "hash": "70f83438c601fcca0b07cf5e787384925b7d813bbf82b7817d7bee5922d85772", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 47668, "end_char_idx": 50870, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
def remove_descriptions(function_list):
    for function in function_list:
        func = function["function"]
        if "description" in func:
            del func["description"]

        params = func["parameters"]
        if "properties" in params:
            for param in params["properties"].values():
                if "description" in param:
                    del param["description"]

    return function_list


modified_function_list = remove_descriptions(function_list)
```


```python
training_examples = []

for prompt in training_examples_unformatted:
    # adjust formatting for training data specs

    # if its not a dict, convert to dict
    if type(prompt["Input"]) != dict:
        prompt["Input"] = ast.literal_eval(prompt["Input"])
    prompt["Input"]["arguments"] = json.dumps(prompt["Input"]["arguments"])
    try:
        prompt["Prompt"] = json.loads(prompt["Prompt"])
    except:
        continue
    for p in prompt["Prompt"]:
        print(p)
        print(prompt["Input"])
        tool_calls = [
            {"id": "call_id", "type": "function", "function": prompt["Input"]}
        ]
        training_examples.append(
            {
                "messages": [
                    {"role": "system", "content": DRONE_SYSTEM_PROMPT},
                    {"role": "user", "content": p},
                    {"role": "assistant", "tool_calls": tool_calls},
                ],
                "parallel_tool_calls": False,
                "tools": modified_function_list,
            }
        )
```

    Let's get the drone in the air, how high should it go?
    {'name': 'takeoff_drone', 'arguments': '{"altitude": 100}'}
    Ready for takeoff, how high should the drone fly?
    {'name': 'takeoff_drone', 'arguments': '{"altitude": 100}'}
    Can you bring the drone down to where we are?
    {'name': 'land_drone', 'arguments': '{"location": "current"}'}
    Let's get the drone to land right here
    {'name': 'land_drone', 'arguments': '{"location": "current"}'}
    Bring the drone back to base for landing
    {'name': 'land_drone', 'arguments': '{"location": "home_base"}'}
    Can you safely land the drone at home base
    {'name': 'land_drone', 'arguments': '{"location": "home_base"}'}
    Can you make the drone move to the left by 10 units?
    {'name': 'control_drone_movement', 'arguments': '{"direction": "left", "distance": 10}'}
    I need the drone to go left, could you move it 10 steps that way?
    {'name': 'control_drone_movement', 'arguments': '{"direction": "left", "distance": 10}'}
    Can you move the drone to the right by 10 feet?
    {'name': 'control_drone_movement', 'arguments': '{"direction": "right", "distance": 10}'}
    I need the drone to go 10 feet to the right, can you do that?
    {'name': 'control_drone_movement', 'arguments': '{"direction": "right", "distance": 10}'}
    Can you make the drone go upwards by 10 units?
    {'name': 'control_drone_movement', 'arguments': '{"direction": "up", "distance": 10}'}
    I need the drone to move up, can you do that for me?
    {'name': 'control_drone_movement', 'arguments': '{"direction": "up", "distance": 10}'}
    Can you bring the drone lower by 10 feet please?


key: _node_content
string_value:
{"id_": "985ec7ad-e8e1-4f63-88ad-09efcc0fba49", "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": "8d42d487-7afd-4684-b6ee-2938a9411f35", "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": "87b203330301a06f524f3002c06a359285584533756cb8c72340fa492524a6db", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5e37eaf7-54d6-4aca-8daa-8a5656acb6a7", "node_type": "1", "metadata": {}, "hash": "a5cd2e96efeddbd49fc117a07af801f025551ecc7f1a3bfe4af2f05763d6439a", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 49506, "end_char_idx": 52116, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
{'name': 'land_drone', 'arguments': '{"location": "current"}'}
    Let's get the drone to land right here
    {'name': 'land_drone', 'arguments': '{"location": "current"}'}
    Bring the drone back to base for landing
    {'name': 'land_drone', 'arguments': '{"location": "home_base"}'}
    Can you safely land the drone at home base
    {'name': 'land_drone', 'arguments': '{"location": "home_base"}'}
    Can you make the drone move to the left by 10 units?
    {'name': 'control_drone_movement', 'arguments': '{"direction": "left", "distance": 10}'}
    I need the drone to go left, could you move it 10 steps that way?
    {'name': 'control_drone_movement', 'arguments': '{"direction": "left", "distance": 10}'}
    Can you move the drone to the right by 10 feet?
    {'name': 'control_drone_movement', 'arguments': '{"direction": "right", "distance": 10}'}
    I need the drone to go 10 feet to the right, can you do that?
    {'name': 'control_drone_movement', 'arguments': '{"direction": "right", "distance": 10}'}
    Can you make the drone go upwards by 10 units?
    {'name': 'control_drone_movement', 'arguments': '{"direction": "up", "distance": 10}'}
    I need the drone to move up, can you do that for me?
    {'name': 'control_drone_movement', 'arguments': '{"direction": "up", "distance": 10}'}
    Can you bring the drone lower by 10 feet please?
    {'name': 'control_drone_movement', 'arguments': '{"direction": "down", "distance": 10}'}
    I need the drone to descend 10 units, can you make that happen?
    {'name': 'control_drone_movement', 'arguments': '{"direction": "down", "distance": 10}'}
    Can you make the drone go faster?
    {'name': 'set_drone_speed', 'arguments': '{"speed": 10}'}
    I think the drone should speed up a bit, don't you think?
    {'name': 'set_drone_speed', 'arguments': '{"speed": 10}'}
    I want to take a picture, can you switch the camera mode to photo
    {'name': 'control_camera', 'arguments': '{"mode": "photo"}'}
    Let's capture this moment, switch the camera to photo mode please
    {'name': 'control_camera', 'arguments': '{"mode": "photo"}'}
    Can you switch the camera to photo mode and take a picture for 10 seconds?
    {'name': 'control_camera', 'arguments': '{"mode": "photo", "duration": 10}'}
    I need to capture something, can you set the camera to take photos for 10 seconds?
    {'name': 'control_camera', 'arguments': '{"mode": "photo", "duration": 10}'}
    Can you switch the camera to video mode?
    {'name': 'control_camera', 'arguments': '{"mode": "video"}'}
    I want to record, can you set the camera to video mode?


key: _node_content
string_value:
{"id_": "5e37eaf7-54d6-4aca-8daa-8a5656acb6a7", "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": "985ec7ad-e8e1-4f63-88ad-09efcc0fba49", "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": "f0ba888d4dbfd0b9f5ce8e3cf2591451295f0e0c04619abb8bcdc18df22c84c5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1cf3e496-4c36-4f11-bab3-16bed89db345", "node_type": "1", "metadata": {}, "hash": "52b3f8c9622b91912f96a0a2f130f6b604a957026432ba6e0a556a07d9f4e2e5", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 50731, "end_char_idx": 53272, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
{'name': 'control_drone_movement', 'arguments': '{"direction": "up", "distance": 10}'}
    Can you bring the drone lower by 10 feet please?
    {'name': 'control_drone_movement', 'arguments': '{"direction": "down", "distance": 10}'}
    I need the drone to descend 10 units, can you make that happen?
    {'name': 'control_drone_movement', 'arguments': '{"direction": "down", "distance": 10}'}
    Can you make the drone go faster?
    {'name': 'set_drone_speed', 'arguments': '{"speed": 10}'}
    I think the drone should speed up a bit, don't you think?
    {'name': 'set_drone_speed', 'arguments': '{"speed": 10}'}
    I want to take a picture, can you switch the camera mode to photo
    {'name': 'control_camera', 'arguments': '{"mode": "photo"}'}
    Let's capture this moment, switch the camera to photo mode please
    {'name': 'control_camera', 'arguments': '{"mode": "photo"}'}
    Can you switch the camera to photo mode and take a picture for 10 seconds?
    {'name': 'control_camera', 'arguments': '{"mode": "photo", "duration": 10}'}
    I need to capture something, can you set the camera to take photos for 10 seconds?
    {'name': 'control_camera', 'arguments': '{"mode": "photo", "duration": 10}'}
    Can you switch the camera to video mode?
    {'name': 'control_camera', 'arguments': '{"mode": "video"}'}
    I want to record, can you set the camera to video mode?
    {'name': 'control_camera', 'arguments': '{"mode": "video"}'}
    Can you start recording a video with the camera for a minute
    {'name': 'control_camera', 'arguments': '{"mode": "video", "duration": 60}'}
    I need to film something, can you put the camera in video mode for 60 seconds
    {'name': 'control_camera', 'arguments': '{"mode": "video", "duration": 60}'}
    Can you switch the camera to panorama mode?
    {'name': 'control_camera', 'arguments': '{"mode": "panorama"}'}
    I'd like to take a 360-degree photo, can you set the camera to panorama mode?
    {'name': 'control_camera', 'arguments': '{"mode": "panorama"}'}
    Can you set the camera to take a panorama shot for a minute
    {'name': 'control_camera', 'arguments': '{"mode": "panorama", "duration": 60}'}
    I'd like to switch the camera mode to panorama and have it last for a minute
    {'name': 'control_camera', 'arguments': '{"mode": "panorama", "duration": 60}'}
    Can you adjust the camera angle up and to the right?
    {'name': 'control_gimbal', 'arguments': '{"tilt": 45, "pan": 90}'}
    I need to tilt the camera up and pan it to the right, can you do that?


key: _node_content
string_value:
{"id_": "1cf3e496-4c36-4f11-bab3-16bed89db345", "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": "5e37eaf7-54d6-4aca-8daa-8a5656acb6a7", "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": "f18f99e780a145e6d3f3886a291026333b9b3d35dadbb9f14c95ea72886c8ded", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7d7d92cb-551e-4c41-b916-261267cadd89", "node_type": "1", "metadata": {}, "hash": "d76124c319154f2dbca48554e8f2fc199a43c604583ffdd7fa816c9f00114440", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 51870, "end_char_idx": 54462, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
{'name': 'control_camera', 'arguments': '{"mode": "photo", "duration": 10}'}
    Can you switch the camera to video mode?
    {'name': 'control_camera', 'arguments': '{"mode": "video"}'}
    I want to record, can you set the camera to video mode?
    {'name': 'control_camera', 'arguments': '{"mode": "video"}'}
    Can you start recording a video with the camera for a minute
    {'name': 'control_camera', 'arguments': '{"mode": "video", "duration": 60}'}
    I need to film something, can you put the camera in video mode for 60 seconds
    {'name': 'control_camera', 'arguments': '{"mode": "video", "duration": 60}'}
    Can you switch the camera to panorama mode?
    {'name': 'control_camera', 'arguments': '{"mode": "panorama"}'}
    I'd like to take a 360-degree photo, can you set the camera to panorama mode?
    {'name': 'control_camera', 'arguments': '{"mode": "panorama"}'}
    Can you set the camera to take a panorama shot for a minute
    {'name': 'control_camera', 'arguments': '{"mode": "panorama", "duration": 60}'}
    I'd like to switch the camera mode to panorama and have it last for a minute
    {'name': 'control_camera', 'arguments': '{"mode": "panorama", "duration": 60}'}
    Can you adjust the camera angle up and to the right?
    {'name': 'control_gimbal', 'arguments': '{"tilt": 45, "pan": 90}'}
    I need to tilt the camera up and pan it to the right, can you do that?
    {'name': 'control_gimbal', 'arguments': '{"tilt": 45, "pan": 90}'}
    Can you turn on the lights for the drone
    {'name': 'set_drone_lighting', 'arguments': '{"mode": "on"}'}
    I need some extra light, can you activate it on the drone
    {'name': 'set_drone_lighting', 'arguments': '{"mode": "on"}'}
    Can you turn off the lights on the drone
    {'name': 'set_drone_lighting', 'arguments': '{"mode": "off"}'}
    I don't need the drone lights on, can you switch them off
    {'name': 'set_drone_lighting', 'arguments': '{"mode": "off"}'}
    Can you make the drone lights flash?
    {'name': 'set_drone_lighting', 'arguments': '{"mode": "blink"}'}
    I want the drone lights to blink, can you do that?
    {'name': 'set_drone_lighting', 'arguments': '{"mode": "blink"}'}
    Can you switch the drone lights to the SOS mode, just in case?
    {'name': 'set_drone_lighting', 'arguments': '{"mode": "sos"}'}
    I need the drone lights to flash SOS, can you set that up?
    {'name': 'set_drone_lighting', 'arguments': '{"mode": "sos"}'}
    Can you bring the drone back home now?
    {'name': 'return_to_home', 'arguments': '{}'}
    Is it time for the drone to return to base?


key: _node_content
string_value:
{"id_": "7d7d92cb-551e-4c41-b916-261267cadd89", "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": "1cf3e496-4c36-4f11-bab3-16bed89db345", "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": "0fdd17883e26064e0f0f6205551300d9bbfec0355a751388da743268ae446fb9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3667cbb7-a9a2-4b08-b429-2d26bce5535a", "node_type": "1", "metadata": {}, "hash": "1a6bec9c48cf99d74fd61d434e81a60aaa3ddd01d9c3810b254e5ab9cbd55a46", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 53131, "end_char_idx": 55842, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
{'name': 'control_gimbal', 'arguments': '{"tilt": 45, "pan": 90}'}
    I need to tilt the camera up and pan it to the right, can you do that?
    {'name': 'control_gimbal', 'arguments': '{"tilt": 45, "pan": 90}'}
    Can you turn on the lights for the drone
    {'name': 'set_drone_lighting', 'arguments': '{"mode": "on"}'}
    I need some extra light, can you activate it on the drone
    {'name': 'set_drone_lighting', 'arguments': '{"mode": "on"}'}
    Can you turn off the lights on the drone
    {'name': 'set_drone_lighting', 'arguments': '{"mode": "off"}'}
    I don't need the drone lights on, can you switch them off
    {'name': 'set_drone_lighting', 'arguments': '{"mode": "off"}'}
    Can you make the drone lights flash?
    {'name': 'set_drone_lighting', 'arguments': '{"mode": "blink"}'}
    I want the drone lights to blink, can you do that?
    {'name': 'set_drone_lighting', 'arguments': '{"mode": "blink"}'}
    Can you switch the drone lights to the SOS mode, just in case?
    {'name': 'set_drone_lighting', 'arguments': '{"mode": "sos"}'}
    I need the drone lights to flash SOS, can you set that up?
    {'name': 'set_drone_lighting', 'arguments': '{"mode": "sos"}'}
    Can you bring the drone back home now?
    {'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?


