@agentionai/agents 0.3.0-beta
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.
- package/README.md +517 -0
- package/dist/agents/Agent.d.ts +29 -0
- package/dist/agents/Agent.js +28 -0
- package/dist/agents/AgentConfig.d.ts +118 -0
- package/dist/agents/AgentConfig.js +3 -0
- package/dist/agents/AgentEvent.d.ts +18 -0
- package/dist/agents/AgentEvent.js +26 -0
- package/dist/agents/BaseAgent.d.ts +82 -0
- package/dist/agents/BaseAgent.js +121 -0
- package/dist/agents/anthropic/ClaudeAgent.d.ts +46 -0
- package/dist/agents/anthropic/ClaudeAgent.js +262 -0
- package/dist/agents/errors/AgentError.d.ts +47 -0
- package/dist/agents/errors/AgentError.js +74 -0
- package/dist/agents/google/GeminiAgent.d.ts +63 -0
- package/dist/agents/google/GeminiAgent.js +395 -0
- package/dist/agents/mistral/MistralAgent.d.ts +47 -0
- package/dist/agents/mistral/MistralAgent.js +313 -0
- package/dist/agents/model-types.d.ts +30 -0
- package/dist/agents/model-types.js +8 -0
- package/dist/agents/openai/OpenAiAgent.d.ts +48 -0
- package/dist/agents/openai/OpenAiAgent.js +338 -0
- package/dist/chunkers/Chunker.d.ts +53 -0
- package/dist/chunkers/Chunker.js +174 -0
- package/dist/chunkers/RecursiveChunker.d.ts +52 -0
- package/dist/chunkers/RecursiveChunker.js +166 -0
- package/dist/chunkers/TextChunker.d.ts +27 -0
- package/dist/chunkers/TextChunker.js +50 -0
- package/dist/chunkers/TokenChunker.d.ts +60 -0
- package/dist/chunkers/TokenChunker.js +176 -0
- package/dist/chunkers/index.d.ts +6 -0
- package/dist/chunkers/index.js +14 -0
- package/dist/chunkers/types.d.ts +95 -0
- package/dist/chunkers/types.js +3 -0
- package/dist/graph/AgentGraph.d.ts +99 -0
- package/dist/graph/AgentGraph.js +115 -0
- package/dist/graph/BaseExecutor.d.ts +86 -0
- package/dist/graph/BaseExecutor.js +61 -0
- package/dist/graph/GraphMetrics.d.ts +143 -0
- package/dist/graph/GraphMetrics.js +264 -0
- package/dist/graph/MapExecutor.d.ts +39 -0
- package/dist/graph/MapExecutor.js +123 -0
- package/dist/graph/ParallelExecutor.d.ts +51 -0
- package/dist/graph/ParallelExecutor.js +103 -0
- package/dist/graph/Pipeline.d.ts +44 -0
- package/dist/graph/Pipeline.js +109 -0
- package/dist/graph/RouterExecutor.d.ts +89 -0
- package/dist/graph/RouterExecutor.js +209 -0
- package/dist/graph/SequentialExecutor.d.ts +44 -0
- package/dist/graph/SequentialExecutor.js +115 -0
- package/dist/graph/VotingSystem.d.ts +54 -0
- package/dist/graph/VotingSystem.js +106 -0
- package/dist/history/History.d.ts +107 -0
- package/dist/history/History.js +166 -0
- package/dist/history/RedisHistory.d.ts +27 -0
- package/dist/history/RedisHistory.js +55 -0
- package/dist/history/transformers.d.ts +102 -0
- package/dist/history/transformers.js +415 -0
- package/dist/history/types.d.ts +130 -0
- package/dist/history/types.js +55 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +48 -0
- package/dist/ingestion/IngestionPipeline.d.ts +86 -0
- package/dist/ingestion/IngestionPipeline.js +266 -0
- package/dist/ingestion/index.d.ts +3 -0
- package/dist/ingestion/index.js +7 -0
- package/dist/ingestion/types.d.ts +74 -0
- package/dist/ingestion/types.js +3 -0
- package/dist/team/Team.d.ts +46 -0
- package/dist/team/Team.js +104 -0
- package/dist/tools/Tool.d.ts +75 -0
- package/dist/tools/Tool.js +137 -0
- package/dist/vectorstore/Embeddings.d.ts +67 -0
- package/dist/vectorstore/Embeddings.js +54 -0
- package/dist/vectorstore/LanceDBVectorStore.d.ts +149 -0
- package/dist/vectorstore/LanceDBVectorStore.js +338 -0
- package/dist/vectorstore/OpenAIEmbeddings.d.ts +45 -0
- package/dist/vectorstore/OpenAIEmbeddings.js +109 -0
- package/dist/vectorstore/VectorStore.d.ts +255 -0
- package/dist/vectorstore/VectorStore.js +216 -0
- package/dist/vectorstore/index.d.ts +28 -0
- package/dist/vectorstore/index.js +35 -0
- package/dist/viz/VizConfig.d.ts +54 -0
- package/dist/viz/VizConfig.js +100 -0
- package/dist/viz/VizReporter.d.ts +127 -0
- package/dist/viz/VizReporter.js +595 -0
- package/dist/viz/index.d.ts +31 -0
- package/dist/viz/index.js +51 -0
- package/dist/viz/types.d.ts +105 -0
- package/dist/viz/types.js +7 -0
- package/package.json +109 -0
- package/readme.md +1 -0
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { FunctionDeclarationsTool, GenerateContentResult, Schema } from "@google/generative-ai";
|
|
2
|
+
import { BaseAgent, BaseAgentConfig, TokenUsage } from "../BaseAgent";
|
|
3
|
+
import { History } from "../../history/History";
|
|
4
|
+
import { GeminiModel } from "../model-types";
|
|
5
|
+
type AgentConfig = BaseAgentConfig & {
|
|
6
|
+
apiKey: string;
|
|
7
|
+
model?: GeminiModel;
|
|
8
|
+
maxTokens?: number;
|
|
9
|
+
candidateCount?: number;
|
|
10
|
+
responseMimeType?: string;
|
|
11
|
+
responseSchema?: Schema;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Agent for Google Gemini models.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```typescript
|
|
18
|
+
* const agent = new GeminiAgent({
|
|
19
|
+
* id: "1",
|
|
20
|
+
* name: "Assistant",
|
|
21
|
+
* description: "A helpful assistant",
|
|
22
|
+
* apiKey: process.env.GOOGLE_API_KEY,
|
|
23
|
+
* });
|
|
24
|
+
*
|
|
25
|
+
* const response = await agent.execute("Hello!");
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
export declare class GeminiAgent extends BaseAgent {
|
|
29
|
+
private client;
|
|
30
|
+
private generativeModel;
|
|
31
|
+
protected config: Partial<AgentConfig>;
|
|
32
|
+
/** Token usage from the last execution (for metrics tracking) */
|
|
33
|
+
lastTokenUsage?: TokenUsage;
|
|
34
|
+
/** Current visualization event ID for tracking */
|
|
35
|
+
private vizEventId?;
|
|
36
|
+
/** Count of tool calls in current execution */
|
|
37
|
+
private currentToolCallCount;
|
|
38
|
+
constructor(config: Omit<AgentConfig, "vendor">, history?: History);
|
|
39
|
+
protected getToolDefinitionsForGemini(): FunctionDeclarationsTool | undefined;
|
|
40
|
+
/**
|
|
41
|
+
* Convert JSON Schema to Gemini's FunctionDeclarationSchema format
|
|
42
|
+
*/
|
|
43
|
+
private convertSchemaToGeminiParams;
|
|
44
|
+
/**
|
|
45
|
+
* Convert a property schema to Gemini Schema type
|
|
46
|
+
*/
|
|
47
|
+
private convertPropertyToSchema;
|
|
48
|
+
/**
|
|
49
|
+
* Map JSON Schema types to Gemini's SchemaType
|
|
50
|
+
*/
|
|
51
|
+
private mapJsonSchemaTypeToGemini;
|
|
52
|
+
protected process(_input: string): Promise<string>;
|
|
53
|
+
execute(input: string): Promise<string>;
|
|
54
|
+
protected handleResponse(response: GenerateContentResult): Promise<string>;
|
|
55
|
+
private handleFunctionCalls;
|
|
56
|
+
protected parseUsage(input: {
|
|
57
|
+
promptTokenCount?: number;
|
|
58
|
+
candidatesTokenCount?: number;
|
|
59
|
+
totalTokenCount?: number;
|
|
60
|
+
}): TokenUsage;
|
|
61
|
+
}
|
|
62
|
+
export {};
|
|
63
|
+
//# sourceMappingURL=GeminiAgent.d.ts.map
|
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.GeminiAgent = void 0;
|
|
4
|
+
const generative_ai_1 = require("@google/generative-ai");
|
|
5
|
+
const BaseAgent_1 = require("../BaseAgent");
|
|
6
|
+
const AgentEvent_1 = require("../AgentEvent");
|
|
7
|
+
const AgentError_1 = require("../errors/AgentError");
|
|
8
|
+
const transformers_1 = require("../../history/transformers");
|
|
9
|
+
const VizReporter_1 = require("../../viz/VizReporter");
|
|
10
|
+
const VizConfig_1 = require("../../viz/VizConfig");
|
|
11
|
+
/**
|
|
12
|
+
* Agent for Google Gemini models.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```typescript
|
|
16
|
+
* const agent = new GeminiAgent({
|
|
17
|
+
* id: "1",
|
|
18
|
+
* name: "Assistant",
|
|
19
|
+
* description: "A helpful assistant",
|
|
20
|
+
* apiKey: process.env.GOOGLE_API_KEY,
|
|
21
|
+
* });
|
|
22
|
+
*
|
|
23
|
+
* const response = await agent.execute("Hello!");
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
class GeminiAgent extends BaseAgent_1.BaseAgent {
|
|
27
|
+
constructor(config, history) {
|
|
28
|
+
super({ ...config, vendor: "gemini" }, history);
|
|
29
|
+
/** Count of tool calls in current execution */
|
|
30
|
+
this.currentToolCallCount = 0;
|
|
31
|
+
this.client = new generative_ai_1.GoogleGenerativeAI(config.apiKey);
|
|
32
|
+
// Merge flat config with nested vendorConfig
|
|
33
|
+
const vendorConfig = config.vendorConfig?.gemini || {};
|
|
34
|
+
const candidateCount = config.candidateCount ?? vendorConfig.candidateCount;
|
|
35
|
+
const responseMimeType = config.responseMimeType ?? vendorConfig.responseMimeType;
|
|
36
|
+
const responseSchema = config.responseSchema ?? vendorConfig.responseSchema;
|
|
37
|
+
this.config = {
|
|
38
|
+
model: config.model || "gemini-2.0-flash",
|
|
39
|
+
maxTokens: config.maxTokens || 1024,
|
|
40
|
+
apiKey: config.apiKey,
|
|
41
|
+
temperature: config.temperature,
|
|
42
|
+
topP: config.topP,
|
|
43
|
+
topK: config.topK,
|
|
44
|
+
stopSequences: config.stopSequences,
|
|
45
|
+
candidateCount,
|
|
46
|
+
responseMimeType,
|
|
47
|
+
responseSchema,
|
|
48
|
+
};
|
|
49
|
+
// Initialize the model
|
|
50
|
+
this.generativeModel = this.client.getGenerativeModel({
|
|
51
|
+
model: this.config.model,
|
|
52
|
+
});
|
|
53
|
+
// Add system message to history (skips if already exists with same content)
|
|
54
|
+
this.addSystemMessage(this.getSystemMessage());
|
|
55
|
+
}
|
|
56
|
+
getToolDefinitionsForGemini() {
|
|
57
|
+
const tools = Array.from(this.tools.values());
|
|
58
|
+
if (tools.length === 0) {
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
functionDeclarations: tools.map((tool) => {
|
|
63
|
+
const prompt = tool.getPrompt();
|
|
64
|
+
// Cast to unknown first to avoid type conflicts
|
|
65
|
+
const schema = prompt.input_schema;
|
|
66
|
+
return {
|
|
67
|
+
name: prompt.name,
|
|
68
|
+
description: prompt.description,
|
|
69
|
+
parameters: this.convertSchemaToGeminiParams(schema),
|
|
70
|
+
};
|
|
71
|
+
}),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Convert JSON Schema to Gemini's FunctionDeclarationSchema format
|
|
76
|
+
*/
|
|
77
|
+
convertSchemaToGeminiParams(schema) {
|
|
78
|
+
const properties = {};
|
|
79
|
+
if (schema.properties) {
|
|
80
|
+
const props = schema.properties;
|
|
81
|
+
for (const [key, value] of Object.entries(props)) {
|
|
82
|
+
properties[key] = this.convertPropertyToSchema(value);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return {
|
|
86
|
+
type: generative_ai_1.SchemaType.OBJECT,
|
|
87
|
+
properties,
|
|
88
|
+
description: schema.description,
|
|
89
|
+
required: schema.required,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Convert a property schema to Gemini Schema type
|
|
94
|
+
*/
|
|
95
|
+
convertPropertyToSchema(prop) {
|
|
96
|
+
const type = prop.type;
|
|
97
|
+
const description = prop.description;
|
|
98
|
+
switch (type) {
|
|
99
|
+
case "string":
|
|
100
|
+
if (prop.enum) {
|
|
101
|
+
return {
|
|
102
|
+
type: generative_ai_1.SchemaType.STRING,
|
|
103
|
+
format: "enum",
|
|
104
|
+
enum: prop.enum,
|
|
105
|
+
description,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
return { type: generative_ai_1.SchemaType.STRING, description };
|
|
109
|
+
case "number":
|
|
110
|
+
return { type: generative_ai_1.SchemaType.NUMBER, description };
|
|
111
|
+
case "integer":
|
|
112
|
+
return { type: generative_ai_1.SchemaType.INTEGER, description };
|
|
113
|
+
case "boolean":
|
|
114
|
+
return { type: generative_ai_1.SchemaType.BOOLEAN, description };
|
|
115
|
+
case "array":
|
|
116
|
+
return {
|
|
117
|
+
type: generative_ai_1.SchemaType.ARRAY,
|
|
118
|
+
items: this.convertPropertyToSchema(prop.items),
|
|
119
|
+
description,
|
|
120
|
+
};
|
|
121
|
+
case "object":
|
|
122
|
+
const objProps = {};
|
|
123
|
+
if (prop.properties) {
|
|
124
|
+
const subProps = prop.properties;
|
|
125
|
+
for (const [key, value] of Object.entries(subProps)) {
|
|
126
|
+
objProps[key] = this.convertPropertyToSchema(value);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return {
|
|
130
|
+
type: generative_ai_1.SchemaType.OBJECT,
|
|
131
|
+
properties: objProps,
|
|
132
|
+
description,
|
|
133
|
+
required: prop.required,
|
|
134
|
+
};
|
|
135
|
+
default:
|
|
136
|
+
return { type: generative_ai_1.SchemaType.STRING, description };
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Map JSON Schema types to Gemini's SchemaType
|
|
141
|
+
*/
|
|
142
|
+
mapJsonSchemaTypeToGemini(type) {
|
|
143
|
+
switch (type) {
|
|
144
|
+
case "string":
|
|
145
|
+
return generative_ai_1.SchemaType.STRING;
|
|
146
|
+
case "number":
|
|
147
|
+
return generative_ai_1.SchemaType.NUMBER;
|
|
148
|
+
case "integer":
|
|
149
|
+
return generative_ai_1.SchemaType.INTEGER;
|
|
150
|
+
case "boolean":
|
|
151
|
+
return generative_ai_1.SchemaType.BOOLEAN;
|
|
152
|
+
case "array":
|
|
153
|
+
return generative_ai_1.SchemaType.ARRAY;
|
|
154
|
+
case "object":
|
|
155
|
+
return generative_ai_1.SchemaType.OBJECT;
|
|
156
|
+
default:
|
|
157
|
+
return generative_ai_1.SchemaType.STRING;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
async process(_input) {
|
|
161
|
+
return "";
|
|
162
|
+
}
|
|
163
|
+
async execute(input) {
|
|
164
|
+
this.emit(AgentEvent_1.AgentEvent.BEFORE_EXECUTE, input);
|
|
165
|
+
// Reset token usage for this execution
|
|
166
|
+
this.lastTokenUsage = undefined;
|
|
167
|
+
this.currentToolCallCount = 0;
|
|
168
|
+
// Start visualization reporting
|
|
169
|
+
if (VizConfig_1.vizConfig.isEnabled()) {
|
|
170
|
+
this.vizEventId = VizReporter_1.vizReporter.agentStart(this.id, this.name, this.config.model, "gemini", input);
|
|
171
|
+
}
|
|
172
|
+
if (this.history.transient) {
|
|
173
|
+
this.history.clear();
|
|
174
|
+
// Re-add system message after clear
|
|
175
|
+
this.addSystemMessage(this.getSystemMessage());
|
|
176
|
+
}
|
|
177
|
+
this.addTextToHistory("user", input);
|
|
178
|
+
try {
|
|
179
|
+
const contents = transformers_1.geminiTransformer.toProvider(this.history.entries);
|
|
180
|
+
const systemMessage = this.history.getSystemMessage();
|
|
181
|
+
const tools = this.getToolDefinitionsForGemini();
|
|
182
|
+
const response = await this.generativeModel.generateContent({
|
|
183
|
+
contents,
|
|
184
|
+
systemInstruction: systemMessage,
|
|
185
|
+
tools: tools ? [tools] : undefined,
|
|
186
|
+
generationConfig: {
|
|
187
|
+
maxOutputTokens: this.config.maxTokens,
|
|
188
|
+
temperature: this.config.temperature,
|
|
189
|
+
topP: this.config.topP,
|
|
190
|
+
topK: this.config.topK,
|
|
191
|
+
stopSequences: this.config.stopSequences,
|
|
192
|
+
candidateCount: this.config.candidateCount,
|
|
193
|
+
responseMimeType: this.config.responseMimeType,
|
|
194
|
+
responseSchema: this.config.responseSchema,
|
|
195
|
+
},
|
|
196
|
+
});
|
|
197
|
+
this.emit(AgentEvent_1.AgentEvent.AFTER_EXECUTE, response);
|
|
198
|
+
return await this.handleResponse(response);
|
|
199
|
+
}
|
|
200
|
+
catch (error) {
|
|
201
|
+
const err = error;
|
|
202
|
+
if (err.status) {
|
|
203
|
+
const apiError = new AgentError_1.ApiError(`Gemini API error: ${err.message || "Unknown error"}`, err.status, error);
|
|
204
|
+
this.emit(AgentEvent_1.AgentEvent.ERROR, apiError);
|
|
205
|
+
// Report error to viz
|
|
206
|
+
if (this.vizEventId) {
|
|
207
|
+
VizReporter_1.vizReporter.agentError(this.vizEventId, "ApiError", apiError.message, err.status === 429);
|
|
208
|
+
this.vizEventId = undefined;
|
|
209
|
+
}
|
|
210
|
+
throw apiError;
|
|
211
|
+
}
|
|
212
|
+
else {
|
|
213
|
+
const executionError = new AgentError_1.ExecutionError(`Error executing agent: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
214
|
+
this.emit(AgentEvent_1.AgentEvent.ERROR, executionError);
|
|
215
|
+
// Report error to viz
|
|
216
|
+
if (this.vizEventId) {
|
|
217
|
+
VizReporter_1.vizReporter.agentError(this.vizEventId, "ExecutionError", executionError.message, false);
|
|
218
|
+
this.vizEventId = undefined;
|
|
219
|
+
}
|
|
220
|
+
throw executionError;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
async handleResponse(response) {
|
|
225
|
+
const result = response.response;
|
|
226
|
+
// Parse and track usage
|
|
227
|
+
if (result.usageMetadata) {
|
|
228
|
+
const usage = this.parseUsage(result.usageMetadata);
|
|
229
|
+
if (this.lastTokenUsage) {
|
|
230
|
+
this.lastTokenUsage.input_tokens += usage.input_tokens;
|
|
231
|
+
this.lastTokenUsage.output_tokens += usage.output_tokens;
|
|
232
|
+
this.lastTokenUsage.total_tokens += usage.total_tokens;
|
|
233
|
+
}
|
|
234
|
+
else {
|
|
235
|
+
this.lastTokenUsage = { ...usage };
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
// Check for finish reason
|
|
239
|
+
const candidate = result.candidates?.[0];
|
|
240
|
+
if (!candidate) {
|
|
241
|
+
const error = new AgentError_1.ExecutionError("No candidates in Gemini response");
|
|
242
|
+
this.emit(AgentEvent_1.AgentEvent.ERROR, error);
|
|
243
|
+
throw error;
|
|
244
|
+
}
|
|
245
|
+
if (candidate.finishReason === "MAX_TOKENS") {
|
|
246
|
+
const error = new AgentError_1.MaxTokensExceededError("Response exceeded maximum token limit", this.config.maxTokens || 1024);
|
|
247
|
+
this.emit(AgentEvent_1.AgentEvent.MAX_TOKENS_EXCEEDED, error);
|
|
248
|
+
this.emit(AgentEvent_1.AgentEvent.ERROR, error);
|
|
249
|
+
// Report error to viz
|
|
250
|
+
if (this.vizEventId) {
|
|
251
|
+
VizReporter_1.vizReporter.agentError(this.vizEventId, "MaxTokensExceededError", error.message, false);
|
|
252
|
+
this.vizEventId = undefined;
|
|
253
|
+
}
|
|
254
|
+
throw error;
|
|
255
|
+
}
|
|
256
|
+
const parts = candidate.content?.parts || [];
|
|
257
|
+
const functionCalls = parts.filter((part) => "functionCall" in part);
|
|
258
|
+
// If no function calls, return text response
|
|
259
|
+
if (functionCalls.length === 0) {
|
|
260
|
+
const textParts = parts.filter((part) => "text" in part);
|
|
261
|
+
const textContent = textParts
|
|
262
|
+
.map((part) => ("text" in part ? part.text : ""))
|
|
263
|
+
.join("");
|
|
264
|
+
// Add to history in normalized format
|
|
265
|
+
const entry = transformers_1.geminiTransformer.fromProviderContent("assistant", parts);
|
|
266
|
+
this.addToHistory(entry);
|
|
267
|
+
this.emit(AgentEvent_1.AgentEvent.DONE, result, this.lastTokenUsage);
|
|
268
|
+
// Report completion to viz
|
|
269
|
+
if (this.vizEventId) {
|
|
270
|
+
VizReporter_1.vizReporter.agentComplete(this.vizEventId, {
|
|
271
|
+
input: this.lastTokenUsage?.input_tokens || 0,
|
|
272
|
+
output: this.lastTokenUsage?.output_tokens || 0,
|
|
273
|
+
total: this.lastTokenUsage?.total_tokens || 0,
|
|
274
|
+
}, "end_turn", this.currentToolCallCount > 0, this.currentToolCallCount, textContent);
|
|
275
|
+
this.vizEventId = undefined;
|
|
276
|
+
}
|
|
277
|
+
return textContent;
|
|
278
|
+
}
|
|
279
|
+
// Handle function calls
|
|
280
|
+
try {
|
|
281
|
+
this.emit(AgentEvent_1.AgentEvent.TOOL_USE, functionCalls);
|
|
282
|
+
// Add assistant response with function calls to history (normalized)
|
|
283
|
+
const assistantEntry = transformers_1.geminiTransformer.fromProviderContent("assistant", parts);
|
|
284
|
+
this.addToHistory(assistantEntry);
|
|
285
|
+
const toolResults = await this.handleFunctionCalls(functionCalls);
|
|
286
|
+
// Add tool results to history (normalized)
|
|
287
|
+
for (const tr of toolResults) {
|
|
288
|
+
const resultEntry = transformers_1.geminiTransformer.toolResultEntry(tr.name, tr.response);
|
|
289
|
+
this.addToHistory(resultEntry);
|
|
290
|
+
}
|
|
291
|
+
// Continue conversation
|
|
292
|
+
try {
|
|
293
|
+
const newContents = transformers_1.geminiTransformer.toProvider(this.history.entries);
|
|
294
|
+
const systemMessage = this.history.getSystemMessage();
|
|
295
|
+
const tools = this.getToolDefinitionsForGemini();
|
|
296
|
+
const newResponse = await this.generativeModel.generateContent({
|
|
297
|
+
contents: newContents,
|
|
298
|
+
systemInstruction: systemMessage,
|
|
299
|
+
tools: tools ? [tools] : undefined,
|
|
300
|
+
generationConfig: {
|
|
301
|
+
maxOutputTokens: this.config.maxTokens,
|
|
302
|
+
temperature: this.config.temperature,
|
|
303
|
+
topP: this.config.topP,
|
|
304
|
+
topK: this.config.topK,
|
|
305
|
+
stopSequences: this.config.stopSequences,
|
|
306
|
+
candidateCount: this.config.candidateCount,
|
|
307
|
+
responseMimeType: this.config.responseMimeType,
|
|
308
|
+
responseSchema: this.config.responseSchema,
|
|
309
|
+
},
|
|
310
|
+
});
|
|
311
|
+
this.emit(AgentEvent_1.AgentEvent.AFTER_EXECUTE, newResponse);
|
|
312
|
+
return this.handleResponse(newResponse);
|
|
313
|
+
}
|
|
314
|
+
catch (error) {
|
|
315
|
+
const err = error;
|
|
316
|
+
if (err.status) {
|
|
317
|
+
const apiError = new AgentError_1.ApiError(`Gemini API error during tool response: ${err.message || "Unknown error"}`, err.status, error);
|
|
318
|
+
this.emit(AgentEvent_1.AgentEvent.ERROR, apiError);
|
|
319
|
+
throw apiError;
|
|
320
|
+
}
|
|
321
|
+
else {
|
|
322
|
+
throw new AgentError_1.ExecutionError(`Error handling tool response: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
catch (error) {
|
|
327
|
+
if (error instanceof AgentError_1.ToolExecutionError) {
|
|
328
|
+
this.emit(AgentEvent_1.AgentEvent.TOOL_ERROR, error);
|
|
329
|
+
throw error;
|
|
330
|
+
}
|
|
331
|
+
const toolError = new AgentError_1.ExecutionError(`Error during tool execution: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
332
|
+
this.emit(AgentEvent_1.AgentEvent.ERROR, toolError);
|
|
333
|
+
// Report error to viz
|
|
334
|
+
if (this.vizEventId) {
|
|
335
|
+
VizReporter_1.vizReporter.agentError(this.vizEventId, "ExecutionError", toolError.message, false);
|
|
336
|
+
this.vizEventId = undefined;
|
|
337
|
+
}
|
|
338
|
+
throw toolError;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
async handleFunctionCalls(functionCalls) {
|
|
342
|
+
if (!functionCalls.length) {
|
|
343
|
+
throw new AgentError_1.ExecutionError("No function calls found in response");
|
|
344
|
+
}
|
|
345
|
+
// Track tool call count for viz reporting
|
|
346
|
+
this.currentToolCallCount += functionCalls.length;
|
|
347
|
+
const results = await Promise.all(functionCalls.map(async (part) => {
|
|
348
|
+
const fc = part.functionCall;
|
|
349
|
+
const toolName = fc.name;
|
|
350
|
+
const tool = this.tools.get(toolName);
|
|
351
|
+
if (!tool) {
|
|
352
|
+
const errorMessage = `Tool '${toolName}' not found`;
|
|
353
|
+
const error = new AgentError_1.ToolExecutionError(errorMessage, toolName, fc.args);
|
|
354
|
+
if (this.debug) {
|
|
355
|
+
console.error(error);
|
|
356
|
+
}
|
|
357
|
+
return {
|
|
358
|
+
name: toolName,
|
|
359
|
+
response: JSON.stringify({ error: errorMessage }),
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
try {
|
|
363
|
+
const args = (fc.args || {});
|
|
364
|
+
const result = await tool.execute(this.getId(), this.getName(), args, toolName, // Gemini uses function name as ID
|
|
365
|
+
this.config.model, "gemini");
|
|
366
|
+
return {
|
|
367
|
+
name: toolName,
|
|
368
|
+
response: JSON.stringify(result),
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
catch (error) {
|
|
372
|
+
const errorMessage = `Error executing tool '${toolName}': ${error instanceof Error ? error.message : "Unknown error"}`;
|
|
373
|
+
if (this.debug) {
|
|
374
|
+
console.error(errorMessage);
|
|
375
|
+
}
|
|
376
|
+
const toolError = new AgentError_1.ToolExecutionError(errorMessage, toolName, fc.args);
|
|
377
|
+
this.emit(AgentEvent_1.AgentEvent.TOOL_ERROR, toolError);
|
|
378
|
+
return {
|
|
379
|
+
name: toolName,
|
|
380
|
+
response: JSON.stringify({ error: errorMessage }),
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
}));
|
|
384
|
+
return results;
|
|
385
|
+
}
|
|
386
|
+
parseUsage(input) {
|
|
387
|
+
return {
|
|
388
|
+
input_tokens: input.promptTokenCount || 0,
|
|
389
|
+
output_tokens: input.candidatesTokenCount || 0,
|
|
390
|
+
total_tokens: input.totalTokenCount || 0,
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
exports.GeminiAgent = GeminiAgent;
|
|
395
|
+
//# sourceMappingURL=GeminiAgent.js.map
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { BaseAgent, BaseAgentConfig, TokenUsage } from "../BaseAgent";
|
|
2
|
+
import { History } from "../../history/History";
|
|
3
|
+
import { ChatCompletionResponse, Tool, UsageInfo } from "@mistralai/mistralai/models/components";
|
|
4
|
+
import { MistralModel } from "../model-types";
|
|
5
|
+
type AgentConfig = BaseAgentConfig & {
|
|
6
|
+
apiKey: string;
|
|
7
|
+
model?: MistralModel;
|
|
8
|
+
maxTokens?: number;
|
|
9
|
+
disableParallelToolUse?: boolean;
|
|
10
|
+
safePrompt?: boolean;
|
|
11
|
+
randomSeed?: number;
|
|
12
|
+
rateLimitDelay?: number;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Agent for Mistral models.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```typescript
|
|
19
|
+
* const agent = new MistralAgent({
|
|
20
|
+
* id: "1",
|
|
21
|
+
* name: "Assistant",
|
|
22
|
+
* description: "A helpful assistant",
|
|
23
|
+
* apiKey: process.env.MISTRAL_API_KEY,
|
|
24
|
+
* });
|
|
25
|
+
*
|
|
26
|
+
* const response = await agent.execute("Hello!");
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
export declare class MistralAgent extends BaseAgent {
|
|
30
|
+
private client;
|
|
31
|
+
protected config: Partial<AgentConfig>;
|
|
32
|
+
/** Token usage from the last execution (for metrics tracking) */
|
|
33
|
+
lastTokenUsage?: TokenUsage;
|
|
34
|
+
/** Current visualization event ID for tracking */
|
|
35
|
+
private vizEventId?;
|
|
36
|
+
/** Count of tool calls in current execution */
|
|
37
|
+
private currentToolCallCount;
|
|
38
|
+
constructor(config: Omit<AgentConfig, "vendor">, history?: History);
|
|
39
|
+
protected getToolDefinitions(): Tool[];
|
|
40
|
+
protected process(_input: string): Promise<string>;
|
|
41
|
+
execute(input: string): Promise<string>;
|
|
42
|
+
protected handleResponse(response: ChatCompletionResponse): Promise<string>;
|
|
43
|
+
private handleToolCalls;
|
|
44
|
+
protected parseUsage(input: UsageInfo): TokenUsage;
|
|
45
|
+
}
|
|
46
|
+
export {};
|
|
47
|
+
//# sourceMappingURL=MistralAgent.d.ts.map
|