@azowl/agentops-sdk
Version:
AgentOps REST client and local task execution SDK for Node.js
42 lines (41 loc) • 1.92 kB
JavaScript
// One tool call per turn, using Ollama's non-streaming /api/chat endpoint.
export function createOllamaModel(model, endpoint = 'http://127.0.0.1:11434/api/chat') {
if (typeof model !== 'string' || !model.trim()) throw new TypeError('A model name is required.');
return async ({ messages, tools }) => {
const history = [];
for (const message of messages) {
if (message.role === 'user') {
history.push({ role: 'user', content: message.text });
} else {
history.push(
{ role: 'assistant', content: '', tool_calls: [{ function: { name: message.name, arguments: message.input } }] },
{ role: 'tool', tool_name: message.name, content: JSON.stringify(message.result) },
);
}
}
const response = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
redirect: 'error',
signal: AbortSignal.timeout(120_000),
body: JSON.stringify({
model, messages: history, stream: false, think: false,
tools: tools.map(tool => ({
type: 'function',
function: { name: tool.name, description: tool.description ?? tool.name,
parameters: tool.inputSchema ?? { type: 'object', properties: {} } },
})),
}),
});
if (!response.ok) throw new Error('Ollama request failed.');
const { done, done_reason, message } = await response.json();
if (done !== true || (done_reason && done_reason !== 'stop') || message?.role !== 'assistant') {
throw new Error('Incomplete Ollama response.');
}
const calls = message.tool_calls ?? [];
if (!Array.isArray(calls) || calls.length > 1) throw new Error('Expected at most one tool call.');
if (!calls.length) return { type: 'final', text: message.content };
const call = calls[0]?.function;
return { type: 'tool_call', name: call?.name, input: call?.arguments };
};
}