Created
May 23, 2024 17:40
-
-
Save judell/1f20e039cc2f7313d5c83d4fa836bb69 to your computer and use it in GitHub Desktop.
openai function call
This file contains hidden or 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
import openai | |
import json | |
import os | |
from openai import OpenAI | |
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY")) | |
# Mock function to simulate fetching weather data from an API | |
def get_weather(location): | |
# In a real scenario, replace this with an actual API call | |
return { | |
"location": location, | |
"temperature": "22°C", | |
"description": "Sunny" | |
} | |
# Define the function parameters for OpenAI | |
function_definition = { | |
"name": "get_weather", | |
"description": "Fetches current weather data for a given location.", | |
"parameters": { | |
"type": "object", | |
"properties": { | |
"location": { | |
"type": "string", | |
"description": "The location to get the weather for." | |
} | |
}, | |
"required": ["location"] | |
} | |
} | |
# Define the messages to send to the OpenAI API | |
messages = [ | |
{"role": "system", "content": "You are a helpful assistant."}, | |
{"role": "user", "content": "What's the weather like in New York?"} | |
] | |
# Make the API call | |
response = client.chat.completions.create( | |
model="gpt-4-turbo", | |
messages=messages, | |
functions=[function_definition], | |
function_call="auto" | |
) | |
# Check if the function was called | |
chat_completion = response | |
message = chat_completion.choices[0].message | |
if message.function_call: | |
function_name = message.function_call.name | |
arguments = json.loads(message.function_call.arguments) | |
if function_name == "get_weather": | |
location = arguments['location'] | |
weather_data = get_weather(location) | |
print(f"Weather data for {location}:") | |
print(weather_data) | |
else: | |
print("No function call was made.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment