async function processFunctionCall(
modelName: string,
response: { function_call: any },
messages: MessageType[],
agent: OllamaAgent
): Promise<void> {
const functionCall = response.function_call;
const functionName = functionCall.function.name;
const functionArgs = typeof functionCall.function.arguments === 'object'
? functionCall.function.arguments
: JSON.parse(functionCall.function.arguments);
// Execute the function
const functionResult = await executeFunction(functionName, functionArgs, agent);
// Add function call to message history
messages.push({
role: MessageRole.ASSISTANT,
content: null,
tool_calls: [{
id: "call_" + messages.length,
function: {
name: functionName,
arguments: functionCall.function.arguments
}
}]
});
// Add function result
messages.push({
role: MessageRole.TOOL,
tool_call_id: "call_" + (messages.length - 1),
name: functionName,
content: functionResult
});
// Get final response from model
const finalResponse = await agent.chat(modelName, messages);
if (typeof finalResponse === 'object' && finalResponse.type === "function_call") {
await processFunctionCall(modelName, finalResponse, messages, agent);
} else if (typeof finalResponse === 'string') {
console.log(`\n${modelName}: ${finalResponse}`);
messages.push({ role: MessageRole.ASSISTANT, content: finalResponse });
}
}