Fixed LLM multi message responses
All checks were successful
Publish Library / Build NPM Project (push) Successful in 44s
Publish Library / Tag Version (push) Successful in 14s

This commit is contained in:
2025-12-17 19:59:34 -05:00
parent 1fe1e0cafe
commit c896b585d0
4 changed files with 17 additions and 24 deletions

View File

@@ -73,12 +73,15 @@ export class Anthropic extends LLMProvider {
stream: !!options.stream,
};
let resp: any;
let resp: any, isFirstMessage = true;
const assistantMessages: string[] = [];
do {
resp = await this.client.messages.create(requestParams);
// Streaming mode
if(options.stream) {
if(assistantMessages.length) options.stream({text: '\n\n'});
if(!isFirstMessage) options.stream({text: '\n\n'});
else isFirstMessage = false;
resp.content = [];
for await (const chunk of resp) {
if(controller.signal.aborted) break;
@@ -105,8 +108,7 @@ export class Anthropic extends LLMProvider {
}
}
const textContent = resp.content.filter((c: any) => c.type == 'text').map((c: any) => c.text).join('\n\n');
if(textContent) assistantMessages.push(textContent);
// Run tools
const toolCalls = resp.content.filter((c: any) => c.type === 'tool_use');
if(toolCalls.length && !controller.signal.aborted) {
history.push({role: 'assistant', content: resp.content});
@@ -122,12 +124,12 @@ export class Anthropic extends LLMProvider {
}
}));
history.push({role: 'user', content: results});
original.push({role: 'user', content: results});
requestParams.messages = history;
}
} while (!controller.signal.aborted && resp.content.some((c: any) => c.type === 'tool_use'));
if(options.stream) options.stream({done: true});
res(this.toStandard([...original, {role: 'assistant', content: assistantMessages.join('\n\n'), timestamp: Date.now()}]));
res(this.toStandard([...history, {role: 'assistant', content: resp.content.filter((c: any) => c.type == 'text').map((c: any) => c.text).join('\n\n')}]));
});
return Object.assign(response, {abort: () => controller.abort()});