typescriptintermediate

OpenAI Tool Calling (Function Calling)

Define tools for GPT to call, parse the response, execute the function, and return results.

typescript
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.