praisonai 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/agent/code.d.ts +155 -0
  2. package/dist/agent/code.js +246 -0
  3. package/dist/agent/embedding.d.ts +118 -0
  4. package/dist/agent/embedding.js +151 -0
  5. package/dist/agent/handoff.d.ts +101 -0
  6. package/dist/agent/handoff.js +111 -1
  7. package/dist/agent/index.d.ts +14 -0
  8. package/dist/agent/index.js +29 -1
  9. package/dist/agent/ocr.d.ts +146 -0
  10. package/dist/agent/ocr.js +164 -0
  11. package/dist/agent/realtime.d.ts +145 -0
  12. package/dist/agent/realtime.js +210 -0
  13. package/dist/agent/research.d.ts +86 -0
  14. package/dist/agent/video.d.ts +104 -0
  15. package/dist/agent/video.js +123 -0
  16. package/dist/agent/vision.d.ts +120 -0
  17. package/dist/agent/vision.js +145 -0
  18. package/dist/cli/features/fast-context.d.ts +63 -0
  19. package/dist/cli/features/fast-context.js +82 -0
  20. package/dist/cli/features/index.d.ts +1 -1
  21. package/dist/cli/features/index.js +9 -2
  22. package/dist/conditions/index.d.ts +80 -0
  23. package/dist/conditions/index.js +237 -0
  24. package/dist/config/index.d.ts +548 -0
  25. package/dist/config/index.js +834 -0
  26. package/dist/context/index.d.ts +5 -2
  27. package/dist/context/index.js +19 -1
  28. package/dist/context/models.d.ts +242 -0
  29. package/dist/context/models.js +286 -0
  30. package/dist/display/index.d.ts +139 -0
  31. package/dist/display/index.js +278 -0
  32. package/dist/embeddings/index.d.ts +95 -0
  33. package/dist/embeddings/index.js +157 -0
  34. package/dist/gateway/index.d.ts +301 -0
  35. package/dist/gateway/index.js +148 -0
  36. package/dist/guardrails/index.d.ts +27 -0
  37. package/dist/guardrails/index.js +36 -0
  38. package/dist/index.d.ts +15 -5
  39. package/dist/index.js +241 -14
  40. package/dist/planning/index.d.ts +88 -0
  41. package/dist/planning/index.js +179 -1
  42. package/dist/plugins/index.d.ts +290 -0
  43. package/dist/plugins/index.js +536 -0
  44. package/dist/protocols/index.d.ts +341 -0
  45. package/dist/protocols/index.js +358 -0
  46. package/dist/rag/index.d.ts +34 -0
  47. package/dist/rag/index.js +114 -0
  48. package/dist/rag/models.d.ts +112 -0
  49. package/dist/rag/models.js +137 -0
  50. package/dist/rag/retrieval-config.d.ts +66 -0
  51. package/dist/rag/retrieval-config.js +89 -0
  52. package/dist/session/index.d.ts +1 -0
  53. package/dist/session/index.js +5 -1
  54. package/dist/session/session.d.ts +209 -0
  55. package/dist/session/session.js +318 -0
  56. package/dist/skills/index.d.ts +51 -0
  57. package/dist/skills/index.js +94 -1
  58. package/dist/task/index.d.ts +21 -0
  59. package/dist/task/index.js +17 -0
  60. package/dist/telemetry/index.d.ts +70 -0
  61. package/dist/telemetry/index.js +131 -1
  62. package/dist/trace/index.d.ts +209 -0
  63. package/dist/trace/index.js +372 -0
  64. package/dist/workflows/index.d.ts +89 -0
  65. package/dist/workflows/index.js +116 -0
  66. package/package.json +1 -1
