@atgs/tapeworm 0.0.1

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.
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class _{messages;manager;constructor(){this.messages=[],this.manager=new T}append(e){this.messages.push(e),this.messages=this.manager.compact(this.messages)}}class a{role;content;toolCalls;toolName;thinking;constructor(e,s,t,o,r){this.role=e,this.content=s,this.toolCalls=t,this.toolName=o,this.thinking=r}setRole(e){this.role=e}setContent(e){this.content=e}setToolCalls(e){this.toolCalls=e}static builder(){return new f}}class f{_role;_content;_toolCalls;_toolName;_thinking;role(e){return this._role=e,this}content(e){return this._content=e,this}toolCalls(e){return this._toolCalls=e,this}toolName(e){return this._toolName=e,this}thinking(e){return this._thinking=e,this}build(){return new a(this._role,this._content,this._toolCalls,this._toolName,this._thinking)}}class y{compact(e){throw new p("No implementation for conversation manager!")}configure(e){throw new p("No implementation for conversation manager!")}}class T extends y{compact(e){return e}configure(e){}}class p extends Error{constructor(e){super(e),this.name="ConversationManagerNotImplemented"}}class v{async invoke(e){throw new g("The invoke function for this model was not correctly implemented.")}tokenLimit(){throw new g("The tokenLimit function for this model was not correctly implemented.")}}class w{messages;tools;constructor(e,s){this.messages=e,this.tools=s}static builder(){return new u}}class u{_messages;_tools;messages(e){return this._messages=e,this}tools(e){return this._tools=e,this}build(){return this._tools==null&&(this._tools=[]),new w(this._messages,this._tools)}}class b{toolCalls;role;content;thinking;constructor(e,s,t,o){this.toolCalls=e,this.role=s,this.content=t,this.thinking=o}static builder(){return new m}}class m{_toolCalls;_role;_content;_thinking;toolCalls(e){return this._toolCalls=e,this}role(e){return this._role=e,this}content(e){return this._content=e,this}thinking(e){return this._thinking=e,this}build(){return new b(this._toolCalls,this._role,this._content,this._thinking)}}class g extends Error{constructor(e){super(e),this.name="ModelNotImplementedError"}}class B{name;system_prompt;tools;model;conversation;conversationManager;toolNameToIndexMap;async invoke(e){this.conversation==null&&(this.conversation=new _,this.conversationManager!=null&&(this.conversation.manager=this.conversationManager),this.conversation.append(a.builder().role("system").content(this.system_prompt).build())),this.conversation.append(a.builder().role("user").content(e).build());let s=!1;for(;!s;){let t=await this._runQuery();if(this.conversation.append(a.builder().role(t.role??"assistant").content(t.content??"").thinking(t.thinking??"").build()),console.log("Assistant thinking: "+t.thinking),console.log("Assistant reply: "+t.content),s=!0,t.toolCalls!=null&&t.toolCalls.length!=0){s=!1,t.toolCalls.sort((o,r)=>(o.sequence??0)<(r.sequence??0)?-1:1);for(let o in t.toolCalls)this._runTool(t.toolCalls[o])}}}async _runQuery(){return await this.model.invoke(new u().messages(this.conversation?.messages).tools(this.tools).build())}async _runTool(e){if(console.log("Calling tool: "+JSON.stringify(e)),this.generateToolNameToIndexMap(),!(e.name in this.toolNameToIndexMap)){this.conversation.append(a.builder().role("tool").toolName(e.name).content(JSON.stringify({error:"tool does not exist"})).build());return}let s=this.tools[this.toolNameToIndexMap[e.name]];try{let t=s.execute(e.parameters);this.conversation.append(a.builder().role("tool").toolName(e.name).content(JSON.stringify(t)).build())}catch(t){this.conversation.append(a.builder().role("tool").toolName(e.name).content(JSON.stringify(t)).build())}}generateToolNameToIndexMap(){if(this.toolNameToIndexMap==null){this.toolNameToIndexMap={};for(let e=0;e<this.tools.length;e++)this.toolNameToIndexMap[this.tools[e].getName()]=e}}}class c extends Error{constructor(e){super(e),this.name="ToolNotDefinedError"}}class I{name;description;tool_schema;constructor(){this.name=this.getName(),this.description=this.getDescription(),this.tool_schema=this.getToolSchema()}getName(){throw new c("Tool name not defined.")}getDescription(){throw new c("Tool description not defined.")}getToolSchema(){throw new c("Tool parameter schema not defined.")}execute(e){return null}}class d{sequence;name;parameters;type;constructor(e,s,t,o){this.sequence=e,this.name=s,this.parameters=t,this.type=o}static builder(){return new M}}class M{_sequence;_name;_parameters;_type;sequence(e){return this._sequence=e,this}name(e){return this._name=e,this}parameters(e){return this._parameters=e,this}type(e){return this._type=e,this}build(){return this._sequence==null&&(this._sequence=0),new d(this._sequence,this._name,this._parameters,this._type)}}class N{parameters;output;constructor(e,s){this.parameters=e,this.output=s}static builder(){return new C}}class C{_parameters;_output;addParameter(e){return this._parameters==null&&(this._parameters=[]),this._parameters.push(e),this}output(e){return this._output=e,this}build(){return this._parameters==null&&(this._parameters=[]),new N(this._parameters,this._output)}}class q{name;description;type;required;constructor(e,s,t,o){this.name=e,this.description=s,this.type=t,this.required=o,this.assertValidType()}assertValidType(){}static builder(){return new k}}class k{_name;_description;_type;_required;name(e){return this._name=e,this}description(e){return this._description=e,this}type(e){return this._type=e,this}required(e){return this._required=e,this}build(){return this._required==null&&(this._required=!1),new q(this._name,this._description,this._type,this._required)}}class j extends v{endpoint;model;options;constructor(e,s,t){super(),this.endpoint=e,this.model=s,this.options=t}async invoke(e){let s={model:this.model,messages:this._formatMessages(e),tools:this._formatTools(e),...this.options},t=await fetch(this.endpoint+"/api/chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!t.ok)throw new Error(`HTTP error! status: ${t.status}`);let o=await t.json(),r=[];if(o.message.tool_calls)for(let h in o.message.tool_calls){const i=o.message.tool_calls[h];let l="function",x=i[l]?.name,O=i[l]?.index,S=i[l]?.arguments;r.push(d.builder().name(x).type(l).parameters(S).sequence(O).build())}return new m().toolCalls(r).role(o.message.role).content(o.message.content).thinking(o.message.thinking).build()}_formatTools(e){let s=[],t=[];for(let o of e.tools){let r={};for(let i of o.getToolSchema().parameters)r[i.name]={},r[i.name].type=i.name,r[i.name].description=i.description,i.required&&t.push(i.name);let h={type:"function",function:{name:o.getName(),description:o.getDescription(),parameters:{type:"object",properties:r,required:t}}};s.push(h)}return s}_formatMessages(e){let s=[];for(let t of e.messages){if(t.role=="assistant"||t.role=="system"||t.role=="user"){s.push(t);continue}t.role=="tool"&&s.push({role:"tool",content:t.content,tool_name:t.toolName})}return s}}exports.Agent=B;exports.Conversation=_;exports.ConversationManager=y;exports.DefaultConversationManager=T;exports.Message=a;exports.MessageBuilder=f;exports.Model=v;exports.ModelRequest=w;exports.ModelRequestBuilder=u;exports.ModelResponse=b;exports.ModelResponseBuilder=m;exports.OllamaModel=j;exports.Parameter=q;exports.ParameterBuilder=k;exports.Tool=I;exports.ToolCall=d;exports.ToolCallBuilder=M;exports.ToolSchema=N;exports.ToolSchemaBuilder=C;
@@ -0,0 +1,524 @@
1
+ class w {
2
+ messages;
3
+ manager;
4
+ constructor() {
5
+ this.messages = [], this.manager = new T();
6
+ }
7
+ append(e) {
8
+ this.messages.push(e), this.messages = this.manager.compact(this.messages);
9
+ }
10
+ }
11
+ class a {
12
+ role;
13
+ content;
14
+ toolCalls;
15
+ toolName;
16
+ thinking;
17
+ constructor(e, s, t, o, i) {
18
+ this.role = e, this.content = s, this.toolCalls = t, this.toolName = o, this.thinking = i;
19
+ }
20
+ setRole(e) {
21
+ this.role = e;
22
+ }
23
+ setContent(e) {
24
+ this.content = e;
25
+ }
26
+ setToolCalls(e) {
27
+ this.toolCalls = e;
28
+ }
29
+ static builder() {
30
+ return new b();
31
+ }
32
+ }
33
+ class b {
34
+ _role;
35
+ _content;
36
+ _toolCalls;
37
+ _toolName;
38
+ _thinking;
39
+ role(e) {
40
+ return this._role = e, this;
41
+ }
42
+ content(e) {
43
+ return this._content = e, this;
44
+ }
45
+ toolCalls(e) {
46
+ return this._toolCalls = e, this;
47
+ }
48
+ toolName(e) {
49
+ return this._toolName = e, this;
50
+ }
51
+ thinking(e) {
52
+ return this._thinking = e, this;
53
+ }
54
+ build() {
55
+ return new a(this._role, this._content, this._toolCalls, this._toolName, this._thinking);
56
+ }
57
+ }
58
+ class v {
59
+ compact(e) {
60
+ throw new m("No implementation for conversation manager!");
61
+ }
62
+ configure(e) {
63
+ throw new m("No implementation for conversation manager!");
64
+ }
65
+ }
66
+ class T extends v {
67
+ compact(e) {
68
+ return e;
69
+ }
70
+ configure(e) {
71
+ }
72
+ }
73
+ class m extends Error {
74
+ constructor(e) {
75
+ super(e), this.name = "ConversationManagerNotImplemented";
76
+ }
77
+ }
78
+ class N {
79
+ /**
80
+ * Execute the model against the provided request.
81
+ * @param request Aggregated messages and tools to send to the model.
82
+ */
83
+ async invoke(e) {
84
+ throw new u("The invoke function for this model was not correctly implemented.");
85
+ }
86
+ /**
87
+ * Return the maximum token budget supported by this model.
88
+ */
89
+ tokenLimit() {
90
+ throw new u("The tokenLimit function for this model was not correctly implemented.");
91
+ }
92
+ }
93
+ class C {
94
+ messages;
95
+ tools;
96
+ /**
97
+ * Create a new model request envelope.
98
+ * @param messages Conversation history to send to the model.
99
+ * @param tools Tool definitions available for function calling.
100
+ */
101
+ constructor(e, s) {
102
+ this.messages = e, this.tools = s;
103
+ }
104
+ static builder() {
105
+ return new d();
106
+ }
107
+ }
108
+ class d {
109
+ _messages;
110
+ _tools;
111
+ /**
112
+ * Supply the conversation messages to include.
113
+ */
114
+ messages(e) {
115
+ return this._messages = e, this;
116
+ }
117
+ /**
118
+ * Supply the tool list for this request.
119
+ */
120
+ tools(e) {
121
+ return this._tools = e, this;
122
+ }
123
+ /**
124
+ * Build the ModelRequest, defaulting tools to an empty array.
125
+ */
126
+ build() {
127
+ return this._tools == null && (this._tools = []), new C(this._messages, this._tools);
128
+ }
129
+ }
130
+ class M {
131
+ toolCalls;
132
+ role;
133
+ content;
134
+ thinking;
135
+ /**
136
+ * Wrap a model response.
137
+ * @param toolCalls Optional tool calls returned by the model.
138
+ * @param role Role of the message (e.g., assistant, tool).
139
+ * @param content Text content returned by the model.
140
+ */
141
+ constructor(e, s, t, o) {
142
+ this.toolCalls = e, this.role = s, this.content = t, this.thinking = o;
143
+ }
144
+ static builder() {
145
+ return new p();
146
+ }
147
+ }
148
+ class p {
149
+ _toolCalls;
150
+ _role;
151
+ _content;
152
+ _thinking;
153
+ /**
154
+ * Attach tool calls to the response.
155
+ */
156
+ toolCalls(e) {
157
+ return this._toolCalls = e, this;
158
+ }
159
+ /**
160
+ * Set the role for the response message.
161
+ */
162
+ role(e) {
163
+ return this._role = e, this;
164
+ }
165
+ /**
166
+ * Set the textual content for the response message.
167
+ */
168
+ content(e) {
169
+ return this._content = e, this;
170
+ }
171
+ /**
172
+ * Set the thinking content for the response message.
173
+ */
174
+ thinking(e) {
175
+ return this._thinking = e, this;
176
+ }
177
+ /**
178
+ * Build the ModelResponse from the collected fields.
179
+ */
180
+ build() {
181
+ return new M(this._toolCalls, this._role, this._content, this._thinking);
182
+ }
183
+ }
184
+ class u extends Error {
185
+ constructor(e) {
186
+ super(e), this.name = "ModelNotImplementedError";
187
+ }
188
+ }
189
+ class S {
190
+ name;
191
+ system_prompt;
192
+ tools;
193
+ model;
194
+ conversation;
195
+ conversationManager;
196
+ toolNameToIndexMap;
197
+ async invoke(e) {
198
+ this.conversation == null && (this.conversation = new w(), this.conversationManager != null && (this.conversation.manager = this.conversationManager), this.conversation.append(
199
+ a.builder().role("system").content(this.system_prompt).build()
200
+ )), this.conversation.append(
201
+ a.builder().role("user").content(e).build()
202
+ );
203
+ let s = !1;
204
+ for (; !s; ) {
205
+ let t = await this._runQuery();
206
+ if (this.conversation.append(
207
+ a.builder().role(t.role ?? "assistant").content(t.content ?? "").thinking(t.thinking ?? "").build()
208
+ ), console.log("Assistant thinking: " + t.thinking), console.log("Assistant reply: " + t.content), s = !0, t.toolCalls != null && t.toolCalls.length != 0) {
209
+ s = !1, t.toolCalls.sort(
210
+ (o, i) => (o.sequence ?? 0) < (i.sequence ?? 0) ? -1 : 1
211
+ );
212
+ for (let o in t.toolCalls)
213
+ this._runTool(t.toolCalls[o]);
214
+ }
215
+ }
216
+ }
217
+ async _runQuery() {
218
+ return await this.model.invoke(
219
+ new d().messages(this.conversation?.messages).tools(this.tools).build()
220
+ );
221
+ }
222
+ async _runTool(e) {
223
+ if (console.log("Calling tool: " + JSON.stringify(e)), this.generateToolNameToIndexMap(), !(e.name in this.toolNameToIndexMap)) {
224
+ this.conversation.append(
225
+ a.builder().role("tool").toolName(e.name).content(JSON.stringify({ error: "tool does not exist" })).build()
226
+ );
227
+ return;
228
+ }
229
+ let s = this.tools[this.toolNameToIndexMap[e.name]];
230
+ try {
231
+ let t = s.execute(e.parameters);
232
+ this.conversation.append(
233
+ a.builder().role("tool").toolName(e.name).content(JSON.stringify(t)).build()
234
+ );
235
+ } catch (t) {
236
+ this.conversation.append(
237
+ a.builder().role("tool").toolName(e.name).content(JSON.stringify(t)).build()
238
+ );
239
+ }
240
+ }
241
+ generateToolNameToIndexMap() {
242
+ if (this.toolNameToIndexMap == null) {
243
+ this.toolNameToIndexMap = {};
244
+ for (let e = 0; e < this.tools.length; e++)
245
+ this.toolNameToIndexMap[this.tools[e].getName()] = e;
246
+ }
247
+ }
248
+ }
249
+ class c extends Error {
250
+ constructor(e) {
251
+ super(e), this.name = "ToolNotDefinedError";
252
+ }
253
+ }
254
+ class j {
255
+ name;
256
+ description;
257
+ tool_schema;
258
+ constructor() {
259
+ this.name = this.getName(), this.description = this.getDescription(), this.tool_schema = this.getToolSchema();
260
+ }
261
+ getName() {
262
+ throw new c("Tool name not defined.");
263
+ }
264
+ getDescription() {
265
+ throw new c("Tool description not defined.");
266
+ }
267
+ getToolSchema() {
268
+ throw new c("Tool parameter schema not defined.");
269
+ }
270
+ // @ts-ignore
271
+ execute(e) {
272
+ return null;
273
+ }
274
+ }
275
+ class _ {
276
+ sequence;
277
+ name;
278
+ parameters;
279
+ type;
280
+ constructor(e, s, t, o) {
281
+ this.sequence = e, this.name = s, this.parameters = t, this.type = o;
282
+ }
283
+ static builder() {
284
+ return new k();
285
+ }
286
+ }
287
+ class k {
288
+ _sequence;
289
+ _name;
290
+ _parameters;
291
+ _type;
292
+ sequence(e) {
293
+ return this._sequence = e, this;
294
+ }
295
+ name(e) {
296
+ return this._name = e, this;
297
+ }
298
+ parameters(e) {
299
+ return this._parameters = e, this;
300
+ }
301
+ type(e) {
302
+ return this._type = e, this;
303
+ }
304
+ build() {
305
+ return this._sequence == null && (this._sequence = 0), new _(this._sequence, this._name, this._parameters, this._type);
306
+ }
307
+ }
308
+ class q {
309
+ parameters;
310
+ output;
311
+ /**
312
+ * Create a new tool schema.
313
+ * @param parameters Ordered list of input parameters the tool accepts.
314
+ * @param output Human-readable description of the tool output.
315
+ */
316
+ constructor(e, s) {
317
+ this.parameters = e, this.output = s;
318
+ }
319
+ /**
320
+ * Return a tool schema builder, so you can properly construct tools instead of dealing with the constructor
321
+ * @returns a tool schema builder.
322
+ */
323
+ static builder() {
324
+ return new x();
325
+ }
326
+ }
327
+ class x {
328
+ _parameters;
329
+ _output;
330
+ /**
331
+ * Add a parameter definition to the schema.
332
+ * @param parameter Fully constructed parameter to append.
333
+ */
334
+ addParameter(e) {
335
+ return this._parameters == null && (this._parameters = []), this._parameters.push(e), this;
336
+ }
337
+ /**
338
+ * Describe the output of the tool.
339
+ * @param output Text description of what the tool returns.
340
+ */
341
+ output(e) {
342
+ return this._output = e, this;
343
+ }
344
+ /**
345
+ * Build the ToolSchema instance from the collected fields.
346
+ */
347
+ build() {
348
+ return this._parameters == null && (this._parameters = []), new q(this._parameters, this._output);
349
+ }
350
+ }
351
+ class O {
352
+ name;
353
+ description;
354
+ type;
355
+ required;
356
+ /**
357
+ * Create a new parameter definition.
358
+ * @param name Identifier for the parameter.
359
+ * @param description Explanation of how the parameter is used.
360
+ * @param type JSON-serializable type name (e.g., string, number).
361
+ * @param required Whether the parameter must be provided.
362
+ */
363
+ constructor(e, s, t, o) {
364
+ this.name = e, this.description = s, this.type = t, this.required = o, this.assertValidType();
365
+ }
366
+ /**
367
+ * Placeholder for validating supported parameter types.
368
+ */
369
+ assertValidType() {
370
+ }
371
+ static builder() {
372
+ return new I();
373
+ }
374
+ }
375
+ class I {
376
+ _name;
377
+ _description;
378
+ _type;
379
+ _required;
380
+ /**
381
+ * Set the parameter name.
382
+ */
383
+ name(e) {
384
+ return this._name = e, this;
385
+ }
386
+ /**
387
+ * Set the parameter description.
388
+ */
389
+ description(e) {
390
+ return this._description = e, this;
391
+ }
392
+ /**
393
+ * Set the parameter type.
394
+ */
395
+ type(e) {
396
+ return this._type = e, this;
397
+ }
398
+ /**
399
+ * Mark the parameter as required or optional.
400
+ */
401
+ required(e) {
402
+ return this._required = e, this;
403
+ }
404
+ /**
405
+ * Build a Parameter instance using the accumulated fields.
406
+ */
407
+ build() {
408
+ return this._required == null && (this._required = !1), new O(this._name, this._description, this._type, this._required);
409
+ }
410
+ }
411
+ class E extends N {
412
+ endpoint;
413
+ model;
414
+ options;
415
+ /**
416
+ * Create a model wrapper for an Ollama chat endpoint.
417
+ * @param endpoint Base URL of the Ollama server (e.g., http://localhost:11434).
418
+ * @param model Model name/tag to use for inference.
419
+ * @param options Additional Ollama options passed through to the API.
420
+ */
421
+ constructor(e, s, t) {
422
+ super(), this.endpoint = e, this.model = s, this.options = t;
423
+ }
424
+ /**
425
+ * Call the Ollama chat API with the provided conversation and tools.
426
+ * Formats the request, performs the HTTP POST, and translates the response into a ModelResponse.
427
+ */
428
+ async invoke(e) {
429
+ let s = {
430
+ model: this.model,
431
+ messages: this._formatMessages(e),
432
+ tools: this._formatTools(e),
433
+ ...this.options
434
+ }, t = await fetch(
435
+ this.endpoint + "/api/chat",
436
+ {
437
+ method: "POST",
438
+ headers: {
439
+ "Content-Type": "application/json"
440
+ },
441
+ body: JSON.stringify(s)
442
+ }
443
+ );
444
+ if (!t.ok)
445
+ throw new Error(`HTTP error! status: ${t.status}`);
446
+ let o = await t.json(), i = [];
447
+ if (o.message.tool_calls)
448
+ for (let h in o.message.tool_calls) {
449
+ const r = o.message.tool_calls[h];
450
+ let l = "function", g = r[l]?.name, f = r[l]?.index, y = r[l]?.arguments;
451
+ i.push(
452
+ _.builder().name(g).type(l).parameters(y).sequence(f).build()
453
+ );
454
+ }
455
+ return new p().toolCalls(i).role(o.message.role).content(o.message.content).thinking(o.message.thinking).build();
456
+ }
457
+ /**
458
+ * Convert internal tool definitions into the JSON schema format expected by Ollama.
459
+ */
460
+ _formatTools(e) {
461
+ let s = [], t = [];
462
+ for (let o of e.tools) {
463
+ let i = {};
464
+ for (let r of o.getToolSchema().parameters)
465
+ i[r.name] = {}, i[r.name].type = r.name, i[r.name].description = r.description, r.required && t.push(r.name);
466
+ let h = {
467
+ type: "function",
468
+ function: {
469
+ name: o.getName(),
470
+ description: o.getDescription(),
471
+ parameters: {
472
+ type: "object",
473
+ properties: i,
474
+ required: t
475
+ }
476
+ }
477
+ };
478
+ s.push(h);
479
+ }
480
+ return s;
481
+ }
482
+ /**
483
+ * Convert internal message objects into Ollama's chat message shape.
484
+ * Passes through assistant/system/user roles and maps tool role into the expected structure.
485
+ */
486
+ _formatMessages(e) {
487
+ let s = [];
488
+ for (let t of e.messages) {
489
+ if (t.role == "assistant" || t.role == "system" || t.role == "user") {
490
+ s.push(t);
491
+ continue;
492
+ }
493
+ t.role == "tool" && s.push(
494
+ {
495
+ role: "tool",
496
+ content: t.content,
497
+ tool_name: t.toolName
498
+ }
499
+ );
500
+ }
501
+ return s;
502
+ }
503
+ }
504
+ export {
505
+ S as Agent,
506
+ w as Conversation,
507
+ v as ConversationManager,
508
+ T as DefaultConversationManager,
509
+ a as Message,
510
+ b as MessageBuilder,
511
+ N as Model,
512
+ C as ModelRequest,
513
+ d as ModelRequestBuilder,
514
+ M as ModelResponse,
515
+ p as ModelResponseBuilder,
516
+ E as OllamaModel,
517
+ O as Parameter,
518
+ I as ParameterBuilder,
519
+ j as Tool,
520
+ _ as ToolCall,
521
+ k as ToolCallBuilder,
522
+ q as ToolSchema,
523
+ x as ToolSchemaBuilder
524
+ };
@@ -0,0 +1 @@
1
+ (function(o,h){typeof exports=="object"&&typeof module<"u"?h(exports):typeof define=="function"&&define.amd?define(["exports"],h):(o=typeof globalThis<"u"?globalThis:o||self,h(o.Tapeworm={}))})(this,(function(o){"use strict";class h{messages;manager;constructor(){this.messages=[],this.manager=new y}append(e){this.messages.push(e),this.messages=this.manager.compact(this.messages)}}class l{role;content;toolCalls;toolName;thinking;constructor(e,s,t,n,r){this.role=e,this.content=s,this.toolCalls=t,this.toolName=n,this.thinking=r}setRole(e){this.role=e}setContent(e){this.content=e}setToolCalls(e){this.toolCalls=e}static builder(){return new _}}class _{_role;_content;_toolCalls;_toolName;_thinking;role(e){return this._role=e,this}content(e){return this._content=e,this}toolCalls(e){return this._toolCalls=e,this}toolName(e){return this._toolName=e,this}thinking(e){return this._thinking=e,this}build(){return new l(this._role,this._content,this._toolCalls,this._toolName,this._thinking)}}class f{compact(e){throw new T("No implementation for conversation manager!")}configure(e){throw new T("No implementation for conversation manager!")}}class y extends f{compact(e){return e}configure(e){}}class T extends Error{constructor(e){super(e),this.name="ConversationManagerNotImplemented"}}class v{async invoke(e){throw new M("The invoke function for this model was not correctly implemented.")}tokenLimit(){throw new M("The tokenLimit function for this model was not correctly implemented.")}}class w{messages;tools;constructor(e,s){this.messages=e,this.tools=s}static builder(){return new c}}class c{_messages;_tools;messages(e){return this._messages=e,this}tools(e){return this._tools=e,this}build(){return this._tools==null&&(this._tools=[]),new w(this._messages,this._tools)}}class b{toolCalls;role;content;thinking;constructor(e,s,t,n){this.toolCalls=e,this.role=s,this.content=t,this.thinking=n}static builder(){return new m}}class m{_toolCalls;_role;_content;_thinking;toolCalls(e){return this._toolCalls=e,this}role(e){return this._role=e,this}content(e){return this._content=e,this}thinking(e){return this._thinking=e,this}build(){return new b(this._toolCalls,this._role,this._content,this._thinking)}}class M extends Error{constructor(e){super(e),this.name="ModelNotImplementedError"}}class S{name;system_prompt;tools;model;conversation;conversationManager;toolNameToIndexMap;async invoke(e){this.conversation==null&&(this.conversation=new h,this.conversationManager!=null&&(this.conversation.manager=this.conversationManager),this.conversation.append(l.builder().role("system").content(this.system_prompt).build())),this.conversation.append(l.builder().role("user").content(e).build());let s=!1;for(;!s;){let t=await this._runQuery();if(this.conversation.append(l.builder().role(t.role??"assistant").content(t.content??"").thinking(t.thinking??"").build()),console.log("Assistant thinking: "+t.thinking),console.log("Assistant reply: "+t.content),s=!0,t.toolCalls!=null&&t.toolCalls.length!=0){s=!1,t.toolCalls.sort((n,r)=>(n.sequence??0)<(r.sequence??0)?-1:1);for(let n in t.toolCalls)this._runTool(t.toolCalls[n])}}}async _runQuery(){return await this.model.invoke(new c().messages(this.conversation?.messages).tools(this.tools).build())}async _runTool(e){if(console.log("Calling tool: "+JSON.stringify(e)),this.generateToolNameToIndexMap(),!(e.name in this.toolNameToIndexMap)){this.conversation.append(l.builder().role("tool").toolName(e.name).content(JSON.stringify({error:"tool does not exist"})).build());return}let s=this.tools[this.toolNameToIndexMap[e.name]];try{let t=s.execute(e.parameters);this.conversation.append(l.builder().role("tool").toolName(e.name).content(JSON.stringify(t)).build())}catch(t){this.conversation.append(l.builder().role("tool").toolName(e.name).content(JSON.stringify(t)).build())}}generateToolNameToIndexMap(){if(this.toolNameToIndexMap==null){this.toolNameToIndexMap={};for(let e=0;e<this.tools.length;e++)this.toolNameToIndexMap[this.tools[e].getName()]=e}}}class d extends Error{constructor(e){super(e),this.name="ToolNotDefinedError"}}class B{name;description;tool_schema;constructor(){this.name=this.getName(),this.description=this.getDescription(),this.tool_schema=this.getToolSchema()}getName(){throw new d("Tool name not defined.")}getDescription(){throw new d("Tool description not defined.")}getToolSchema(){throw new d("Tool parameter schema not defined.")}execute(e){return null}}class p{sequence;name;parameters;type;constructor(e,s,t,n){this.sequence=e,this.name=s,this.parameters=t,this.type=n}static builder(){return new N}}class N{_sequence;_name;_parameters;_type;sequence(e){return this._sequence=e,this}name(e){return this._name=e,this}parameters(e){return this._parameters=e,this}type(e){return this._type=e,this}build(){return this._sequence==null&&(this._sequence=0),new p(this._sequence,this._name,this._parameters,this._type)}}class C{parameters;output;constructor(e,s){this.parameters=e,this.output=s}static builder(){return new q}}class q{_parameters;_output;addParameter(e){return this._parameters==null&&(this._parameters=[]),this._parameters.push(e),this}output(e){return this._output=e,this}build(){return this._parameters==null&&(this._parameters=[]),new C(this._parameters,this._output)}}class k{name;description;type;required;constructor(e,s,t,n){this.name=e,this.description=s,this.type=t,this.required=n,this.assertValidType()}assertValidType(){}static builder(){return new O}}class O{_name;_description;_type;_required;name(e){return this._name=e,this}description(e){return this._description=e,this}type(e){return this._type=e,this}required(e){return this._required=e,this}build(){return this._required==null&&(this._required=!1),new k(this._name,this._description,this._type,this._required)}}class I extends v{endpoint;model;options;constructor(e,s,t){super(),this.endpoint=e,this.model=s,this.options=t}async invoke(e){let s={model:this.model,messages:this._formatMessages(e),tools:this._formatTools(e),...this.options},t=await fetch(this.endpoint+"/api/chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!t.ok)throw new Error(`HTTP error! status: ${t.status}`);let n=await t.json(),r=[];if(n.message.tool_calls)for(let g in n.message.tool_calls){const a=n.message.tool_calls[g];let u="function",j=a[u]?.name,E=a[u]?.index,R=a[u]?.arguments;r.push(p.builder().name(j).type(u).parameters(R).sequence(E).build())}return new m().toolCalls(r).role(n.message.role).content(n.message.content).thinking(n.message.thinking).build()}_formatTools(e){let s=[],t=[];for(let n of e.tools){let r={};for(let a of n.getToolSchema().parameters)r[a.name]={},r[a.name].type=a.name,r[a.name].description=a.description,a.required&&t.push(a.name);let g={type:"function",function:{name:n.getName(),description:n.getDescription(),parameters:{type:"object",properties:r,required:t}}};s.push(g)}return s}_formatMessages(e){let s=[];for(let t of e.messages){if(t.role=="assistant"||t.role=="system"||t.role=="user"){s.push(t);continue}t.role=="tool"&&s.push({role:"tool",content:t.content,tool_name:t.toolName})}return s}}o.Agent=S,o.Conversation=h,o.ConversationManager=f,o.DefaultConversationManager=y,o.Message=l,o.MessageBuilder=_,o.Model=v,o.ModelRequest=w,o.ModelRequestBuilder=c,o.ModelResponse=b,o.ModelResponseBuilder=m,o.OllamaModel=I,o.Parameter=k,o.ParameterBuilder=O,o.Tool=B,o.ToolCall=p,o.ToolCallBuilder=N,o.ToolSchema=C,o.ToolSchemaBuilder=q,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})}));
package/package.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "@atgs/tapeworm",
3
+ "version": "0.0.1",
4
+ "type": "module",
5
+ "main": "dist/tapeworm.cjs.js",
6
+ "module": "dist/tapeworm.es.js",
7
+ "browser": "dist/tapeworm.umd.js",
8
+ "types": "dist/index.d.ts",
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "scripts": {
13
+ "build": "vite build",
14
+ "test": "jest"
15
+ },
16
+ "devDependencies": {
17
+ "@babel/preset-env": "^7.28.5",
18
+ "@babel/preset-typescript": "^7.28.5",
19
+ "@types/jest": "^30.0.0",
20
+ "jest": "^30.2.0",
21
+ "ts-node": "^10.9.2",
22
+ "typescript": "^5.9.3",
23
+ "vite": "^7.2.7"
24
+ }
25
+ }