import { ChatCompletionsParams } from "premai/resources/chat";
import PremAI from "premai";
const tools = [
{
type: "function",
function: {
name: "get_current_weather",
description: "Get the current weather in a given location",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "The city and state, e.g. San Francisco, CA",
},
unit: {
type: "string",
enum: ["celsius", "fahrenheit"]
},
},
required: ["location"],
},
},
}
];
// Mock function implementation
function getCurrentWeather(location: string, unit: string = "celsius"): object {
// In a real app, you'd call a weather API here
return {
location: location,
temperature: unit === "celsius" ? "15Β°C" : "59Β°F",
condition: "Partly cloudy",
humidity: "65%"
};
}
const client = new PremAI({
apiKey: process.env.PREMAI_API_KEY || "",
});
const messages: ChatCompletionsParams.Message[] = [
{ role: "user", content: "What's the weather like in Boston today?" }
] as any;
const response = await client.chat.completions({
model: "claude-4-sonnet",
messages,
tools,
tool_choice: "auto"
});
// Check if the model wants to call a function
if (response.choices[0].message.tool_calls) {
// Add the assistant's response to conversation
messages.push({
role: "assistant",
content: response.choices[0].message.content,
tool_calls: response.choices[0].message.tool_calls
});
// Execute each tool call
for (const toolCall of response.choices[0].message.tool_calls) {
const functionName = toolCall.function.name;
const functionArgs = JSON.parse(toolCall.function.arguments);
let result: object;
if (functionName === "get_current_weather") {
result = getCurrentWeather(functionArgs.location, functionArgs.unit);
} else {
result = { error: "Unknown function" };
}
// Add the function result to conversation
messages.push({
role: "tool",
tool_call_id: toolCall.id,
content: JSON.stringify(result),
name: functionName
});
}
// Get final response with function results
const finalResponse = await client.chat.completions({
model: "claude-4-sonnet",
messages,
tools
});
console.log(finalResponse.choices[0].message.content);
} else {
console.log(response.choices[0].message.content);
}