@@ -0,0 +1,155 @@
1
+ /**
2
+ * CodeAgent - Code generation, execution, review, and refactoring
3
+ *
4
+ * Python parity with praisonaiagents/agent/code_agent.py
5
+ */
6
+ /**
7
+ * Configuration for CodeAgent.
8
+ * Python parity with CodeConfig dataclass.
9
+ */
10
+ export interface CodeConfig {
11
+ /** Enable sandboxed execution (default: true for safety) */
12
+ sandbox?: boolean;
13
+ /** Execution timeout in seconds */
14
+ timeout?: number;
15
+ /** List of allowed programming languages */
16
+ allowedLanguages?: string[];
17
+ /** Maximum output length in characters */
18
+ maxOutputLength?: number;
19
+ /** Working directory for code execution */
20
+ workingDirectory?: string;
21
+ /** Environment variables for execution */
22
+ environment?: Record<string, string>;
23
+ }
24
+ /**
25
+ * Result of code execution.
26
+ */
27
+ export interface CodeExecutionResult {
28
+ /** Whether execution was successful */
29
+ success: boolean;
30
+ /** Standard output from execution */
31
+ output: string;
32
+ /** Error message if execution failed */
33
+ error?: string;
34
+ /** Exit code from execution */
35
+ exitCode: number;
36
+ /** Execution time in seconds */
37
+ executionTime: number;
38
+ }
39
+ /**
40
+ * Configuration for creating a CodeAgent.
41
+ */
42
+ export interface CodeAgentConfig {
43
+ /** Agent name */
44
+ name?: string;
45
+ /** LLM model (default: gpt-4o-mini) */
46
+ llm?: string;
47
+ /** Code configuration (bool, object, or CodeConfig) */
48
+ code?: boolean | CodeConfig;
49
+ /** System instructions */
50
+ instructions?: string;
51
+ /** Enable verbose output */
52
+ verbose?: boolean;
53
+ }
54
+ /**
55
+ * Agent for code generation, execution, review, and refactoring.
56
+ *
57
+ * This agent provides capabilities for:
58
+ * - Generating code from natural language descriptions
59
+ * - Executing code in a sandboxed environment
60
+ * - Reviewing code for issues and improvements
61
+ * - Refactoring and fixing code
62
+ * - Explaining code functionality
63
+ *
64
+ * @example
65
+ * ```typescript
66
+ * import { CodeAgent } from 'praisonai';
67
+ *
68
+ * const agent = new CodeAgent({ name: 'Coder' });
69
+ *
70
+ * // Generate code
71
+ * const code = await agent.generate('Write a function to calculate fibonacci');
72
+ *
73
+ * // Execute code
74
+ * const result = await agent.execute("console.log('Hello, World!')");
75
+ *
76
+ * // Review code
77
+ * const review = await agent.review(code);
78
+ * ```
79
+ */
80
+ export declare class CodeAgent {
81
+ readonly name: string;
82
+ private readonly llm;
83
+ private readonly instructions?;
84
+ private readonly verbose;
85
+ private readonly codeConfig;
86
+ private readonly agent;
87
+ constructor(config: CodeAgentConfig);
88
+ private buildSystemPrompt;
89
+ /**
90
+ * Generate code from natural language description.
91
+ *
92
+ * @param prompt - Natural language description of desired code
93
+ * @param language - Target programming language (default: python)
94
+ * @returns Generated code as string
95
+ */
96
+ generate(prompt: string, language?: string): Promise<string>;
97
+ /**
98
+ * Alias for generate() method.
99
+ */
100
+ generateCode(prompt: string, language?: string): Promise<string>;
101
+ /**
102
+ * Execute code in a sandboxed environment.
103
+ *
104
+ * @param code - Code to execute
105
+ * @param language - Programming language (default: python)
106
+ * @returns Execution result
107
+ */
108
+ execute(code: string, language?: string): Promise<CodeExecutionResult>;
109
+ /**
110
+ * Alias for execute() method.
111
+ */
112
+ executeCode(code: string, language?: string): Promise<CodeExecutionResult>;
113
+ /**
114
+ * Review code for issues and improvements.
115
+ *
116
+ * @param code - Code to review
117
+ * @param language - Programming language
118
+ * @returns Review feedback
119
+ */
120
+ review(code: string, language?: string): Promise<string>;
121
+ /**
122
+ * Alias for review() method.
123
+ */
124
+ reviewCode(code: string, language?: string): Promise<string>;
125
+ /**
126
+ * Refactor code for better quality.
127
+ *
128
+ * @param code - Code to refactor
129
+ * @param instructions - Specific refactoring instructions
130
+ * @returns Refactored code
131
+ */
132
+ refactor(code: string, instructions?: string): Promise<string>;
133
+ /**
134
+ * Fix bugs in code.
135
+ *
136
+ * @param code - Code with bugs
137
+ * @param errorMessage - Optional error message to help identify the bug
138
+ * @returns Fixed code
139
+ */
140
+ fix(code: string, errorMessage?: string): Promise<string>;
141
+ /**
142
+ * Explain code functionality.
143
+ *
144
+ * @param code - Code to explain
145
+ * @returns Explanation of the code
146
+ */
147
+ explain(code: string): Promise<string>;
148
+ }
149
+ /**
150
+ * Create a CodeAgent instance.
151
+ *
152
+ * @param config - CodeAgent configuration
153
+ * @returns CodeAgent instance
154
+ */
155
+ export declare function createCodeAgent(config: CodeAgentConfig): CodeAgent;
@@ -0,0 +1,246 @@
1
+ "use strict";
2
+ /**
3
+ * CodeAgent - Code generation, execution, review, and refactoring
4
+ *
5
+ * Python parity with praisonaiagents/agent/code_agent.py
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.CodeAgent = void 0;
9
+ exports.createCodeAgent = createCodeAgent;
10
+ const simple_1 = require("./simple");
11
+ // ============================================================================
12
+ // Default Configuration
13
+ // ============================================================================
14
+ const DEFAULT_CODE_CONFIG = {
15
+ sandbox: true,
16
+ timeout: 30,
17
+ allowedLanguages: ['python'],
18
+ maxOutputLength: 10000,
19
+ workingDirectory: process.cwd(),
20
+ environment: {},
21
+ };
22
+ // ============================================================================
23
+ // CodeAgent Class
24
+ // ============================================================================
25
+ /**
26
+ * Agent for code generation, execution, review, and refactoring.
27
+ *
28
+ * This agent provides capabilities for:
29
+ * - Generating code from natural language descriptions
30
+ * - Executing code in a sandboxed environment
31
+ * - Reviewing code for issues and improvements
32
+ * - Refactoring and fixing code
33
+ * - Explaining code functionality
34
+ *
35
+ * @example
36
+ * ```typescript
37
+ * import { CodeAgent } from 'praisonai';
38
+ *
39
+ * const agent = new CodeAgent({ name: 'Coder' });
40
+ *
41
+ * // Generate code
42
+ * const code = await agent.generate('Write a function to calculate fibonacci');
43
+ *
44
+ * // Execute code
45
+ * const result = await agent.execute("console.log('Hello, World!')");
46
+ *
47
+ * // Review code
48
+ * const review = await agent.review(code);
49
+ * ```
50
+ */
51
+ class CodeAgent {
52
+ constructor(config) {
53
+ this.name = config.name || 'CodeAgent';
54
+ this.llm = config.llm || process.env.OPENAI_MODEL_NAME || 'gpt-4o-mini';
55
+ this.instructions = config.instructions;
56
+ this.verbose = config.verbose ?? true;
57
+ // Resolve code configuration
58
+ if (config.code === undefined || config.code === true) {
59
+ this.codeConfig = { ...DEFAULT_CODE_CONFIG };
60
+ }
61
+ else if (typeof config.code === 'object') {
62
+ this.codeConfig = { ...DEFAULT_CODE_CONFIG, ...config.code };
63
+ }
64
+ else {
65
+ this.codeConfig = { ...DEFAULT_CODE_CONFIG };
66
+ }
67
+ // Create underlying agent for LLM calls
68
+ this.agent = new simple_1.Agent({
69
+ name: this.name,
70
+ instructions: this.buildSystemPrompt(),
71
+ llm: this.llm,
72
+ verbose: this.verbose,
73
+ });
74
+ }
75
+ buildSystemPrompt() {
76
+ let prompt = `You are an expert programmer and code assistant.
77
+ You can generate, review, refactor, fix, and explain code.
78
+ Follow best practices and coding standards.
79
+ Write clean, well-documented, production-ready code.`;
80
+ if (this.instructions) {
81
+ prompt += `\n\nAdditional instructions: ${this.instructions}`;
82
+ }
83
+ return prompt;
84
+ }
85
+ // =========================================================================
86
+ // Code Generation Methods
87
+ // =========================================================================
88
+ /**
89
+ * Generate code from natural language description.
90
+ *
91
+ * @param prompt - Natural language description of desired code
92
+ * @param language - Target programming language (default: python)
93
+ * @returns Generated code as string
94
+ */
95
+ async generate(prompt, language = 'python') {
96
+ const systemPrompt = `You are an expert ${language} programmer.
97
+ Generate clean, well-documented, production-ready code.
98
+ Only output the code, no explanations unless asked.
99
+ Follow best practices and coding standards.`;
100
+ const response = await this.agent.chat(`Generate ${language} code for: ${prompt}`);
101
+ return response;
102
+ }
103
+ /**
104
+ * Alias for generate() method.
105
+ */
106
+ async generateCode(prompt, language = 'python') {
107
+ return this.generate(prompt, language);
108
+ }
109
+ // =========================================================================
110
+ // Code Execution Methods
111
+ // =========================================================================
112
+ /**
113
+ * Execute code in a sandboxed environment.
114
+ *
115
+ * @param code - Code to execute
116
+ * @param language - Programming language (default: python)
117
+ * @returns Execution result
118
+ */
119
+ async execute(code, language = 'python') {
120
+ // Check if language is allowed
121
+ if (!this.codeConfig.allowedLanguages.includes(language)) {
122
+ return {
123
+ success: false,
124
+ output: '',
125
+ error: `Language '${language}' is not allowed. Allowed: ${this.codeConfig.allowedLanguages.join(', ')}`,
126
+ exitCode: 1,
127
+ executionTime: 0,
128
+ };
129
+ }
130
+ const startTime = Date.now();
131
+ try {
132
+ // For safety, we use the sandbox executor if available
133
+ // This is a simplified implementation - full sandbox would use child_process
134
+ if (language === 'javascript' || language === 'typescript') {
135
+ // Use eval for simple JS (NOT SAFE FOR PRODUCTION - use sandbox)
136
+ if (!this.codeConfig.sandbox) {
137
+ const result = eval(code);
138
+ return {
139
+ success: true,
140
+ output: String(result ?? ''),
141
+ exitCode: 0,
142
+ executionTime: (Date.now() - startTime) / 1000,
143
+ };
144
+ }
145
+ }
146
+ // For other languages or sandboxed execution, return placeholder
147
+ return {
148
+ success: false,
149
+ output: '',
150
+ error: `Sandboxed execution for '${language}' requires additional setup. Use sandbox executor.`,
151
+ exitCode: 1,
152
+ executionTime: (Date.now() - startTime) / 1000,
153
+ };
154
+ }
155
+ catch (error) {
156
+ return {
157
+ success: false,
158
+ output: '',
159
+ error: error instanceof Error ? error.message : String(error),
160
+ exitCode: 1,
161
+ executionTime: (Date.now() - startTime) / 1000,
162
+ };
163
+ }
164
+ }
165
+ /**
166
+ * Alias for execute() method.
167
+ */
168
+ async executeCode(code, language = 'python') {
169
+ return this.execute(code, language);
170
+ }
171
+ // =========================================================================
172
+ // Code Review Methods
173
+ // =========================================================================
174
+ /**
175
+ * Review code for issues and improvements.
176
+ *
177
+ * @param code - Code to review
178
+ * @param language - Programming language
179
+ * @returns Review feedback
180
+ */
181
+ async review(code, language) {
182
+ const langHint = language ? ` (${language})` : '';
183
+ const response = await this.agent.chat(`Review the following code${langHint} for issues, bugs, and improvements:\n\n\`\`\`\n${code}\n\`\`\``);
184
+ return response;
185
+ }
186
+ /**
187
+ * Alias for review() method.
188
+ */
189
+ async reviewCode(code, language) {
190
+ return this.review(code, language);
191
+ }
192
+ // =========================================================================
193
+ // Code Refactoring Methods
194
+ // =========================================================================
195
+ /**
196
+ * Refactor code for better quality.
197
+ *
198
+ * @param code - Code to refactor
199
+ * @param instructions - Specific refactoring instructions
200
+ * @returns Refactored code
201
+ */
202
+ async refactor(code, instructions) {
203
+ const prompt = instructions
204
+ ? `Refactor the following code according to these instructions: ${instructions}\n\n\`\`\`\n${code}\n\`\`\``
205
+ : `Refactor the following code for better readability, performance, and maintainability:\n\n\`\`\`\n${code}\n\`\`\``;
206
+ const response = await this.agent.chat(prompt);
207
+ return response;
208
+ }
209
+ /**
210
+ * Fix bugs in code.
211
+ *
212
+ * @param code - Code with bugs
213
+ * @param errorMessage - Optional error message to help identify the bug
214
+ * @returns Fixed code
215
+ */
216
+ async fix(code, errorMessage) {
217
+ const prompt = errorMessage
218
+ ? `Fix the bug in the following code. Error: ${errorMessage}\n\n\`\`\`\n${code}\n\`\`\``
219
+ : `Fix any bugs in the following code:\n\n\`\`\`\n${code}\n\`\`\``;
220
+ const response = await this.agent.chat(prompt);
221
+ return response;
222
+ }
223
+ /**
224
+ * Explain code functionality.
225
+ *
226
+ * @param code - Code to explain
227
+ * @returns Explanation of the code
228
+ */
229
+ async explain(code) {
230
+ const response = await this.agent.chat(`Explain what the following code does in detail:\n\n\`\`\`\n${code}\n\`\`\``);
231
+ return response;
232
+ }
233
+ }
234
+ exports.CodeAgent = CodeAgent;
235
+ // ============================================================================
236
+ // Factory Function
237
+ // ============================================================================
238
+ /**
239
+ * Create a CodeAgent instance.
240
+ *
241
+ * @param config - CodeAgent configuration
242
+ * @returns CodeAgent instance
243
+ */
244
+ function createCodeAgent(config) {
245
+ return new CodeAgent(config);
246
+ }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * EmbeddingAgent - Text embedding generation agent
3
+ *
4
+ * Python parity with praisonaiagents/agent/embedding_agent.py
5
+ * Generates embeddings for text using embedding models.
6
+ */
7
+ /**
8
+ * Configuration for Embedding settings.
9
+ */
10
+ export interface EmbeddingConfig {
11
+ /** Embedding model to use */
12
+ model?: string;
13
+ /** Dimensions for the embedding */
14
+ dimensions?: number;
15
+ /** Batch size for processing multiple texts */
16
+ batchSize?: number;
17
+ /** Timeout in seconds */
18
+ timeout?: number;
19
+ }
20
+ /**
21
+ * Result of embedding generation.
22
+ */
23
+ export interface EmbeddingResult {
24
+ /** The embedding vector */
25
+ embedding: number[];
26
+ /** Model used */
27
+ model: string;
28
+ /** Token usage */
29
+ usage?: {
30
+ promptTokens: number;
31
+ totalTokens: number;
32
+ };
33
+ }
34
+ /**
35
+ * Result of batch embedding generation.
36
+ */
37
+ export interface BatchEmbeddingResult {
38
+ /** Array of embeddings */
39
+ embeddings: number[][];
40
+ /** Model used */
41
+ model: string;
42
+ /** Total token usage */
43
+ usage?: {
44
+ promptTokens: number;
45
+ totalTokens: number;
46
+ };
47
+ }
48
+ /**
49
+ * Configuration for creating an EmbeddingAgent.
50
+ */
51
+ export interface EmbeddingAgentConfig {
52
+ /** Agent name */
53
+ name?: string;
54
+ /** Embedding model */
55
+ llm?: string;
56
+ /** Alias for llm */
57
+ model?: string;
58
+ /** Embedding configuration */
59
+ embedding?: boolean | EmbeddingConfig;
60
+ /** Enable verbose output */
61
+ verbose?: boolean;
62
+ }
63
+ /**
64
+ * Agent for generating text embeddings.
65
+ *
66
+ * @example
67
+ * ```typescript
68
+ * import { EmbeddingAgent } from 'praisonai';
69
+ *
70
+ * const agent = new EmbeddingAgent({});
71
+ *
72
+ * // Generate embedding for text
73
+ * const result = await agent.embed('Hello, world!');
74
+ * console.log(result.embedding.length); // 1536
75
+ *
76
+ * // Generate embeddings for multiple texts
77
+ * const results = await agent.embedMany(['Hello', 'World']);
78
+ * ```
79
+ */
80
+ export declare class EmbeddingAgent {
81
+ static readonly DEFAULT_MODEL = "text-embedding-3-small";
82
+ readonly name: string;
83
+ private readonly model;
84
+ private readonly verbose;
85
+ private readonly embeddingConfig;
86
+ constructor(config: EmbeddingAgentConfig);
87
+ private log;
88
+ /**
89
+ * Generate embedding for a single text.
90
+ *
91
+ * @param text - Text to embed
92
+ * @returns EmbeddingResult with the embedding vector
93
+ */
94
+ embed(text: string): Promise<EmbeddingResult>;
95
+ /**
96
+ * Generate embeddings for multiple texts.
97
+ *
98
+ * @param texts - Array of texts to embed
99
+ * @returns BatchEmbeddingResult with all embeddings
100
+ */
101
+ embedMany(texts: string[]): Promise<BatchEmbeddingResult>;
102
+ /**
103
+ * Calculate cosine similarity between two embeddings.
104
+ */
105
+ cosineSimilarity(a: number[], b: number[]): number;
106
+ /**
107
+ * Find the most similar text from a list.
108
+ */
109
+ findMostSimilar(query: string, candidates: string[]): Promise<{
110
+ text: string;
111
+ similarity: number;
112
+ index: number;
113
+ }>;
114
+ }
115
+ /**
116
+ * Create an EmbeddingAgent instance.
117
+ */
118
+ export declare function createEmbeddingAgent(config: EmbeddingAgentConfig): EmbeddingAgent;
@@ -0,0 +1,151 @@
1
+ "use strict";
2
+ /**
3
+ * EmbeddingAgent - Text embedding generation agent
4
+ *
5
+ * Python parity with praisonaiagents/agent/embedding_agent.py
6
+ * Generates embeddings for text using embedding models.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.EmbeddingAgent = void 0;
10
+ exports.createEmbeddingAgent = createEmbeddingAgent;
11
+ // ============================================================================
12
+ // Default Configuration
13
+ // ============================================================================
14
+ const DEFAULT_EMBEDDING_CONFIG = {
15
+ model: 'text-embedding-3-small',
16
+ dimensions: 1536,
17
+ batchSize: 100,
18
+ timeout: 60,
19
+ };
20
+ // ============================================================================
21
+ // EmbeddingAgent Class
22
+ // ============================================================================
23
+ /**
24
+ * Agent for generating text embeddings.
25
+ *
26
+ * @example
27
+ * ```typescript
28
+ * import { EmbeddingAgent } from 'praisonai';
29
+ *
30
+ * const agent = new EmbeddingAgent({});
31
+ *
32
+ * // Generate embedding for text
33
+ * const result = await agent.embed('Hello, world!');
34
+ * console.log(result.embedding.length); // 1536
35
+ *
36
+ * // Generate embeddings for multiple texts
37
+ * const results = await agent.embedMany(['Hello', 'World']);
38
+ * ```
39
+ */
40
+ class EmbeddingAgent {
41
+ constructor(config) {
42
+ this.name = config.name || 'EmbeddingAgent';
43
+ this.model = config.llm || config.model || process.env.OPENAI_EMBEDDING_MODEL || EmbeddingAgent.DEFAULT_MODEL;
44
+ this.verbose = config.verbose ?? true;
45
+ // Resolve embedding configuration
46
+ if (config.embedding === undefined || config.embedding === true || config.embedding === false) {
47
+ this.embeddingConfig = { ...DEFAULT_EMBEDDING_CONFIG };
48
+ }
49
+ else {
50
+ this.embeddingConfig = { ...DEFAULT_EMBEDDING_CONFIG, ...config.embedding };
51
+ }
52
+ }
53
+ log(message) {
54
+ if (this.verbose) {
55
+ console.log(message);
56
+ }
57
+ }
58
+ /**
59
+ * Generate embedding for a single text.
60
+ *
61
+ * @param text - Text to embed
62
+ * @returns EmbeddingResult with the embedding vector
63
+ */
64
+ async embed(text) {
65
+ this.log(`Generating embedding for text (${text.length} chars)...`);
66
+ // Placeholder implementation - real implementation would call OpenAI
67
+ // For now, return a mock embedding
68
+ const embedding = new Array(this.embeddingConfig.dimensions).fill(0).map(() => Math.random() - 0.5);
69
+ return {
70
+ embedding,
71
+ model: this.model,
72
+ usage: {
73
+ promptTokens: Math.ceil(text.length / 4),
74
+ totalTokens: Math.ceil(text.length / 4),
75
+ },
76
+ };
77
+ }
78
+ /**
79
+ * Generate embeddings for multiple texts.
80
+ *
81
+ * @param texts - Array of texts to embed
82
+ * @returns BatchEmbeddingResult with all embeddings
83
+ */
84
+ async embedMany(texts) {
85
+ this.log(`Generating embeddings for ${texts.length} texts...`);
86
+ const embeddings = [];
87
+ let totalTokens = 0;
88
+ for (const text of texts) {
89
+ const result = await this.embed(text);
90
+ embeddings.push(result.embedding);
91
+ totalTokens += result.usage?.totalTokens || 0;
92
+ }
93
+ return {
94
+ embeddings,
95
+ model: this.model,
96
+ usage: {
97
+ promptTokens: totalTokens,
98
+ totalTokens,
99
+ },
100
+ };
101
+ }
102
+ /**
103
+ * Calculate cosine similarity between two embeddings.
104
+ */
105
+ cosineSimilarity(a, b) {
106
+ if (a.length !== b.length) {
107
+ throw new Error('Embeddings must have the same dimensions');
108
+ }
109
+ let dotProduct = 0;
110
+ let normA = 0;
111
+ let normB = 0;
112
+ for (let i = 0; i < a.length; i++) {
113
+ dotProduct += a[i] * b[i];
114
+ normA += a[i] * a[i];
115
+ normB += b[i] * b[i];
116
+ }
117
+ return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
118
+ }
119
+ /**
120
+ * Find the most similar text from a list.
121
+ */
122
+ async findMostSimilar(query, candidates) {
123
+ const queryResult = await this.embed(query);
124
+ const candidateResults = await this.embedMany(candidates);
125
+ let bestIndex = 0;
126
+ let bestSimilarity = -1;
127
+ for (let i = 0; i < candidateResults.embeddings.length; i++) {
128
+ const similarity = this.cosineSimilarity(queryResult.embedding, candidateResults.embeddings[i]);
129
+ if (similarity > bestSimilarity) {
130
+ bestSimilarity = similarity;
131
+ bestIndex = i;
132
+ }
133
+ }
134
+ return {
135
+ text: candidates[bestIndex],
136
+ similarity: bestSimilarity,
137
+ index: bestIndex,
138
+ };
139
+ }
140
+ }
141
+ exports.EmbeddingAgent = EmbeddingAgent;
142
+ EmbeddingAgent.DEFAULT_MODEL = 'text-embedding-3-small';
143
+ // ============================================================================
144
+ // Factory Function
145
+ // ============================================================================
146
+ /**
147
+ * Create an EmbeddingAgent instance.
148
+ */
149
+ function createEmbeddingAgent(config) {
150
+ return new EmbeddingAgent(config);
151
+ }