Skip to content

yoniLavi/Structured-OpenAI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Structured OpenAI

Background

This repo demonstrates a concise way of utilizing the new Function Calling capability of OpenAI's API, as a way to create complex prompts in a structured manner, without any string templating.

The generate_structured_openai_call function allows you to define such a prompt by providing just the general request (passed into the system message) and a dict representing the output properties you want in JSON Schema format.

Prerequisites

  • Install dependencies (pip install -r requirements.txt)
  • Set the OPENAI_API_KEY environment variable to your OpenAI API key (e.g. via a .env file)

Example

In this example we create a function to analyze any kind of sequence and predict some possible next values.

We then use pandas to apply the function to a column and output a new dataframe.

import pandas as pd

from structured_openai import generate_structured_openai_call

# Our prompt function - with just a basic system prompt
# and the rest in the property descriptions
analyze_sequence = generate_structured_openai_call(
    "Analyze this sequence of items",
    {
        "sequence_description": {
            "type": "string",
            "description": "What is the sequence about?",
        },
        "next_several_items": {
            "type": "array",
            "items": {"type": "string"},
            "description": "Extrapolation of several more items in the sequence",
        },
    },
    temperature=0.5,
)


# Example sequences as a dataframe column
df = pd.DataFrame({'sequences': [
    "Apple, Banana, Cherry",
    "Tuesday, Wednesday",
    "Aquamarine, Smithsonite",
    "Thor, Odin",
    "A, E, I",
    "1, 1, 2, 3",
]})

# Run the prompt on each of the above entries, and collect into a new dataframe
response_df = pd.DataFrame(df['sequences'].apply(analyze_sequence).tolist())

The above will generate an output of the following form:

original_input sequence_description next_several_items
Apple, Banana, Cherry This sequence consists of fruits in alphabetical order. ['Date', 'Elderberry', 'Fig']
Tuesday, Wednesday This sequence represents the days of the week starting from Tuesday and continuing to Wednesday. ['Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday']
Aquamarine, Smithsonite This sequence consists of gemstones. ['Amethyst', 'Emerald', 'Ruby']
Thor, Odin Norse Mythology Gods ['Loki', 'Frigg', 'Baldr']
A, E, I The sequence consists of the vowels A, E, and I. ['O', 'U']
1, 1, 2, 3 This sequence is generated by starting with 1, then adding the two previous numbers to get the next number. ['5', '8', '13']

About

An example of utilizing OpenAI function calling for structured responses

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages