ai-persona-hub
Version:
AI Profile CLI - Create custom AI profiles run against dynamic LLM providers
93 lines • 3.33 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AIClient = void 0;
const core_1 = require("@mastra/core");
const memory_1 = require("@mastra/memory");
const libsql_1 = require("@mastra/libsql");
const openai_1 = require("@ai-sdk/openai");
const anthropic_1 = require("@ai-sdk/anthropic");
const google_1 = require("@ai-sdk/google");
const crypto_1 = require("crypto");
class AIClient {
agent;
config;
profile;
threadId;
constructor(config, profile, apiKey) {
this.config = config;
this.profile = profile;
this.agent = this.createAgent(apiKey);
this.threadId = (0, crypto_1.randomUUID)();
}
createAgent(apiKey) {
const model = this.getProviderModel(apiKey);
// Create memory instance with working memory enabled and message range of 10
const memory = new memory_1.Memory({
storage: new libsql_1.LibSQLStore({
url: 'file:./memory.db',
}),
options: {
workingMemory: { enabled: true },
},
});
return new core_1.Agent({
name: this.profile.name,
instructions: this.profile.systemPrompt,
model,
memory,
});
}
getProviderModel(apiKey) {
// Set the API key in the environment for the providers
switch (this.config.provider) {
case 'openai':
process.env.OPENAI_API_KEY = apiKey;
return (0, openai_1.openai)(this.config.model);
case 'anthropic':
process.env.ANTHROPIC_API_KEY = apiKey;
return (0, anthropic_1.anthropic)(this.config.model);
case 'google':
process.env.GOOGLE_GENERATIVE_AI_API_KEY = apiKey;
return (0, google_1.google)(this.config.model);
default:
throw new Error(`Unsupported provider: ${this.config.provider}`);
}
}
async sendMessage(message, onChunk) {
try {
// Use the agent's stream method with memory parameters
const stream = await this.agent.stream(message, {
maxTokens: this.config.maxTokens,
resourceId: this.profile.id,
threadId: this.threadId,
});
let fullResponse = '';
// Stream the response in real-time
for await (const chunk of stream.textStream) {
fullResponse += chunk;
if (onChunk) {
onChunk(chunk);
}
}
return fullResponse;
}
catch (_error) {
if (_error instanceof Error) {
throw new Error(`AI API error: ${_error.message}`);
}
throw new Error('Unknown error occurred while communicating with AI provider');
}
}
updateConfig(newConfig, newApiKey, newProfile) {
this.config = { ...this.config, ...newConfig };
if (newProfile) {
this.profile = newProfile;
}
// Recreate agent with new configuration
if (newApiKey || newProfile) {
this.agent = this.createAgent(newApiKey || '');
}
}
}
exports.AIClient = AIClient;
//# sourceMappingURL=ai-client.js.map