-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunction_call.js
106 lines (94 loc) · 3.03 KB
/
function_call.js
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
//this file includes samples for structured output and few shot learning
import OpenAI from 'openai';
import dotenv from 'dotenv';
import { zodResponseFormat } from "openai/helpers/zod";
import { z } from "zod";
// Load environment variables
dotenv.config();
function get_weather(location) {
return {
temperature: 20,
location: location
}
}
const tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current temperature for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City and country e.g. Bogotá, Colombia"
}
},
"required": [
"location"
],
"additionalProperties": false
},
"strict": true
}
}]
const DocumentFields = z.object({
name: z.string(),
document_date: z.string().nullable(),
fields: z.array(z.string()),
});
// Initialize OpenAI client
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
async function main() {
try {
const completion = await openai.chat.completions.create({
messages: [
{
role: "system",
content: "You are a helpful assistant that outputs JSON. Keep responses concise."
},
{
role: "user",
content: "Please get me some weather information for Bogotá, Colombia."
},
],
model: "gpt-4o",
response_format: {
type: "json_object"
},
tools: tools
});
const tool_calls = completion.choices[0].message.tool_calls;
if (tool_calls.length > 0) {
const tool_call = tool_calls[0];
const tool_result = await tool_call.function.arguments;
const weather_info = get_weather(tool_result.location);
//llm call with tool result
const completion2 = await openai.chat.completions.create({
messages: [
{
role: "system",
content: "You are a helpful assistant that outputs JSON. Keep responses concise."
},
{
role: "user",
content: "Please get me some weather information for Bogotá, Colombia."
},
completion.choices[0].message,
{
role: "tool",
"tool_call_id": tool_call.id,
"content": JSON.stringify(weather_info)
},
],
model: "gpt-4o",
});
console.log('Response:', completion2.choices[0].message.content);
}
} catch (error) {
console.error('Error:', error);
}
}
main();