@misgara/ai-agent 1.0.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.
- package/dist/core/AgentBuilder.d.ts +101 -0
- package/dist/core/AgentBuilder.d.ts.map +1 -0
- package/dist/core/AgentBuilder.js +281 -0
- package/dist/core/AgentBuilder.js.map +1 -0
- package/dist/core/types.d.ts +60 -0
- package/dist/core/types.d.ts.map +1 -0
- package/dist/core/types.js +2 -0
- package/dist/core/types.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +76 -0
- package/dist/index.js.map +1 -0
- package/dist/infrastructure/InMemory.d.ts +20 -0
- package/dist/infrastructure/InMemory.d.ts.map +1 -0
- package/dist/infrastructure/InMemory.js +26 -0
- package/dist/infrastructure/InMemory.js.map +1 -0
- package/dist/infrastructure/RedisMemory.d.ts +26 -0
- package/dist/infrastructure/RedisMemory.d.ts.map +1 -0
- package/dist/infrastructure/RedisMemory.js +39 -0
- package/dist/infrastructure/RedisMemory.js.map +1 -0
- package/dist/tools/common.d.ts +33 -0
- package/dist/tools/common.d.ts.map +1 -0
- package/dist/tools/common.js +105 -0
- package/dist/tools/common.js.map +1 -0
- package/package.json +44 -0
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { type ToolSet, type LanguageModel, type StreamTextResult } from 'ai';
|
|
2
|
+
import type { IMemoryAdapter, AgentResult } from './types.js';
|
|
3
|
+
type GeminiModel = 'gemini-1.5-pro' | 'gemini-1.5-flash' | 'gemini-2.0-flash' | 'gemini-3-flash-preview';
|
|
4
|
+
type OpenAIModel = 'gpt-4o' | 'gpt-4o-mini' | 'gpt-5' | 'gpt-5-mini' | 'gpt-5-nano' | 'gpt-5.2' | 'o1' | 'o1-mini' | 'o3' | 'o3-mini' | 'o3-pro' | 'o4-mini';
|
|
5
|
+
/**
|
|
6
|
+
* AgentBuilder - Fluent interface for building AI agents
|
|
7
|
+
* Supports both Google Gemini and OpenAI models
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```typescript
|
|
11
|
+
* // Using Gemini
|
|
12
|
+
* const agent = new AgentBuilder()
|
|
13
|
+
* .useGemini('gemini-3-flash-preview')
|
|
14
|
+
* .setSystem('You are a helpful assistant.')
|
|
15
|
+
* .addTools({ time: CommonTools.time });
|
|
16
|
+
*
|
|
17
|
+
* // Using OpenAI
|
|
18
|
+
* const agent = new AgentBuilder()
|
|
19
|
+
* .useOpenAI('gpt-4o-mini')
|
|
20
|
+
* .setSystem('You are a helpful assistant.')
|
|
21
|
+
* .addTools({ time: CommonTools.time });
|
|
22
|
+
*
|
|
23
|
+
* const result = await agent.run('Hello!');
|
|
24
|
+
* console.log(result.text);
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
export declare class AgentBuilder {
|
|
28
|
+
private model;
|
|
29
|
+
private systemPrompt;
|
|
30
|
+
private tools;
|
|
31
|
+
private memory?;
|
|
32
|
+
private sessionId?;
|
|
33
|
+
private maxSteps;
|
|
34
|
+
private temperature;
|
|
35
|
+
private maxOutputTokens?;
|
|
36
|
+
/**
|
|
37
|
+
* Sets a Google Gemini model
|
|
38
|
+
*/
|
|
39
|
+
useGemini(modelId: GeminiModel): this;
|
|
40
|
+
/**
|
|
41
|
+
* Sets an OpenAI model
|
|
42
|
+
*/
|
|
43
|
+
useOpenAI(modelId: OpenAIModel): this;
|
|
44
|
+
/**
|
|
45
|
+
* @deprecated Use useGemini() instead
|
|
46
|
+
* Sets the Gemini model to use (legacy method)
|
|
47
|
+
*/
|
|
48
|
+
useModel(modelId: GeminiModel): this;
|
|
49
|
+
/**
|
|
50
|
+
* Sets a custom LanguageModel (for other providers like Anthropic, Mistral, etc.)
|
|
51
|
+
*/
|
|
52
|
+
useCustomModel(model: LanguageModel): this;
|
|
53
|
+
/**
|
|
54
|
+
* Sets the system prompt
|
|
55
|
+
*/
|
|
56
|
+
setSystem(prompt: string): this;
|
|
57
|
+
/**
|
|
58
|
+
* Configures memory persistence for conversation history
|
|
59
|
+
*/
|
|
60
|
+
withMemory(adapter: IMemoryAdapter, sessionId: string): this;
|
|
61
|
+
/**
|
|
62
|
+
* Adds tools to the agent (enables agentic behavior with multiple steps)
|
|
63
|
+
* Can be called multiple times to add more tools
|
|
64
|
+
*/
|
|
65
|
+
addTools(tools: ToolSet): this;
|
|
66
|
+
/**
|
|
67
|
+
* Sets the temperature for generation (0-2)
|
|
68
|
+
*/
|
|
69
|
+
setTemperature(temp: number): this;
|
|
70
|
+
/**
|
|
71
|
+
* Sets maximum steps for tool call loops
|
|
72
|
+
* Higher values allow more complex multi-step operations
|
|
73
|
+
*/
|
|
74
|
+
setMaxSteps(steps: number): this;
|
|
75
|
+
/**
|
|
76
|
+
* Sets maximum output tokens for generation
|
|
77
|
+
*/
|
|
78
|
+
setMaxOutputTokens(tokens: number): this;
|
|
79
|
+
private formatStepResult;
|
|
80
|
+
/**
|
|
81
|
+
* Runs the agent with a user prompt
|
|
82
|
+
* @param userPrompt - The user's message
|
|
83
|
+
* @param imageUrl - Optional image URL or base64 for multimodal input
|
|
84
|
+
*/
|
|
85
|
+
run(userPrompt: string, imageUrl?: string): Promise<AgentResult>;
|
|
86
|
+
/**
|
|
87
|
+
* Runs the agent without saving to memory (stateless)
|
|
88
|
+
*/
|
|
89
|
+
runStateless(userPrompt: string, imageUrl?: string): Promise<AgentResult>;
|
|
90
|
+
/**
|
|
91
|
+
* Runs the agent in Streaming mode
|
|
92
|
+
* Automatically saves history on finish
|
|
93
|
+
*/
|
|
94
|
+
stream(userPrompt: string, imageUrl?: string): Promise<StreamTextResult<ToolSet, any>>;
|
|
95
|
+
/**
|
|
96
|
+
* Stateless version of Streaming (no persistence)
|
|
97
|
+
*/
|
|
98
|
+
streamStateless(userPrompt: string, imageUrl?: string): Promise<StreamTextResult<ToolSet, any>>;
|
|
99
|
+
}
|
|
100
|
+
export {};
|
|
101
|
+
//# sourceMappingURL=AgentBuilder.d.ts.map
|
|
@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GAAG,IAAI;IAM5D;;;OAGG;IACH,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI;IAS9B;;OAEG;IACH,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAKlC;;;OAGG;IACH,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAKhC;;OAEG;IACH,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAOxC,OAAO,CAAC,gBAAgB;IAsBxB;;;;OAIG;IACG,GAAG,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC;IAoDtE;;OAEG;IACG,YAAY,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC;IAmC/E;;;OAGG;IACG,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;IA2C5F;;OAEG;IACG,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;CAuBxG"}
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
// src/core/AgentBuilder.ts
|
|
2
|
+
import { generateText, streamText, stepCountIs } from 'ai';
|
|
3
|
+
import { google } from '@ai-sdk/google';
|
|
4
|
+
import { openai } from '@ai-sdk/openai';
|
|
5
|
+
/**
|
|
6
|
+
* AgentBuilder - Fluent interface for building AI agents
|
|
7
|
+
* Supports both Google Gemini and OpenAI models
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```typescript
|
|
11
|
+
* // Using Gemini
|
|
12
|
+
* const agent = new AgentBuilder()
|
|
13
|
+
* .useGemini('gemini-3-flash-preview')
|
|
14
|
+
* .setSystem('You are a helpful assistant.')
|
|
15
|
+
* .addTools({ time: CommonTools.time });
|
|
16
|
+
*
|
|
17
|
+
* // Using OpenAI
|
|
18
|
+
* const agent = new AgentBuilder()
|
|
19
|
+
* .useOpenAI('gpt-4o-mini')
|
|
20
|
+
* .setSystem('You are a helpful assistant.')
|
|
21
|
+
* .addTools({ time: CommonTools.time });
|
|
22
|
+
*
|
|
23
|
+
* const result = await agent.run('Hello!');
|
|
24
|
+
* console.log(result.text);
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
export class AgentBuilder {
|
|
28
|
+
model = google('gemini-3-flash-preview');
|
|
29
|
+
systemPrompt = 'Eres un asistente útil y directo.';
|
|
30
|
+
tools = {};
|
|
31
|
+
memory;
|
|
32
|
+
sessionId;
|
|
33
|
+
maxSteps = 1; // 1 = Single turn, >1 = Agent mode with tool loops
|
|
34
|
+
temperature = 0.5;
|
|
35
|
+
maxOutputTokens;
|
|
36
|
+
// --- CONFIGURATION (Fluent Interface) ---
|
|
37
|
+
/**
|
|
38
|
+
* Sets a Google Gemini model
|
|
39
|
+
*/
|
|
40
|
+
useGemini(modelId) {
|
|
41
|
+
this.model = google(modelId);
|
|
42
|
+
return this;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Sets an OpenAI model
|
|
46
|
+
*/
|
|
47
|
+
useOpenAI(modelId) {
|
|
48
|
+
this.model = openai(modelId);
|
|
49
|
+
return this;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* @deprecated Use useGemini() instead
|
|
53
|
+
* Sets the Gemini model to use (legacy method)
|
|
54
|
+
*/
|
|
55
|
+
useModel(modelId) {
|
|
56
|
+
return this.useGemini(modelId);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Sets a custom LanguageModel (for other providers like Anthropic, Mistral, etc.)
|
|
60
|
+
*/
|
|
61
|
+
useCustomModel(model) {
|
|
62
|
+
this.model = model;
|
|
63
|
+
return this;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Sets the system prompt
|
|
67
|
+
*/
|
|
68
|
+
setSystem(prompt) {
|
|
69
|
+
this.systemPrompt = prompt;
|
|
70
|
+
return this;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Configures memory persistence for conversation history
|
|
74
|
+
*/
|
|
75
|
+
withMemory(adapter, sessionId) {
|
|
76
|
+
this.memory = adapter;
|
|
77
|
+
this.sessionId = sessionId;
|
|
78
|
+
return this;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Adds tools to the agent (enables agentic behavior with multiple steps)
|
|
82
|
+
* Can be called multiple times to add more tools
|
|
83
|
+
*/
|
|
84
|
+
addTools(tools) {
|
|
85
|
+
this.tools = { ...this.tools, ...tools };
|
|
86
|
+
// If adding tools, enable agentic behavior
|
|
87
|
+
if (this.maxSteps === 1) {
|
|
88
|
+
this.maxSteps = 10;
|
|
89
|
+
}
|
|
90
|
+
return this;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Sets the temperature for generation (0-2)
|
|
94
|
+
*/
|
|
95
|
+
setTemperature(temp) {
|
|
96
|
+
this.temperature = Math.max(0, Math.min(2, temp));
|
|
97
|
+
return this;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Sets maximum steps for tool call loops
|
|
101
|
+
* Higher values allow more complex multi-step operations
|
|
102
|
+
*/
|
|
103
|
+
setMaxSteps(steps) {
|
|
104
|
+
this.maxSteps = Math.max(1, steps);
|
|
105
|
+
return this;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Sets maximum output tokens for generation
|
|
109
|
+
*/
|
|
110
|
+
setMaxOutputTokens(tokens) {
|
|
111
|
+
this.maxOutputTokens = tokens;
|
|
112
|
+
return this;
|
|
113
|
+
}
|
|
114
|
+
// --- PRIVATE HELPERS ---
|
|
115
|
+
formatStepResult(steps) {
|
|
116
|
+
return steps.map((step) => ({
|
|
117
|
+
text: step.text,
|
|
118
|
+
finishReason: step.finishReason,
|
|
119
|
+
toolCalls: step.toolCalls.map((tc) => ({
|
|
120
|
+
toolName: tc.toolName,
|
|
121
|
+
input: tc.input,
|
|
122
|
+
})),
|
|
123
|
+
toolResults: step.toolResults.map((tr) => ({
|
|
124
|
+
toolName: tr.toolName,
|
|
125
|
+
output: tr.output,
|
|
126
|
+
})),
|
|
127
|
+
}));
|
|
128
|
+
}
|
|
129
|
+
// --- EXECUTION ---
|
|
130
|
+
/**
|
|
131
|
+
* Runs the agent with a user prompt
|
|
132
|
+
* @param userPrompt - The user's message
|
|
133
|
+
* @param imageUrl - Optional image URL or base64 for multimodal input
|
|
134
|
+
*/
|
|
135
|
+
async run(userPrompt, imageUrl) {
|
|
136
|
+
// 1. Load History
|
|
137
|
+
let history = [];
|
|
138
|
+
if (this.memory && this.sessionId) {
|
|
139
|
+
history = await this.memory.get(this.sessionId);
|
|
140
|
+
}
|
|
141
|
+
// 2. Prepare Current Message (supports multimodal)
|
|
142
|
+
const currentMessage = {
|
|
143
|
+
role: 'user',
|
|
144
|
+
content: imageUrl
|
|
145
|
+
? [
|
|
146
|
+
{ type: 'text', text: userPrompt },
|
|
147
|
+
{ type: 'image', image: imageUrl },
|
|
148
|
+
]
|
|
149
|
+
: userPrompt,
|
|
150
|
+
};
|
|
151
|
+
// 3. Call AI SDK with generateText
|
|
152
|
+
// In v6, stopWhen with stepCountIs controls the multi-step behavior
|
|
153
|
+
const hasTools = Object.keys(this.tools).length > 0;
|
|
154
|
+
const result = await generateText({
|
|
155
|
+
model: this.model,
|
|
156
|
+
system: this.systemPrompt,
|
|
157
|
+
messages: [...history, currentMessage],
|
|
158
|
+
tools: hasTools ? this.tools : undefined,
|
|
159
|
+
stopWhen: hasTools ? stepCountIs(this.maxSteps) : undefined,
|
|
160
|
+
temperature: this.temperature,
|
|
161
|
+
maxOutputTokens: this.maxOutputTokens,
|
|
162
|
+
});
|
|
163
|
+
// 4. Save Updated History
|
|
164
|
+
// result.response.messages contains all new messages (responses, tool calls, tool results)
|
|
165
|
+
if (this.memory && this.sessionId) {
|
|
166
|
+
const updatedHistory = [...history, currentMessage, ...result.response.messages];
|
|
167
|
+
await this.memory.add(this.sessionId, updatedHistory);
|
|
168
|
+
}
|
|
169
|
+
// 5. Format and return result
|
|
170
|
+
return {
|
|
171
|
+
text: result.text,
|
|
172
|
+
steps: this.formatStepResult(result.steps),
|
|
173
|
+
usage: {
|
|
174
|
+
inputTokens: result.usage.inputTokens,
|
|
175
|
+
outputTokens: result.usage.outputTokens,
|
|
176
|
+
totalTokens: result.usage.totalTokens,
|
|
177
|
+
},
|
|
178
|
+
totalUsage: result.usage,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Runs the agent without saving to memory (stateless)
|
|
183
|
+
*/
|
|
184
|
+
async runStateless(userPrompt, imageUrl) {
|
|
185
|
+
const currentMessage = {
|
|
186
|
+
role: 'user',
|
|
187
|
+
content: imageUrl
|
|
188
|
+
? [
|
|
189
|
+
{ type: 'text', text: userPrompt },
|
|
190
|
+
{ type: 'image', image: imageUrl },
|
|
191
|
+
]
|
|
192
|
+
: userPrompt,
|
|
193
|
+
};
|
|
194
|
+
const hasTools = Object.keys(this.tools).length > 0;
|
|
195
|
+
const result = await generateText({
|
|
196
|
+
model: this.model,
|
|
197
|
+
system: this.systemPrompt,
|
|
198
|
+
messages: [currentMessage],
|
|
199
|
+
tools: hasTools ? this.tools : undefined,
|
|
200
|
+
stopWhen: hasTools ? stepCountIs(this.maxSteps) : undefined,
|
|
201
|
+
temperature: this.temperature,
|
|
202
|
+
maxOutputTokens: this.maxOutputTokens,
|
|
203
|
+
});
|
|
204
|
+
return {
|
|
205
|
+
text: result.text,
|
|
206
|
+
steps: this.formatStepResult(result.steps),
|
|
207
|
+
usage: {
|
|
208
|
+
inputTokens: result.usage.inputTokens,
|
|
209
|
+
outputTokens: result.usage.outputTokens,
|
|
210
|
+
totalTokens: result.usage.totalTokens,
|
|
211
|
+
},
|
|
212
|
+
totalUsage: result.usage,
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Runs the agent in Streaming mode
|
|
217
|
+
* Automatically saves history on finish
|
|
218
|
+
*/
|
|
219
|
+
async stream(userPrompt, imageUrl) {
|
|
220
|
+
// 1. Load History
|
|
221
|
+
let history = [];
|
|
222
|
+
if (this.memory && this.sessionId) {
|
|
223
|
+
history = await this.memory.get(this.sessionId);
|
|
224
|
+
}
|
|
225
|
+
// 2. Prepare Current Message
|
|
226
|
+
const currentMessage = {
|
|
227
|
+
role: 'user',
|
|
228
|
+
content: imageUrl
|
|
229
|
+
? [
|
|
230
|
+
{ type: 'text', text: userPrompt },
|
|
231
|
+
{ type: 'image', image: imageUrl },
|
|
232
|
+
]
|
|
233
|
+
: userPrompt,
|
|
234
|
+
};
|
|
235
|
+
const hasTools = Object.keys(this.tools).length > 0;
|
|
236
|
+
// 3. Start Stream
|
|
237
|
+
const result = streamText({
|
|
238
|
+
model: this.model,
|
|
239
|
+
system: this.systemPrompt,
|
|
240
|
+
messages: [...history, currentMessage],
|
|
241
|
+
tools: hasTools ? this.tools : undefined,
|
|
242
|
+
stopWhen: hasTools ? stepCountIs(this.maxSteps) : undefined,
|
|
243
|
+
temperature: this.temperature,
|
|
244
|
+
maxOutputTokens: this.maxOutputTokens,
|
|
245
|
+
// Callback for persistence
|
|
246
|
+
onFinish: async ({ response }) => {
|
|
247
|
+
if (this.memory && this.sessionId) {
|
|
248
|
+
// response.messages includes the full roundtrip (tool calls, results, final response)
|
|
249
|
+
const updatedHistory = [...history, currentMessage, ...response.messages];
|
|
250
|
+
await this.memory.add(this.sessionId, updatedHistory);
|
|
251
|
+
}
|
|
252
|
+
},
|
|
253
|
+
});
|
|
254
|
+
return result;
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Stateless version of Streaming (no persistence)
|
|
258
|
+
*/
|
|
259
|
+
async streamStateless(userPrompt, imageUrl) {
|
|
260
|
+
const currentMessage = {
|
|
261
|
+
role: 'user',
|
|
262
|
+
content: imageUrl
|
|
263
|
+
? [
|
|
264
|
+
{ type: 'text', text: userPrompt },
|
|
265
|
+
{ type: 'image', image: imageUrl },
|
|
266
|
+
]
|
|
267
|
+
: userPrompt,
|
|
268
|
+
};
|
|
269
|
+
const hasTools = Object.keys(this.tools).length > 0;
|
|
270
|
+
return streamText({
|
|
271
|
+
model: this.model,
|
|
272
|
+
system: this.systemPrompt,
|
|
273
|
+
messages: [currentMessage],
|
|
274
|
+
tools: hasTools ? this.tools : undefined,
|
|
275
|
+
stopWhen: hasTools ? stepCountIs(this.maxSteps) : undefined,
|
|
276
|
+
temperature: this.temperature,
|
|
277
|
+
maxOutputTokens: this.maxOutputTokens,
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
//# sourceMappingURL=AgentBuilder.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"AgentBuilder.js","sourceRoot":"","sources":["../../src/core/AgentBuilder.ts"],"names":[],"mappings":"AAAA,2BAA2B;AAC3B,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,WAAW,EAAkG,MAAM,IAAI,CAAC;AAE3J,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAgBxC;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,OAAO,YAAY;IACb,KAAK,GAAkB,MAAM,CAAC,wBAAwB,CAAC,CAAC;IACxD,YAAY,GAAG,mCAAmC,CAAC;IACnD,KAAK,GAAY,EAAE,CAAC;IACpB,MAAM,CAAkB;IACxB,SAAS,CAAU;IACnB,QAAQ,GAAG,CAAC,CAAC,CAAC,mDAAmD;IACjE,WAAW,GAAG,GAAG,CAAC;IAClB,eAAe,CAAU;IAEjC,2CAA2C;IAE3C;;OAEG;IACH,SAAS,CAAC,OAAoB;QAC1B,IAAI,CAAC,KAAK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,SAAS;YACrF,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,eAAe,EAAE,IAAI,CAAC,eAAe;SACxC,CAAC,CAAC;IACP,CAAC;CACJ"}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { ModelMessage, LanguageModelUsage } from 'ai';
|
|
2
|
+
/**
|
|
3
|
+
* Interface for memory adapters (Port)
|
|
4
|
+
* Allows the agent to persist conversation history
|
|
5
|
+
*/
|
|
6
|
+
export interface IMemoryAdapter {
|
|
7
|
+
/**
|
|
8
|
+
* Retrieves conversation history for a session
|
|
9
|
+
*/
|
|
10
|
+
get(sessionId: string): Promise<ModelMessage[]>;
|
|
11
|
+
/**
|
|
12
|
+
* Adds/updates messages in the conversation history
|
|
13
|
+
*/
|
|
14
|
+
add(sessionId: string, messages: ModelMessage[]): Promise<void>;
|
|
15
|
+
/**
|
|
16
|
+
* Clears all conversation history for a session
|
|
17
|
+
*/
|
|
18
|
+
clear(sessionId: string): Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Tool call information
|
|
22
|
+
*/
|
|
23
|
+
export interface ToolCallInfo {
|
|
24
|
+
toolName: string;
|
|
25
|
+
input: unknown;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Tool result information
|
|
29
|
+
*/
|
|
30
|
+
export interface ToolResultInfo {
|
|
31
|
+
toolName: string;
|
|
32
|
+
output: unknown;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Step information for debugging
|
|
36
|
+
*/
|
|
37
|
+
export interface StepInfo {
|
|
38
|
+
toolCalls: ToolCallInfo[];
|
|
39
|
+
toolResults: ToolResultInfo[];
|
|
40
|
+
text: string;
|
|
41
|
+
finishReason: string;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Result returned from agent execution
|
|
45
|
+
*/
|
|
46
|
+
export interface AgentResult {
|
|
47
|
+
/** The final text response from the agent */
|
|
48
|
+
text: string;
|
|
49
|
+
/** Details about each step taken (useful for debugging tool usage) */
|
|
50
|
+
steps: StepInfo[];
|
|
51
|
+
/** Token usage statistics */
|
|
52
|
+
usage: {
|
|
53
|
+
inputTokens: number | undefined;
|
|
54
|
+
outputTokens: number | undefined;
|
|
55
|
+
totalTokens: number | undefined;
|
|
56
|
+
};
|
|
57
|
+
/** Total usage across all steps */
|
|
58
|
+
totalUsage: LanguageModelUsage;
|
|
59
|
+
}
|
|
60
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/core/types.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,IAAI,CAAC;AAE3D;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC3B;;OAEG;IACH,GAAG,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC,CAAC;IAEhD;;OAEG;IACH,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEhE;;OAEG;IACH,KAAK,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC3C;AAED;;GAEG;AACH,MAAM,WAAW,YAAY;IACzB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,OAAO,CAAC;CAClB;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,OAAO,CAAC;CACnB;AAED;;GAEG;AACH,MAAM,WAAW,QAAQ;IACrB,SAAS,EAAE,YAAY,EAAE,CAAC;IAC1B,WAAW,EAAE,cAAc,EAAE,CAAC;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,EAAE,MAAM,CAAC;CACxB;AAED;;GAEG;AACH,MAAM,WAAW,WAAW;IACxB,6CAA6C;IAC7C,IAAI,EAAE,MAAM,CAAC;IACb,sEAAsE;IACtE,KAAK,EAAE,QAAQ,EAAE,CAAC;IAClB,6BAA6B;IAC7B,KAAK,EAAE;QACH,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;QAChC,YAAY,EAAE,MAAM,GAAG,SAAS,CAAC;QACjC,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;KACnC,CAAC;IACF,mCAAmC;IACnC,UAAU,EAAE,kBAAkB,CAAC;CAClC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/core/types.ts"],"names":[],"mappings":""}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,eAAe,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// src/index.ts - Example usage of the AI Agent Library
|
|
2
|
+
import 'dotenv/config';
|
|
3
|
+
import { tool } from 'ai';
|
|
4
|
+
import { z } from 'zod/v4';
|
|
5
|
+
import { AgentBuilder } from './core/AgentBuilder.js';
|
|
6
|
+
import { InMemoryAdapter } from './infrastructure/InMemory.js';
|
|
7
|
+
import { CommonTools } from './tools/common.js';
|
|
8
|
+
async function main() {
|
|
9
|
+
const userId = 'usuario-dev-01';
|
|
10
|
+
// Choose your memory adapter:
|
|
11
|
+
// Option 1: Redis (requires Redis running)
|
|
12
|
+
// const memory = new RedisMemory();
|
|
13
|
+
// Option 2: In-Memory (for development, no external deps)
|
|
14
|
+
const memory = new InMemoryAdapter();
|
|
15
|
+
// Build the agent with fluent interface
|
|
16
|
+
const agent = new AgentBuilder()
|
|
17
|
+
.useModel('gemini-3-flash-preview')
|
|
18
|
+
.setSystem('Eres un asistente financiero sarcástico pero muy útil.')
|
|
19
|
+
.withMemory(memory, userId)
|
|
20
|
+
.setTemperature(0.7)
|
|
21
|
+
// 1. Inject pre-built common tools
|
|
22
|
+
.addTools({
|
|
23
|
+
hora: CommonTools.time,
|
|
24
|
+
web: CommonTools.webSearchMock,
|
|
25
|
+
calcular: CommonTools.calculator,
|
|
26
|
+
})
|
|
27
|
+
// 2. Inject an ad-hoc project-specific tool
|
|
28
|
+
.addTools({
|
|
29
|
+
comprarCripto: tool({
|
|
30
|
+
description: 'Compra una criptomoneda específica',
|
|
31
|
+
inputSchema: z.object({
|
|
32
|
+
moneda: z.string().describe('El símbolo de la criptomoneda (BTC, ETH, etc.)'),
|
|
33
|
+
cantidad: z.number().describe('La cantidad a comprar'),
|
|
34
|
+
}),
|
|
35
|
+
execute: async ({ moneda, cantidad }) => {
|
|
36
|
+
// Simulated order - replace with actual exchange API
|
|
37
|
+
const orderId = Math.random().toString(36).substring(7);
|
|
38
|
+
return JSON.stringify({
|
|
39
|
+
success: true,
|
|
40
|
+
orderId,
|
|
41
|
+
message: `Orden de compra creada: ${cantidad} ${moneda.toUpperCase()}`,
|
|
42
|
+
estimatedPrice: `$${(Math.random() * 50000 + 20000).toFixed(2)} USD`,
|
|
43
|
+
});
|
|
44
|
+
},
|
|
45
|
+
}),
|
|
46
|
+
});
|
|
47
|
+
console.log('--- 🤖 Inicio del Chat ---\n');
|
|
48
|
+
// Prompt 1: Requires web search and time
|
|
49
|
+
console.log('👤 Usuario: Hola, ¿qué hora es y busca en internet a cuánto está el Bitcoin hoy?');
|
|
50
|
+
const resp1 = await agent.run('Hola, ¿qué hora es y busca en internet a cuánto está el Bitcoin hoy?');
|
|
51
|
+
console.log('🤖 IA:', resp1.text);
|
|
52
|
+
console.log('📊 Tokens usados:', resp1.usage.totalTokens);
|
|
53
|
+
console.log('🔧 Tools usadas:', resp1.steps.flatMap((s) => s.toolCalls.map((t) => t.toolName)).join(', ') || 'ninguna');
|
|
54
|
+
console.log();
|
|
55
|
+
// Prompt 2: Context + new tool (Buy crypto)
|
|
56
|
+
// Thanks to memory, the agent knows we were talking about Bitcoin
|
|
57
|
+
console.log('👤 Usuario: Ok, compra 5 unidades de esa moneda entonces.');
|
|
58
|
+
const resp2 = await agent.run('Ok, compra 5 unidades de esa moneda entonces.');
|
|
59
|
+
console.log('🤖 IA:', resp2.text);
|
|
60
|
+
console.log('📊 Tokens usados:', resp2.usage.totalTokens);
|
|
61
|
+
console.log('🔧 Tools usadas:', resp2.steps.flatMap((s) => s.toolCalls.map((t) => t.toolName)).join(', ') || 'ninguna');
|
|
62
|
+
console.log();
|
|
63
|
+
// Prompt 3: Using calculator
|
|
64
|
+
console.log('👤 Usuario: Si compré a $45000, ¿cuánto gasto en total?');
|
|
65
|
+
const resp3 = await agent.run('Si compré a $45000, ¿cuánto gasto en total por las 5 unidades?');
|
|
66
|
+
console.log('🤖 IA:', resp3.text);
|
|
67
|
+
console.log('📊 Tokens usados:', resp3.usage.totalTokens);
|
|
68
|
+
console.log('🔧 Tools usadas:', resp3.steps.flatMap((s) => s.toolCalls.map((t) => t.toolName)).join(', ') || 'ninguna');
|
|
69
|
+
console.log('\n--- ✅ Chat Finalizado ---');
|
|
70
|
+
process.exit(0);
|
|
71
|
+
}
|
|
72
|
+
main().catch((err) => {
|
|
73
|
+
console.error('❌ Error:', err);
|
|
74
|
+
process.exit(1);
|
|
75
|
+
});
|
|
76
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,uDAAuD;AACvD,OAAO,eAAe,CAAC;AACvB,OAAO,EAAE,IAAI,EAAE,MAAM,IAAI,CAAC;AAC1B,OAAO,EAAE,CAAC,EAAE,MAAM,QAAQ,CAAC;AAC3B,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAEtD,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,KAAK,U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AC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,SAAS,CAAC,CAAC;IACxH,OAAO,CAAC,GAAG,EAAE,CAAC;IAEd,6BAA6B;IAC7B,OAAO,CAAC,GAAG,CAAC,yDAAyD,CAAC,CAAC;IACvE,MAAM,KAAK,GAAG,MAAM,KAAK,CAAC,GAAG,CACzB,gEAAgE,CACnE,CAAC;IACF,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;IAClC,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IAC1D,OAAO,CAAC,GAAG,CAAC,kBAAkB,EAAE,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,SAAS,CAAC,CAAC;IAExH,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAC;IAC3C,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC;IAC/B,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { ModelMessage } from 'ai';
|
|
2
|
+
import type { IMemoryAdapter } from '../core/types.js';
|
|
3
|
+
/**
|
|
4
|
+
* In-memory adapter for development/testing (no external dependencies)
|
|
5
|
+
*/
|
|
6
|
+
export declare class InMemoryAdapter implements IMemoryAdapter {
|
|
7
|
+
private store;
|
|
8
|
+
private maxMessages;
|
|
9
|
+
constructor(options?: {
|
|
10
|
+
maxMessages?: number;
|
|
11
|
+
});
|
|
12
|
+
get(sessionId: string): Promise<ModelMessage[]>;
|
|
13
|
+
add(sessionId: string, messages: ModelMessage[]): Promise<void>;
|
|
14
|
+
clear(sessionId: string): Promise<void>;
|
|
15
|
+
/**
|
|
16
|
+
* Clears all stored sessions
|
|
17
|
+
*/
|
|
18
|
+
clearAll(): void;
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=InMemory.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"InMemory.d.ts","sourceRoot":"","sources":["../../src/infrastructure/InMemory.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AACvC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAEvD;;GAEG;AACH,qBAAa,eAAgB,YAAW,cAAc;IAClD,OAAO,CAAC,KAAK,CAAqC;IAClD,OAAO,CAAC,WAAW,CAAS;gBAEhB,OAAO,CAAC,EAAE;QAAE,WAAW,CAAC,EAAE,MAAM,CAAA;KAAE;IAIxC,GAAG,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC;IAI/C,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAI/D,KAAK,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAI7C;;OAEG;IACH,QAAQ,IAAI,IAAI;CAGnB"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-memory adapter for development/testing (no external dependencies)
|
|
3
|
+
*/
|
|
4
|
+
export class InMemoryAdapter {
|
|
5
|
+
store = new Map();
|
|
6
|
+
maxMessages;
|
|
7
|
+
constructor(options) {
|
|
8
|
+
this.maxMessages = options?.maxMessages || 30;
|
|
9
|
+
}
|
|
10
|
+
async get(sessionId) {
|
|
11
|
+
return this.store.get(sessionId) || [];
|
|
12
|
+
}
|
|
13
|
+
async add(sessionId, messages) {
|
|
14
|
+
this.store.set(sessionId, messages.slice(-this.maxMessages));
|
|
15
|
+
}
|
|
16
|
+
async clear(sessionId) {
|
|
17
|
+
this.store.delete(sessionId);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Clears all stored sessions
|
|
21
|
+
*/
|
|
22
|
+
clearAll() {
|
|
23
|
+
this.store.clear();
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
//# sourceMappingURL=InMemory.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"InMemory.js","sourceRoot":"","sources":["../../src/infrastructure/InMemory.ts"],"names":[],"mappings":"AAIA;;GAEG;AACH,MAAM,OAAO,eAAe;IAChB,KAAK,GAAG,IAAI,GAAG,EAA0B,CAAC;IAC1C,WAAW,CAAS;IAE5B,YAAY,OAAkC;QAC1C,IAAI,CAAC,WAAW,GAAG,OAAO,EAAE,WAAW,IAAI,EAAE,CAAC;IAClD,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,SAAiB;QACvB,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC;IAC3C,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,SAAiB,EAAE,QAAwB;QACjD,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,SAAS,EAAE,QAAQ,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC;IACjE,CAAC;IAED,KAAK,CAAC,KAAK,CAAC,SAAiB;QACzB,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IACjC,CAAC;IAED;;OAEG;IACH,QAAQ;QACJ,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;IACvB,CAAC;CACJ"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { ModelMessage } from 'ai';
|
|
2
|
+
import type { IMemoryAdapter } from '../core/types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Redis-based memory adapter for conversation persistence
|
|
5
|
+
*/
|
|
6
|
+
export declare class RedisMemory implements IMemoryAdapter {
|
|
7
|
+
private client;
|
|
8
|
+
private keyPrefix;
|
|
9
|
+
private maxMessages;
|
|
10
|
+
private ttlSeconds;
|
|
11
|
+
constructor(options?: {
|
|
12
|
+
connectionString?: string;
|
|
13
|
+
keyPrefix?: string;
|
|
14
|
+
maxMessages?: number;
|
|
15
|
+
ttlSeconds?: number;
|
|
16
|
+
});
|
|
17
|
+
private getKey;
|
|
18
|
+
get(sessionId: string): Promise<ModelMessage[]>;
|
|
19
|
+
add(sessionId: string, newMessages: ModelMessage[]): Promise<void>;
|
|
20
|
+
clear(sessionId: string): Promise<void>;
|
|
21
|
+
/**
|
|
22
|
+
* Gracefully close the Redis connection
|
|
23
|
+
*/
|
|
24
|
+
disconnect(): Promise<void>;
|
|
25
|
+
}
|
|
26
|
+
//# sourceMappingURL=RedisMemory.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RedisMemory.d.ts","sourceRoot":"","sources":["../../src/infrastructure/RedisMemory.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AACvC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAEvD;;GAEG;AACH,qBAAa,WAAY,YAAW,cAAc;IAC9C,OAAO,CAAC,MAAM,CAAQ;IACtB,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,UAAU,CAAS;gBAEf,OAAO,CAAC,EAAE;QAClB,gBAAgB,CAAC,EAAE,MAAM,CAAC;QAC1B,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,UAAU,CAAC,EAAE,MAAM,CAAC;KACvB;IAOD,OAAO,CAAC,MAAM;IAIR,GAAG,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC;IAK/C,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,WAAW,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAMlE,KAAK,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAI7C;;OAEG;IACG,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;CAGpC"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// src/infrastructure/RedisMemory.ts
|
|
2
|
+
import { Redis } from 'ioredis';
|
|
3
|
+
/**
|
|
4
|
+
* Redis-based memory adapter for conversation persistence
|
|
5
|
+
*/
|
|
6
|
+
export class RedisMemory {
|
|
7
|
+
client;
|
|
8
|
+
keyPrefix;
|
|
9
|
+
maxMessages;
|
|
10
|
+
ttlSeconds;
|
|
11
|
+
constructor(options) {
|
|
12
|
+
this.client = new Redis(options?.connectionString || 'redis://localhost:6379');
|
|
13
|
+
this.keyPrefix = options?.keyPrefix || 'agent';
|
|
14
|
+
this.maxMessages = options?.maxMessages || 30;
|
|
15
|
+
this.ttlSeconds = options?.ttlSeconds || 86400; // 24 hours default
|
|
16
|
+
}
|
|
17
|
+
getKey(sessionId) {
|
|
18
|
+
return `${this.keyPrefix}:${sessionId}`;
|
|
19
|
+
}
|
|
20
|
+
async get(sessionId) {
|
|
21
|
+
const data = await this.client.get(this.getKey(sessionId));
|
|
22
|
+
return data ? JSON.parse(data) : [];
|
|
23
|
+
}
|
|
24
|
+
async add(sessionId, newMessages) {
|
|
25
|
+
// Keep only the last N messages (sliding window for context management)
|
|
26
|
+
const serialized = JSON.stringify(newMessages.slice(-this.maxMessages));
|
|
27
|
+
await this.client.set(this.getKey(sessionId), serialized, 'EX', this.ttlSeconds);
|
|
28
|
+
}
|
|
29
|
+
async clear(sessionId) {
|
|
30
|
+
await this.client.del(this.getKey(sessionId));
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Gracefully close the Redis connection
|
|
34
|
+
*/
|
|
35
|
+
async disconnect() {
|
|
36
|
+
await this.client.quit();
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=RedisMemory.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RedisMemory.js","sourceRoot":"","sources":["../../src/infrastructure/RedisMemory.ts"],"names":[],"mappings":"AAAA,oCAAoC;AACpC,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAIhC;;GAEG;AACH,MAAM,OAAO,WAAW;IACZ,MAAM,CAAQ;IACd,SAAS,CAAS;IAClB,WAAW,CAAS;IACpB,UAAU,CAAS;IAE3B,YAAY,OAKX;QACG,IAAI,CAAC,MAAM,GAAG,IAAI,KAAK,CAAC,OAAO,EAAE,gBAAgB,IAAI,wBAAwB,CAAC,CAAC;QAC/E,IAAI,CAAC,SAAS,GAAG,OAAO,EAAE,SAAS,IAAI,OAAO,CAAC;QAC/C,IAAI,CAAC,WAAW,GAAG,OAAO,EAAE,WAAW,IAAI,EAAE,CAAC;QAC9C,IAAI,CAAC,UAAU,GAAG,OAAO,EAAE,UAAU,IAAI,KAAK,CAAC,CAAC,mBAAmB;IACvE,CAAC;IAEO,MAAM,CAAC,SAAiB;QAC5B,OAAO,GAAG,IAAI,CAAC,SAAS,IAAI,SAAS,EAAE,CAAC;IAC5C,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,SAAiB;QACvB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC;QAC3D,OAAO,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IACxC,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,SAAiB,EAAE,WAA2B;QACpD,wEAAwE;QACxE,MAAM,UAAU,GAAG,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC;QACxE,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;IACrF,CAAC;IAED,KAAK,CAAC,KAAK,CAAC,SAAiB;QACzB,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC;IAClD,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,UAAU;QACZ,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;IAC7B,CAAC;CACJ"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Collection of pre-built common tools
|
|
3
|
+
*/
|
|
4
|
+
export declare const CommonTools: {
|
|
5
|
+
/**
|
|
6
|
+
* Tool 1: Current date and time
|
|
7
|
+
*/
|
|
8
|
+
time: import("ai").Tool<Record<string, never>, string>;
|
|
9
|
+
calculator: import("ai").Tool<{
|
|
10
|
+
expression: string;
|
|
11
|
+
}, string>;
|
|
12
|
+
/**
|
|
13
|
+
* Tool 3: Web search mock (replace with actual API in production)
|
|
14
|
+
*/
|
|
15
|
+
webSearchMock: import("ai").Tool<{
|
|
16
|
+
query: string;
|
|
17
|
+
}, string>;
|
|
18
|
+
/**
|
|
19
|
+
* Tool 4: Random number generator
|
|
20
|
+
*/
|
|
21
|
+
randomNumber: import("ai").Tool<{
|
|
22
|
+
min: number;
|
|
23
|
+
max: number;
|
|
24
|
+
}, string>;
|
|
25
|
+
/**
|
|
26
|
+
* Tool 5: Text utilities
|
|
27
|
+
*/
|
|
28
|
+
textUtils: import("ai").Tool<{
|
|
29
|
+
text: string;
|
|
30
|
+
operation: "reverse" | "wordCount" | "charCount" | "uppercase" | "lowercase";
|
|
31
|
+
}, string>;
|
|
32
|
+
};
|
|
33
|
+
//# sourceMappingURL=common.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../../src/tools/common.ts"],"names":[],"mappings":"AAKA;;GAEG;AACH,eAAO,MAAM,WAAW;IACpB;;OAEG;;;;;IA+BH;;OAEG;;;;IAqBH;;OAEG;;;;;IAaH;;OAEG;;;;;CAyBN,CAAC"}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// src/tools/common.ts
|
|
2
|
+
import { tool } from 'ai';
|
|
3
|
+
import { z } from 'zod/v4';
|
|
4
|
+
import { evaluate } from 'mathjs';
|
|
5
|
+
/**
|
|
6
|
+
* Collection of pre-built common tools
|
|
7
|
+
*/
|
|
8
|
+
export const CommonTools = {
|
|
9
|
+
/**
|
|
10
|
+
* Tool 1: Current date and time
|
|
11
|
+
*/
|
|
12
|
+
time: tool({
|
|
13
|
+
description: 'Obtiene la fecha y hora actual (útil para contextos temporales)',
|
|
14
|
+
inputSchema: z.object({}),
|
|
15
|
+
execute: async () => {
|
|
16
|
+
const now = new Date();
|
|
17
|
+
return JSON.stringify({
|
|
18
|
+
iso: now.toISOString(),
|
|
19
|
+
local: now.toLocaleString(),
|
|
20
|
+
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
21
|
+
});
|
|
22
|
+
},
|
|
23
|
+
}),
|
|
24
|
+
// Tool 2: Safe calculator using mathjs
|
|
25
|
+
calculator: tool({
|
|
26
|
+
description: 'Realiza cálculos matemáticos seguros. Soporta +, -, *, /, potencias y funciones básicas.',
|
|
27
|
+
inputSchema: z.object({
|
|
28
|
+
expression: z.string().describe('La expresión matemática a evaluar, ej: "2 + 2", "sqrt(16)", o "(10 * 5) / 2"'),
|
|
29
|
+
}),
|
|
30
|
+
execute: async ({ expression }) => {
|
|
31
|
+
try {
|
|
32
|
+
// evaluate from mathjs is safer and more powerful
|
|
33
|
+
const result = evaluate(expression);
|
|
34
|
+
return JSON.stringify({ result: result.toString(), expression });
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return JSON.stringify({ error: 'Error en el cálculo: Expresión inválida o no soportada', result: null });
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
}),
|
|
41
|
+
/**
|
|
42
|
+
* Tool 3: Web search mock (replace with actual API in production)
|
|
43
|
+
*/
|
|
44
|
+
webSearchMock: tool({
|
|
45
|
+
description: 'Busca información actual en internet sobre un tópico',
|
|
46
|
+
inputSchema: z.object({
|
|
47
|
+
query: z.string().describe('El término o frase a buscar'),
|
|
48
|
+
}),
|
|
49
|
+
execute: async ({ query }) => {
|
|
50
|
+
console.log(`[🔍 Buscando en la web: ${query}]`);
|
|
51
|
+
// Mock response - replace with actual search API (SerpAPI, Tavily, etc.)
|
|
52
|
+
return JSON.stringify({
|
|
53
|
+
query,
|
|
54
|
+
results: [
|
|
55
|
+
{ title: 'Resultado simulado 1', snippet: `Información sobre: ${query}` },
|
|
56
|
+
{ title: 'Resultado simulado 2', snippet: 'El clima está soleado en Madrid.' },
|
|
57
|
+
{ title: 'Resultado simulado 3', snippet: 'El dólar está a 1.05 EUR.' },
|
|
58
|
+
],
|
|
59
|
+
note: 'Esto es una respuesta simulada. Implementa una API real en producción.',
|
|
60
|
+
});
|
|
61
|
+
},
|
|
62
|
+
}),
|
|
63
|
+
/**
|
|
64
|
+
* Tool 4: Random number generator
|
|
65
|
+
*/
|
|
66
|
+
randomNumber: tool({
|
|
67
|
+
description: 'Genera un número aleatorio entre un mínimo y máximo',
|
|
68
|
+
inputSchema: z.object({
|
|
69
|
+
min: z.number().describe('Valor mínimo (incluido)'),
|
|
70
|
+
max: z.number().describe('Valor máximo (incluido)'),
|
|
71
|
+
}),
|
|
72
|
+
execute: async ({ min, max }) => {
|
|
73
|
+
const result = Math.floor(Math.random() * (max - min + 1)) + min;
|
|
74
|
+
return JSON.stringify({ min, max, result });
|
|
75
|
+
},
|
|
76
|
+
}),
|
|
77
|
+
/**
|
|
78
|
+
* Tool 5: Text utilities
|
|
79
|
+
*/
|
|
80
|
+
textUtils: tool({
|
|
81
|
+
description: 'Realiza operaciones de texto: contar palabras, caracteres, o transformar texto',
|
|
82
|
+
inputSchema: z.object({
|
|
83
|
+
text: z.string().describe('El texto a procesar'),
|
|
84
|
+
operation: z.enum(['wordCount', 'charCount', 'uppercase', 'lowercase', 'reverse'])
|
|
85
|
+
.describe('La operación a realizar'),
|
|
86
|
+
}),
|
|
87
|
+
execute: async ({ text, operation }) => {
|
|
88
|
+
switch (operation) {
|
|
89
|
+
case 'wordCount':
|
|
90
|
+
return JSON.stringify({ operation, result: text.split(/\s+/).filter((w) => w.length > 0).length });
|
|
91
|
+
case 'charCount':
|
|
92
|
+
return JSON.stringify({ operation, result: text.length });
|
|
93
|
+
case 'uppercase':
|
|
94
|
+
return JSON.stringify({ operation, result: text.toUpperCase() });
|
|
95
|
+
case 'lowercase':
|
|
96
|
+
return JSON.stringify({ operation, result: text.toLowerCase() });
|
|
97
|
+
case 'reverse':
|
|
98
|
+
return JSON.stringify({ operation, result: text.split('').reverse().join('') });
|
|
99
|
+
default:
|
|
100
|
+
return JSON.stringify({ operation, error: 'Operación no reconocida' });
|
|
101
|
+
}
|
|
102
|
+
},
|
|
103
|
+
}),
|
|
104
|
+
};
|
|
105
|
+
//# sourceMappingURL=common.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"common.js","sourceRoot":"","sources":["../../src/tools/common.ts"],"names":[],"mappings":"AAAA,sBAAsB;AACtB,OAAO,EAAE,IAAI,EAAE,MAAM,IAAI,CAAC;AAC1B,OAAO,EAAE,CAAC,EAAE,MAAM,QAAQ,CAAC;AAC3B,OAAO,EAAE,QAAQ,EAAE,MAAM,QAAQ,CA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,OAAO,IAAI,CAAC,SAAS,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,yBAAyB,EAAE,CAAC,CAAC;YAC/E,CAAC;QACL,CAAC;KACJ,CAAC;CACL,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@misgara/ai-agent",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Librería hexagonal para agentes de IA",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"dev": "tsx src/index.ts",
|
|
9
|
+
"build": "tsc",
|
|
10
|
+
"start": "node dist/index.js",
|
|
11
|
+
"typecheck": "tsc --noEmit",
|
|
12
|
+
"prepublishOnly": "npm run build"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist"
|
|
16
|
+
],
|
|
17
|
+
"keywords": [
|
|
18
|
+
"ai",
|
|
19
|
+
"agent",
|
|
20
|
+
"gemini",
|
|
21
|
+
"vercel-ai-sdk"
|
|
22
|
+
],
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"author": "misgara",
|
|
27
|
+
"license": "ISC",
|
|
28
|
+
"type": "module",
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@ai-sdk/google": "^3.0.6",
|
|
31
|
+
"@ai-sdk/openai": "^3.0.7",
|
|
32
|
+
"ai": "^6.0.27",
|
|
33
|
+
"dotenv": "^17.2.3",
|
|
34
|
+
"ioredis": "^5.9.1",
|
|
35
|
+
"mathjs": "^15.1.0",
|
|
36
|
+
"zod": "^4.3.5"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@types/ioredis": "^4.28.10",
|
|
40
|
+
"@types/node": "^25.0.6",
|
|
41
|
+
"tsx": "^4.21.0",
|
|
42
|
+
"typescript": "^5.9.3"
|
|
43
|
+
}
|
|
44
|
+
}
|