Last active
July 24, 2023 08:53
-
-
Save jerheff/254718528237c9a5327b541af9fb8cba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Example use of function calling to return structured data from GPT API | |
import asyncio | |
import json | |
import os | |
import sys | |
import openai | |
openai.api_key = os.getenv("OPENAI_API_KEY") | |
gpt_functions = [ | |
{ | |
"name": "return_sentiment", | |
"description": "Returns the sentiment of the provided text", | |
"parameters": { | |
"type": "object", | |
"properties": { | |
"sentiment": { | |
"type": "string", | |
"description": "The sentiment of the text", | |
"enum": ["Positive", "Negative", "Neutral"], | |
}, | |
}, | |
"required": ["sentiment"], | |
"additionalProperties": False, | |
}, | |
}, | |
] | |
async def main(): | |
text_to_analyze = sys.argv[1] # get text from command line | |
messages = [ | |
{"role": "system", "content": "You are a helpful assistant."}, | |
{"role": "user", "content": text_to_analyze}, | |
] | |
completion = await openai.ChatCompletion.acreate( | |
model="gpt-3.5-turbo", | |
messages=messages, | |
functions=gpt_functions, | |
function_call={"name": "return_sentiment"}, | |
) | |
response = json.loads( | |
completion["choices"][0]["message"]["function_call"]["arguments"] | |
) | |
print(response) | |
if __name__ == "__main__": | |
asyncio.run(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment