OpenAI Tool Calling (Function Calling)
Define tools for GPT to call, parse the response, execute the function, and return results.
import OpenAI from "openai";
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [{
type: "function",
function: {
name: "get_weather",
description: "Get current weather for a city",
parameters: {
type: "object",
properties: {
city: { type: "string", description: "City name" },
},
required: ["city"],
},
},
}];
// Fake implementation
function get_weather({ city }: { city: string }) {
return JSON.stringify({ city, temp: "22°C", condition: "Sunny" });
}
export async function runWithTools(query: string) {
const msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
{ role: "user", content: query },
];
const res = await client.chat.completions.create({ model: "gpt-4o", tools, messages: msgs });
const msg = res.choices[0].message;
if (msg.tool_calls) {
for (const call of msg.tool_calls) {
const args = JSON.parse(call.function.arguments);
const result = get_weather(args);
msgs.push(msg, { role: "tool", tool_call_id: call.id, content: result });
}
const final = await client.chat.completions.create({ model: "gpt-4o", messages: msgs });
return final.choices[0].message.content;
}
return msg.content;
}Use Cases
- AI agents
- structured data extraction
- API orchestration
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
OpenAI Chat Completion with Streaming
Stream GPT responses token-by-token using the OpenAI SDK with async iteration.
OpenAI Structured Output with Zod
Force GPT-4o to return valid JSON matching a Zod schema using response_format structured output.
AI Agent Loop with Tool Calling
Implement an autonomous agent loop that plans, selects tools, executes actions, and observes results.
Generate Text Embeddings with OpenAI
Create vector embeddings for semantic search and similarity matching using text-embedding-3-small.