Slide 26
Slide 26 text
/**
* Automates a process based on a user query.
* @param content - The query from the user.
*/
async automate(content: string): Promise
Agents
/**
* Handles a choice made by the AI model.
* @param choice - The choice made by the model.
* @param chat - The current chat history.
* @param tools - Available tools for the AI.
* @param state - Current application state.
* @param trace - Langfuse trace client for logging.
*/
private async handleChoice(
choice: Choice,
chat: ChatCompletionMessageParam[],
tools: Tool[],
state?: any,
trace?: LangfuseTraceClient,
): Promise {
// handle tool call, can be one or more
if (choice.finish_reason === 'tool_calls') {
// display information to the user
this.createToolMessage(choice).forEach(message => this.message$.next(message));
// make the actual function call and create a message from it
const toolResult = this.handleToolCalls(choice);
// respond to the API with made calls
if (toolResult) {
chat.push(choice.message, ...toolResult);
(await this.aiBackend.automate(chat, tools, state, trace)).map(choice =>
this.handleChoice(choice, chat, tools, state, trace),
);
}
} else {
this.message$.next({
role: choice.message.role,
message: choice.message.content ?? 'NO MESSAGE',
});
/**
* Handles tool calls made by the AI model.
* @param param0 - Object containing the message with tool calls.
* @returns An array of tool message params.
*/
private handleToolCalls({ message }: Pick): ChatCompletionToolMessageParam[] {
// iterate through tool calls in choices.
return message.tool_calls!.map(call => {
// find the matching instance for this tool
const { name, guid } = this.splitFunctionName(call.function.name);
const toolInstance = this.findToolInstance(name, guid);
let content = '';
// call the instance function with params
const instance = toolInstance?.instance as any;
if (instance && name in instance) {
const toolFunction = instance[name];
content = JSON.stringify(
toolFunction.call(instance, ...Object.values(JSON.parse(call.function.arguments))) ?? '',
);
// message user about tool call results
…
}
return {
content,
tool_call_id: call.id,
role: 'tool',
name: call.function.name,
};
});
}