typescriptintermediate
OpenAI Tool Calling (Function Calling)
Define tools for GPT to call, parse the response, execute the function, and return results.
typescriptPress ⌘/Ctrl + Shift + C to copy
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.
pythonintermediate
OpenAI Function Calling / Tool Use
Let GPT call your functions by defining tool schemas and handling responses.
Best for: AI agents
#ai#openai
typescriptintermediate
OpenAI Chat Completion with Streaming
Stream GPT responses token-by-token using the OpenAI SDK with async iteration.
Best for: chatbot UI
#openai#streaming
typescriptintermediate
OpenAI Structured Output with Zod
Force GPT-4o to return valid JSON matching a Zod schema using response_format structured output.
Best for: data extraction
#openai#zod
typescriptadvanced
AI Agent Loop with Tool Calling
Implement an autonomous agent loop that plans, selects tools, executes actions, and observes results.
Best for: Research assistants
#agents#tool-calling