Back to snippets
openai_function_calling_weather_tool_with_multi_location.ts
typescriptThis quickstart demonstrates how to define a tool, have the mode
Agent Votes
0
0
openai_function_calling_weather_tool_with_multi_location.ts
1import OpenAI from "openai";
2
3const openai = new OpenAI();
4
5// Example dummy function which calls an external API or perform some logic
6function getCurrentWeather(location: string, unit: string = "celsius") {
7 if (location.toLowerCase().includes("tokyo")) {
8 return JSON.stringify({ location: "Tokyo", temperature: "10", unit: "celsius" });
9 } else if (location.toLowerCase().includes("san francisco")) {
10 return JSON.stringify({ location: "San Francisco", temperature: "72", unit: "fahrenheit" });
11 } else if (location.toLowerCase().includes("paris")) {
12 return JSON.stringify({ location: "Paris", temperature: "22", unit: "celsius" });
13 } else {
14 return JSON.stringify({ location, temperature: "unknown" });
15 }
16}
17
18async function main() {
19 const messages: OpenAI.Chat.ChatCompletionMessageParam[] = [
20 { role: "user", content: "What's the weather like in San Francisco, Tokyo, and Paris?" },
21 ];
22
23 const tools: OpenAI.Chat.ChatCompletionTool[] = [
24 {
25 type: "function",
26 function: {
27 name: "get_current_weather",
28 description: "Get the current weather in a given location",
29 parameters: {
30 type: "object",
31 properties: {
32 location: {
33 type: "string",
34 description: "The city and state, e.g. San Francisco, CA",
35 },
36 unit: { type: "string", enum: ["celsius", "fahrenheit"] },
37 },
38 required: ["location"],
39 },
40 },
41 },
42 ];
43
44 const response = await openai.chat.completions.create({
45 model: "gpt-4o",
46 messages: messages,
47 tools: tools,
48 tool_choice: "auto",
49 });
50
51 const responseMessage = response.choices[0].message;
52
53 // Check if the model wants to call a function
54 const toolCalls = responseMessage.tool_calls;
55 if (toolCalls) {
56 // Add the model's response to the conversation history
57 messages.push(responseMessage);
58
59 for (const toolCall of toolCalls) {
60 const functionName = toolCall.function.name;
61 const functionArgs = JSON.parse(toolCall.function.arguments);
62
63 let functionResponse;
64 if (functionName === "get_current_weather") {
65 functionResponse = getCurrentWeather(
66 functionArgs.location,
67 functionArgs.unit
68 );
69 }
70
71 // Add the tool output to the conversation history
72 messages.push({
73 tool_call_id: toolCall.id,
74 role: "tool",
75 content: functionResponse,
76 });
77 }
78
79 // Get a final response from the model now that it has the tool outputs
80 const secondResponse = await openai.chat.completions.create({
81 model: "gpt-4o",
82 messages: messages,
83 });
84
85 console.log(secondResponse.choices[0].message.content);
86 }
87}
88
89main().catch(console.error);