import Together from "together-ai";
import { CompletionCreateParams } from "together-ai/resources/chat/completions.mjs";
const together = new Together();
// Example function to make available to model
function getCurrentWeather({
location,
unit = "fahrenheit",
}: {
location: string;
unit: "fahrenheit" | "celsius";
}) {
let result: { location: string; temperature: number | null; unit: string };
if (location.toLowerCase().includes("chicago")) {
result = {
location: "Chicago",
temperature: 13,
unit,
};
} else if (location.toLowerCase().includes("san francisco")) {
result = {
location: "San Francisco",
temperature: 55,
unit,
};
} else if (location.toLowerCase().includes("new york")) {
result = {
location: "New York",
temperature: 11,
unit,
};
} else {
result = {
location,
temperature: null,
unit,
};
}
return JSON.stringify(result);
}
const tools = [
{
type: "function",
function: {
name: "getCurrentWeather",
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"],
},
},
},
},
},
];
const messages: CompletionCreateParams.Message[] = [
{
role: "system",
content:
"You are a helpful assistant that can access external functions. The responses from these function calls will be appended to this dialogue. Please provide responses based on the information from these function calls.",
},
{
role: "user",
content:
"What is the current temperature of New York, San Francisco and Chicago?",
},
];
const response = await together.chat.completions.create({
model: "Qwen/Qwen2.5-7B-Instruct-Turbo",
messages,
tools,
});
if (response.choices[0].message?.tool_calls) {
for (const toolCall of response.choices[0].message.tool_calls) {
if (toolCall.function.name === "getCurrentWeather") {
const args = JSON.parse(toolCall.function.arguments);
const functionResponse = getCurrentWeather(args);
messages.push({
role: "tool",
content: functionResponse,
});
}
}
const functionEnrichedResponse = await together.chat.completions.create({
model: "Qwen/Qwen2.5-7B-Instruct-Turbo",
messages,
tools,
});
console.log(
JSON.stringify(functionEnrichedResponse.choices[0].message, null, 2),
);
}