Code Examples
JavaScript tool-calling agent
A Node.js agent loop using the OpenAI JavaScript SDK pointed at Orqen. The same baseURL and apiKey pattern works for any OpenAI-compatible client.
For Anthropic or Bedrock in Python, see the Python agent example or provider migration.
agent.mjs
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.ORQEN_API_KEY,
baseURL: "https://api.orqen.app/v1",
});
const tools = [
{
type: "function",
function: {
name: "get_weather",
description: "Get current weather for a city.",
parameters: {
type: "object",
properties: { city: { type: "string" } },
required: ["city"],
},
},
},
];
async function callTool(name, args) {
if (name === "get_weather") {
return { city: args.city, temperature_c: 13, conditions: "light rain" };
}
return { error: "Unknown tool" };
}
async function run(userMessage) {
const messages = [{ role: "user", content: userMessage }];
for (let i = 0; i < 8; i++) {
const response = await client.chat.completions.create({
model: "gpt-4o",
messages,
tools,
tool_choice: "auto",
});
const message = response.choices[0].message;
if (!message.tool_calls?.length) return message.content ?? "";
messages.push(message);
for (const call of message.tool_calls) {
const args = JSON.parse(call.function.arguments || "{}");
const result = await callTool(call.function.name, args);
messages.push({
role: "tool",
tool_call_id: call.id,
content: JSON.stringify(result),
});
}
}
return "Stopped after max tool rounds.";
}
console.log(await run("What is the weather in London?"));Streaming
const stream = await client.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "Explain agent payload optimization" }],
tools,
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}