-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathopenai_example.py
More file actions
160 lines (131 loc) · 4.48 KB
/
openai_example.py
File metadata and controls
160 lines (131 loc) · 4.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
"""
OpenAI API integration example for function-schema library.
This example demonstrates how to use function schemas with OpenAI's API for:
1. Assistant API with tool calling
2. Chat completion with function calling
Note: This example requires the openai library to be installed and an API key to be set.
For demonstration purposes, this shows the structure without actually making API calls.
"""
from typing import Annotated, Optional
from function_schema import Doc, get_function_schema
import enum
import json
# For actual usage, uncomment the following:
# import openai
# openai.api_key = "sk-your-api-key-here"
def get_weather(
city: Annotated[str, Doc("The city to get the weather for")],
unit: Annotated[
Optional[str],
Doc("The unit to return the temperature in"),
enum.Enum("Unit", "celcius fahrenheit")
] = "celcius",
) -> str:
"""Returns the weather for the given city."""
return f"Weather for {city} is 20°C"
def get_current_time(
timezone: Annotated[Optional[str], Doc("Timezone (e.g., 'UTC', 'EST')")] = "UTC"
) -> str:
"""Get the current time in the specified timezone."""
from datetime import datetime
return f"Current time in {timezone}: {datetime.now().isoformat()}"
def openai_assistant_example():
"""Example of using function schema with OpenAI Assistant API."""
# Generate function schema for OpenAI format
weather_tool = {
"type": "function",
"function": get_function_schema(get_weather)
}
time_tool = {
"type": "function",
"function": get_function_schema(get_current_time)
}
print("OpenAI Assistant API Example:")
print("Tool definitions:")
print(json.dumps([weather_tool, time_tool], indent=2))
print("\nExample assistant creation code:")
print("""
import openai
client = openai.OpenAI(api_key="your-api-key")
# Create an assistant with the function
assistant = client.beta.assistants.create(
instructions="You are a helpful assistant. Use the provided functions to answer questions.",
model="gpt-4-turbo-preview",
tools=[
{
"type": "function",
"function": get_function_schema(get_weather),
},
{
"type": "function",
"function": get_function_schema(get_current_time),
}
]
)
# Create a thread and run
thread = client.beta.threads.create()
run = client.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant.id,
messages=[
{"role": "user", "content": "What's the weather like in Seoul?"}
]
)
""")
def openai_chat_completion_example():
"""Example of using function schema with OpenAI Chat Completion API."""
# Generate function schemas
tools = [
{
"type": "function",
"function": get_function_schema(get_weather)
},
{
"type": "function",
"function": get_function_schema(get_current_time)
}
]
print("\nOpenAI Chat Completion API Example:")
print("Tools for chat completion:")
print(json.dumps(tools, indent=2))
print("\nExample chat completion code:")
print("""
import openai
client = openai.OpenAI(api_key="your-api-key")
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": "What's the weather like in Seoul and what time is it?"}
],
tools=[
{
"type": "function",
"function": get_function_schema(get_weather)
},
{
"type": "function",
"function": get_function_schema(get_current_time)
}
],
tool_choice="auto",
)
# Handle tool calls in the response
if response.choices[0].message.tool_calls:
for tool_call in response.choices[0].message.tool_calls:
if tool_call.function.name == "get_weather":
# Parse arguments and call the actual function
import json
args = json.loads(tool_call.function.arguments)
result = get_weather(**args)
print(f"Weather result: {result}")
elif tool_call.function.name == "get_current_time":
args = json.loads(tool_call.function.arguments)
result = get_current_time(**args)
print(f"Time result: {result}")
""")
if __name__ == "__main__":
print("Function Schema - OpenAI Integration Examples")
print("=" * 50)
openai_assistant_example()
print("\n" + "=" * 50)
openai_chat_completion_example()