-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy path04-structured-openai.py
60 lines (51 loc) · 1.52 KB
/
04-structured-openai.py
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
import json
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
client = OpenAI()
# Create a JSON schema for an object that contains a `fruit` field; that field
# is a list of objects that each have `name` and `color` fields.
schema = {
"type": "object",
"properties": {
"fruit": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {"type": "string"},
"color": {"type": "string"},
},
"additionalProperties": False,
"required": ["name", "color"],
},
},
},
"additionalProperties": False,
"required": ["fruit"],
}
def get_structured_response(prompt):
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "system",
"content": "You are a helpful assistant. Always respond in valid JSON format.",
},
{"role": "user", "content": prompt},
],
temperature=0.7,
response_format={
"type": "json_schema",
"json_schema": {
"name": "fruits",
"schema": schema,
"strict": True,
},
},
)
# Parse the response content as JSON
return json.loads(response.choices[0].message.content)
# Example usage
result = get_structured_response("Give me a list of 3 fruits with their colors")
print(result)