smartai/ts/provider.anthropic.ts

75 lines
2.2 KiB
TypeScript
Raw Normal View History

2024-04-04 00:47:44 +00:00
import * as plugins from './plugins.js';
import * as paths from './paths.js';
import { MultiModalModel } from './abstract.classes.multimodal.js';
export class AnthropicProvider extends MultiModalModel {
private anthropicToken: string;
public anthropicApiClient: plugins.anthropic.default;
constructor(anthropicToken: string) {
super();
this.anthropicToken = anthropicToken; // Ensure the token is stored
}
async start() {
this.anthropicApiClient = new plugins.anthropic.default({
apiKey: this.anthropicToken,
});
}
async stop() {}
chatStream(input: ReadableStream<string>): ReadableStream<string> {
const decoder = new TextDecoder();
let messageHistory: { role: 'assistant' | 'user'; content: string }[] = [];
return new ReadableStream({
async start(controller) {
const reader = input.getReader();
try {
let done, value;
while ((({ done, value } = await reader.read()), !done)) {
const userMessage = decoder.decode(value, { stream: true });
messageHistory.push({ role: 'user', content: userMessage });
const aiResponse = await this.chat('', userMessage, messageHistory);
messageHistory.push({ role: 'assistant', content: aiResponse.message });
// Directly enqueue the string response instead of encoding it first
controller.enqueue(aiResponse.message);
}
controller.close();
} catch (err) {
controller.error(err);
}
},
});
}
// Implementing the synchronous chat interaction
public async chat(
systemMessage: string,
userMessage: string,
messageHistory: {
role: 'assistant' | 'user';
content: string;
}[]
) {
const result = await this.anthropicApiClient.messages.create({
model: 'claude-3-opus-20240229',
system: systemMessage,
messages: [
...messageHistory,
{ role: 'user', content: userMessage },
],
max_tokens: 4000,
});
return {
message: result.content,
};
}
public async audio(messageArg: string) {
// Anthropic does not provide an audio API, so this method is not implemented.
throw new Error('Audio generation is not supported by Anthropic.');
}
}