@cslug/ai 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +7 -7
  2. package/src/ai.ts +120 -33
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cslug/ai",
3
- "version": "0.7.1",
3
+ "version": "0.8.0",
4
4
  "description": "Agents and tools, structured output, prompts, streaming; Anthropic and OpenAI-compatible providers.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -29,12 +29,12 @@
29
29
  "bun": ">=1.3.14"
30
30
  },
31
31
  "peerDependencies": {
32
- "@cslug/core": "0.7.1",
33
- "@cslug/validation": "0.7.1",
34
- "@cslug/queue": "0.7.1",
35
- "@cslug/http": "0.7.1",
36
- "@cslug/database": "0.7.1",
37
- "@cslug/search": "0.7.1"
32
+ "@cslug/core": "0.8.0",
33
+ "@cslug/validation": "0.8.0",
34
+ "@cslug/queue": "0.8.0",
35
+ "@cslug/http": "0.8.0",
36
+ "@cslug/database": "0.8.0",
37
+ "@cslug/search": "0.8.0"
38
38
  },
39
39
  "peerDependenciesMeta": {
40
40
  "@cslug/queue": {
package/src/ai.ts CHANGED
@@ -1,4 +1,15 @@
1
- import { type Application, Cache, Clock, CslugError, currentContext, type Logger, resolve } from '@cslug/core'
1
+ import {
2
+ type Application,
3
+ Cache,
4
+ Clock,
5
+ CslugError,
6
+ currentContext,
7
+ type Logger,
8
+ resolve,
9
+ runInContext,
10
+ type Span,
11
+ Tracer,
12
+ } from '@cslug/core'
2
13
  import { type AgentSettings, type RunnableTool, type RunOptions, renderInstructions } from './agent'
3
14
  import { AiStream } from './ai-stream'
4
15
  import { Budget, type BudgetConfig, costOf, type ModelPrice } from './budget'
@@ -254,42 +265,118 @@ export class Ai {
254
265
  const provider = this.provider(agent.provider)
255
266
  const usage: Required<Usage> = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 }
256
267
  const budget = this.budget
257
- for (let step = 1; step <= maxSteps; step++) {
258
- await budget?.check()
259
- let response: ModelResponse | undefined
260
- if (streaming)
261
- for await (const event of provider.stream(request)) {
262
- if (event.type === 'text') yield event
263
- else response = event.response
268
+ // spans (OpenTelemetry gen_ai conventions): the run, each model call, each tool call inside the run
269
+ const tracer = this.app.resolve(Tracer)
270
+ const ctx = currentContext()
271
+ const runSpan = tracer.enabled
272
+ ? tracer.startSpan(`invoke_agent ${agent.constructor.name}`, {
273
+ parent: ctx?.traceparent as string | undefined,
274
+ attributes: {
275
+ 'gen_ai.operation.name': 'invoke_agent',
276
+ 'gen_ai.agent.name': agent.constructor.name,
277
+ 'gen_ai.request.model': request.model,
278
+ 'cslug.ai.run_id': runId,
279
+ },
280
+ })
281
+ : undefined
282
+ const inRun = <T>(fn: () => T): T =>
283
+ runSpan && ctx
284
+ ? runInContext(
285
+ {
286
+ ...ctx,
287
+ span: runSpan,
288
+ traceId: runSpan.traceId,
289
+ spanId: runSpan.spanId,
290
+ traceparent: runSpan.traceparent,
291
+ },
292
+ fn,
293
+ )
294
+ : fn()
295
+ try {
296
+ for (let step = 1; step <= maxSteps; step++) {
297
+ await budget?.check()
298
+ let response: ModelResponse | undefined
299
+ const chat: Span | undefined = runSpan
300
+ ? tracer.startSpan(`chat ${request.model}`, {
301
+ kind: 'client',
302
+ parent: runSpan.traceparent,
303
+ attributes: { 'gen_ai.operation.name': 'chat', 'gen_ai.request.model': request.model },
304
+ })
305
+ : undefined
306
+ try {
307
+ if (streaming)
308
+ for await (const event of provider.stream(request)) {
309
+ if (event.type === 'text') yield event
310
+ else response = event.response
311
+ }
312
+ else response = await provider.complete(request)
313
+ } catch (error) {
314
+ chat?.recordError(error)
315
+ throw error
316
+ } finally {
317
+ if (response)
318
+ chat?.setAttributes({
319
+ 'gen_ai.usage.input_tokens': response.usage.inputTokens,
320
+ 'gen_ai.usage.output_tokens': response.usage.outputTokens,
321
+ })
322
+ chat?.end()
264
323
  }
265
- else response = await provider.complete(request)
266
- if (!response) throw new CslugError('ai.provider', 'The stream ended without a response')
267
- for (const k of Object.keys(usage) as (keyof Usage)[]) usage[k] += response.usage[k] ?? 0
268
- await budget?.charge(request.model, response.usage)
269
- request.messages.push({ role: 'assistant', content: response.content })
270
- const calls = response.content.filter((b) => b.type === 'tool_use')
271
- if (!calls.length) {
272
- const costUsd = costOf(request.model, usage, this.config.prices)
273
- this.log.info('ai.run', { agent: agent.constructor.name, model: request.model, steps: step, ...usage, costUsd })
274
- const text = textOf(response.content)
275
- const raw = agent.output ? this.json(text) : text
276
- const result: AiResult = {
277
- runId,
278
- raw,
279
- value: this.validate(agent, raw, text),
280
- model: request.model,
281
- steps: step,
282
- usage,
283
- costUsd,
284
- messages: [...request.messages],
324
+ if (!response) throw new CslugError('ai.provider', 'The stream ended without a response')
325
+ for (const k of Object.keys(usage) as (keyof Usage)[]) usage[k] += response.usage[k] ?? 0
326
+ await budget?.charge(request.model, response.usage)
327
+ request.messages.push({ role: 'assistant', content: response.content })
328
+ const calls = response.content.filter((b) => b.type === 'tool_use')
329
+ if (!calls.length) {
330
+ const costUsd = costOf(request.model, usage, this.config.prices)
331
+ runSpan?.setAttributes({
332
+ 'gen_ai.usage.input_tokens': usage.inputTokens,
333
+ 'gen_ai.usage.output_tokens': usage.outputTokens,
334
+ 'cslug.ai.steps': step,
335
+ 'cslug.ai.cost_usd': costUsd,
336
+ })
337
+ this.log.info('ai.run', {
338
+ agent: agent.constructor.name,
339
+ model: request.model,
340
+ steps: step,
341
+ ...usage,
342
+ costUsd,
343
+ })
344
+ const text = textOf(response.content)
345
+ const raw = agent.output ? this.json(text) : text
346
+ const result: AiResult = {
347
+ runId,
348
+ raw,
349
+ value: this.validate(agent, raw, text),
350
+ model: request.model,
351
+ steps: step,
352
+ usage,
353
+ costUsd,
354
+ messages: [...request.messages],
355
+ }
356
+ yield { type: 'result' as const, result }
357
+ return
285
358
  }
286
- yield { type: 'result' as const, result }
287
- return
359
+ // every result of one turn goes back in one message
360
+ const results = await inRun(() =>
361
+ Promise.all(
362
+ calls.map((call) =>
363
+ tracer.span(
364
+ `execute_tool ${call.name}`,
365
+ { attributes: { 'gen_ai.operation.name': 'execute_tool', 'gen_ai.tool.name': call.name } },
366
+ () => this.call(tools, call),
367
+ ),
368
+ ),
369
+ ),
370
+ )
371
+ request.messages.push({ role: 'user', content: results })
288
372
  }
289
- // every result of one turn goes back in one message
290
- request.messages.push({ role: 'user', content: await Promise.all(calls.map((call) => this.call(tools, call))) })
373
+ throw new CslugError('ai.max_steps', `${agent.constructor.name} did not finish in ${maxSteps} steps`)
374
+ } catch (error) {
375
+ runSpan?.recordError(error)
376
+ throw error
377
+ } finally {
378
+ runSpan?.end()
291
379
  }
292
- throw new CslugError('ai.max_steps', `${agent.constructor.name} did not finish in ${maxSteps} steps`)
293
380
  }
294
381
 
295
382
  private async call(tools: RunnableTool[], call: Extract<Block, { type: 'tool_use' }>): Promise<Block> {