@cslug/ai 0.4.1 → 0.6.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.
@@ -0,0 +1,79 @@
1
+ import { join } from 'node:path'
2
+ import { type Application, Clock } from '@cslug/core'
3
+ import type { ConversationRow, ConversationStore } from './conversations'
4
+ import type { Message } from './model'
5
+
6
+ /** The `cslug_ai_conversations`, `cslug_ai_messages` and `cslug_ai_runs` migration (registered with @cslug/database). */
7
+ export const AI_MIGRATIONS = join(import.meta.dir, '../migrations')
8
+
9
+ /** The tables through @cslug/database (ambient transaction when there is one), or undefined without it. */
10
+ export async function databaseStore(app: Application): Promise<ConversationStore | undefined> {
11
+ const db = await import('@cslug/database').catch(() => undefined)
12
+ if (!db || !app.has(db.Database)) return undefined
13
+ db.addMigrations(AI_MIGRATIONS)
14
+ const { sql } = db
15
+ const database = () => app.resolve(db.Database)
16
+ const now = () => app.resolve(Clock).now()
17
+ const row = (r: ConversationRow) => ({ ...r, metadata: r.metadata ?? {} })
18
+ return {
19
+ async create(c) {
20
+ await database().exec(sql`insert into cslug_ai_conversations
21
+ (id, agent, owner_type, owner_id, title, metadata, created_at, updated_at)
22
+ values (${c.id}, ${c.agent}, ${c.ownerType}, ${c.ownerId}, ${c.title}, ${sql.json(c.metadata)}, ${c.createdAt},
23
+ ${c.createdAt})`)
24
+ },
25
+ async find(id) {
26
+ const found = await database().maybeOne<ConversationRow>(
27
+ sql`select * from cslug_ai_conversations where id = ${id}`,
28
+ )
29
+ return found && row(found)
30
+ },
31
+ async list({ ownerType, ownerId, agent, limit }) {
32
+ const rows = await database().many<ConversationRow>(sql`select * from cslug_ai_conversations
33
+ where owner_type is not distinct from ${ownerType} and owner_id is not distinct from ${ownerId}
34
+ ${agent ? sql`and agent = ${agent}` : sql.empty}
35
+ order by updated_at desc, id desc limit ${limit}`)
36
+ return rows.map(row)
37
+ },
38
+ async messages(id) {
39
+ const rows = await database().many<{ role: Message['role']; content: Message['content'] }>(
40
+ sql`select role, content from cslug_ai_messages where conversation_id = ${id} order by position`,
41
+ )
42
+ return rows.map(({ role, content }) => ({ role, content }))
43
+ },
44
+ async append(id, after, messages, runId) {
45
+ if (!messages.length) return true
46
+ return database().transaction(async (tx) => {
47
+ // the count moves only if no other turn was stored since this one read the history
48
+ const moved = await tx.exec(sql`update cslug_ai_conversations
49
+ set message_count = message_count + ${messages.length}, updated_at = ${now()}
50
+ where id = ${id} and message_count = ${after}`)
51
+ if (!moved) return false
52
+ const at = now()
53
+ const values = messages.map(
54
+ (m, i) => sql`(${id}, ${after + i}, ${m.role}, ${sql.json(m.content)}, ${runId}, ${at})`,
55
+ )
56
+ await tx.exec(sql`insert into cslug_ai_messages (conversation_id, position, role, content, run_id, created_at)
57
+ values ${sql.join(values)}`)
58
+ return true
59
+ })
60
+ },
61
+ async update(id, { title, metadata }) {
62
+ await database().exec(sql`update cslug_ai_conversations set
63
+ title = ${title === undefined ? sql`title` : title},
64
+ metadata = ${metadata === undefined ? sql`metadata` : sql.json(metadata)},
65
+ updated_at = ${now()}
66
+ where id = ${id}`)
67
+ },
68
+ async delete(id) {
69
+ await database().exec(sql`delete from cslug_ai_conversations where id = ${id}`)
70
+ },
71
+ async recordRun(r) {
72
+ await database().exec(sql`insert into cslug_ai_runs (id, agent, model, conversation_id, user_id, status, steps,
73
+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost_usd, error, started_at, finished_at)
74
+ values (${r.id}, ${r.agent}, ${r.model}, ${r.conversationId ?? null}, ${r.userId ?? null}, ${r.status},
75
+ ${r.steps}, ${r.usage.inputTokens}, ${r.usage.outputTokens}, ${r.usage.cacheReadTokens},
76
+ ${r.usage.cacheWriteTokens}, ${r.costUsd ?? null}, ${r.error ?? null}, ${r.startedAt}, ${r.finishedAt})`)
77
+ },
78
+ }
79
+ }
@@ -0,0 +1,251 @@
1
+ import {
2
+ type Application,
3
+ Clock,
4
+ ConflictError,
5
+ CslugError,
6
+ currentContext,
7
+ type Logger,
8
+ Logger as LoggerToken,
9
+ NotFoundError,
10
+ runInContext,
11
+ } from '@cslug/core'
12
+ import type { Agent, AgentOutput } from './agent'
13
+ import { Ai, type AiResult, type RunRecord } from './ai'
14
+ import { AiStream } from './ai-stream'
15
+ import type { Message } from './model'
16
+ import { CONVERSATION_KEY, remember } from './search-tools'
17
+
18
+ type AgentClass<A extends Agent> = abstract new (...args: never[]) => A
19
+
20
+ /** Who a conversation belongs to: a user row (`{ id }`), or another kind of owner with `ownerType`. */
21
+ export type OwnerRef = { id: string | number }
22
+
23
+ export type ConversationRow = {
24
+ id: string
25
+ agent: string
26
+ ownerType: string | null
27
+ ownerId: string | null
28
+ title: string | null
29
+ metadata: Record<string, unknown>
30
+ messageCount: number
31
+ createdAt: Date
32
+ updatedAt: Date
33
+ }
34
+
35
+ /** Where conversations, messages and runs are kept (`cslug_ai_*` tables, set by `AiProvider` with @cslug/database). */
36
+ export interface ConversationStore {
37
+ create(
38
+ row: Pick<ConversationRow, 'id' | 'agent' | 'ownerType' | 'ownerId' | 'title' | 'metadata' | 'createdAt'>,
39
+ ): Promise<void>
40
+ find(id: string): Promise<ConversationRow | null>
41
+ list(where: {
42
+ ownerType: string | null
43
+ ownerId: string | null
44
+ agent?: string
45
+ limit: number
46
+ }): Promise<ConversationRow[]>
47
+ messages(id: string): Promise<Message[]>
48
+ /** Append after exactly `after` messages; false when another turn was stored first. */
49
+ append(id: string, after: number, messages: Message[], runId: string): Promise<boolean>
50
+ update(id: string, changes: { title?: string | null; metadata?: Record<string, unknown> }): Promise<void>
51
+ delete(id: string): Promise<void>
52
+ recordRun(run: RunRecord): Promise<void>
53
+ }
54
+
55
+ export type StartOptions = {
56
+ /** The owner: the signed-in user by default; `null` for none (anyone with the id can continue it). */
57
+ owner?: OwnerRef | null
58
+ /** The kind of owner (default `user`; only `user` owners are matched with the signed-in user). */
59
+ ownerType?: string
60
+ title?: string
61
+ metadata?: Record<string, unknown>
62
+ }
63
+
64
+ export type FindOptions = {
65
+ /** Check against this owner instead of the signed-in user (a job, another kind of owner). */
66
+ owner?: OwnerRef
67
+ ownerType?: string
68
+ }
69
+
70
+ /** A stored conversation with one agent: each `send` continues it and stores the new messages. */
71
+ export class Conversation<A extends Agent = Agent> {
72
+ constructor(
73
+ private row: ConversationRow,
74
+ readonly agent: A,
75
+ private readonly store: ConversationStore,
76
+ private readonly ai: Ai,
77
+ ) {}
78
+
79
+ get id(): string {
80
+ return this.row.id
81
+ }
82
+ get title(): string | null {
83
+ return this.row.title
84
+ }
85
+ get metadata(): Record<string, unknown> {
86
+ return this.row.metadata
87
+ }
88
+ get owner(): { type: string; id: string } | null {
89
+ return this.row.ownerType && this.row.ownerId ? { type: this.row.ownerType, id: this.row.ownerId } : null
90
+ }
91
+ get createdAt(): Date {
92
+ return this.row.createdAt
93
+ }
94
+
95
+ /** Every stored message, oldest first (provider blocks included; send them back unchanged). */
96
+ messages(): Promise<Message[]> {
97
+ return this.store.messages(this.id)
98
+ }
99
+
100
+ /** Continue the conversation; the new messages are stored with the run's id. */
101
+ async send(input: string, options: { context?: Record<string, unknown> } = {}): Promise<AiResult<AgentOutput<A>>> {
102
+ const history = await this.messages()
103
+ const result = await this.scoped(() => this.ai.result(this.agent, { input, history, ...options }, this.meta()))
104
+ await this.storeTurn(history.length, result)
105
+ return result as AiResult<AgentOutput<A>>
106
+ }
107
+
108
+ /** Run `fn` with this conversation in the ambient context (`recallTool()` reads its owner from there). */
109
+ private scoped<T>(fn: () => T): T {
110
+ const context = currentContext()
111
+ if (!context) return fn()
112
+ return runInContext({ ...context, [CONVERSATION_KEY]: { id: this.id, owner: this.owner } }, fn)
113
+ }
114
+
115
+ /** `send` as a stream: the text as it arrives; the messages are stored once it has been read. */
116
+ stream(input: string, options: { context?: Record<string, unknown> } = {}): AiStream<AgentOutput<A>> {
117
+ const self = this
118
+ return new AiStream(
119
+ (async function* () {
120
+ const history = await self.messages()
121
+ const inner = self.scoped(() => self.ai.stream(self.agent, { input, history, ...options }, self.meta()))
122
+ const iterator = inner[Symbol.asyncIterator]()
123
+ for (
124
+ let next = await self.scoped(() => iterator.next());
125
+ !next.done;
126
+ next = await self.scoped(() => iterator.next())
127
+ )
128
+ yield { type: 'text' as const, text: next.value }
129
+ const result = await inner.result
130
+ await self.storeTurn(history.length, result)
131
+ yield { type: 'result' as const, result }
132
+ })(),
133
+ )
134
+ }
135
+
136
+ /** Change the title or replace the metadata. */
137
+ async update(changes: { title?: string | null; metadata?: Record<string, unknown> }): Promise<void> {
138
+ await this.store.update(this.id, changes)
139
+ this.row = { ...this.row, ...changes } as ConversationRow
140
+ }
141
+
142
+ /** Delete the conversation and its messages (its run records stay, without the link; recall forgets it). */
143
+ async delete(): Promise<void> {
144
+ await this.store.delete(this.id)
145
+ await this.ai.recallIndex?.removeWhere({ conversationId: this.id })
146
+ }
147
+
148
+ private meta() {
149
+ return { conversationId: this.id, compact: true }
150
+ }
151
+
152
+ private async storeTurn(after: number, result: AiResult): Promise<void> {
153
+ const stored = await this.store.append(this.id, after, result.messages.slice(after), result.runId)
154
+ if (!stored)
155
+ throw new ConflictError(
156
+ 'ai.conversation_changed',
157
+ { id: this.id },
158
+ 'Another message was added to this conversation during the run; reload it and send again',
159
+ )
160
+ this.row = { ...this.row, messageCount: result.messages.length }
161
+ const recall = this.ai.recallIndex
162
+ if (recall)
163
+ // best effort: a turn is stored even if recall (an embedding call) fails
164
+ await remember(recall, { id: this.id, owner: this.owner }, after, result.messages.slice(after)).catch((error) =>
165
+ this.log?.warn('ai.recall_failed', { conversation: this.id, error }),
166
+ )
167
+ }
168
+
169
+ /** Set by `Conversations` (recall failures are logged). */
170
+ log?: Logger
171
+ }
172
+
173
+ const ownerKey = (owner: OwnerRef | null | undefined, type = 'user') =>
174
+ owner ? { ownerType: type, ownerId: String(owner.id) } : { ownerType: null, ownerId: null }
175
+
176
+ const signedIn = (): OwnerRef | undefined => {
177
+ const id = currentContext()?.userId
178
+ return id === undefined || id === null ? undefined : { id: String(id) }
179
+ }
180
+
181
+ /**
182
+ * Stored conversations (`@inject(Conversations)`), with @cslug/database: `start(Agent, { owner })`, `find(Agent, id)`
183
+ * (owner checked), `list()`.
184
+ */
185
+ export class Conversations {
186
+ /** Set by `AiProvider` when @cslug/database is installed. */
187
+ store?: ConversationStore
188
+
189
+ constructor(private readonly app: Application) {}
190
+
191
+ private get db(): ConversationStore {
192
+ if (!this.store)
193
+ throw new CslugError(
194
+ 'ai.no_database',
195
+ 'Stored conversations need @cslug/database (cslug add database); without it, pass `history` to run()',
196
+ )
197
+ return this.store
198
+ }
199
+
200
+ private open<A extends Agent>(row: ConversationRow, agent: AgentClass<A>): Conversation<A> {
201
+ const conversation = new Conversation(row, this.app.resolve(agent as never) as A, this.db, this.app.resolve(Ai))
202
+ conversation.log = this.app.resolve(LoggerToken)
203
+ return conversation
204
+ }
205
+
206
+ /** A new conversation with `agent`, owned by the signed-in user unless `owner` says otherwise. */
207
+ async start<A extends Agent>(agent: AgentClass<A>, options: StartOptions = {}): Promise<Conversation<A>> {
208
+ const owner = options.owner === undefined ? signedIn() : options.owner
209
+ const row = {
210
+ id: Bun.randomUUIDv7(),
211
+ agent: agent.name,
212
+ ...ownerKey(owner, options.ownerType),
213
+ title: options.title ?? null,
214
+ metadata: options.metadata ?? {},
215
+ createdAt: this.app.resolve(Clock).now(),
216
+ }
217
+ await this.db.create(row)
218
+ return this.open({ ...row, messageCount: 0, updatedAt: row.createdAt }, agent)
219
+ }
220
+
221
+ /**
222
+ * A conversation with `agent`, if its owner is the signed-in user (or `options.owner`); a conversation without an
223
+ * owner is open to anyone with its id. Anything else is a `NotFoundError`, so ids are not confirmed to strangers.
224
+ */
225
+ async find<A extends Agent>(agent: AgentClass<A>, id: string, options: FindOptions = {}): Promise<Conversation<A>> {
226
+ const row = UUID.test(id) ? await this.db.find(id) : null
227
+ if (!row || row.agent !== agent.name || !this.allowed(row, options)) throw new NotFoundError('conversation', id)
228
+ return this.open(row, agent)
229
+ }
230
+
231
+ /** The owner's conversations, most recent first (default: the signed-in user's). */
232
+ async list<A extends Agent>(
233
+ options: FindOptions & { agent?: AgentClass<A>; limit?: number } = {},
234
+ ): Promise<ConversationRow[]> {
235
+ const owner = options.owner ?? signedIn()
236
+ if (!owner) return []
237
+ return this.db.list({
238
+ ...ownerKey(owner, options.ownerType),
239
+ ...(options.agent ? { agent: options.agent.name } : {}),
240
+ limit: options.limit ?? 50,
241
+ })
242
+ }
243
+
244
+ private allowed(row: ConversationRow, { owner, ownerType = 'user' }: FindOptions): boolean {
245
+ if (row.ownerId === null) return true
246
+ const expected = owner ?? (row.ownerType === 'user' ? signedIn() : undefined)
247
+ return !!expected && row.ownerType === (owner ? ownerType : 'user') && row.ownerId === String(expected.id)
248
+ }
249
+ }
250
+
251
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
package/src/drivers.ts ADDED
@@ -0,0 +1,249 @@
1
+ import { CslugError } from '@cslug/core'
2
+ import {
3
+ AiRefusalError,
4
+ type Block,
5
+ type ModelRequest,
6
+ type ModelResponse,
7
+ type Provider,
8
+ postJson,
9
+ type StreamEvent,
10
+ sseEvents,
11
+ } from './model'
12
+
13
+ type Json = Record<string, unknown>
14
+
15
+ export type AnthropicConfig = {
16
+ driver: 'anthropic'
17
+ /** Default: `ANTHROPIC_API_KEY`. */
18
+ apiKey?: string
19
+ baseUrl?: string
20
+ /**
21
+ * Prompt caching, on by default: a breakpoint on the system prompt, and automatic caching (top-level
22
+ * `cache_control`) once there is more than one message, so each turn or tool round reads the earlier ones.
23
+ */
24
+ promptCaching?: boolean
25
+ /** Server-side refusal fallbacks (`fallbacks: "default"`) on the models that have them; on by default. */
26
+ fallbacks?: boolean
27
+ }
28
+
29
+ const API_VERSION = '2026-10-21'
30
+ const FALLBACK_BETA = 'server-side-fallback-2026-07-01'
31
+ const WITH_FALLBACKS = ['claude-fable-5-2', 'claude-fable-5-1', 'claude-opus-5-5', 'claude-opus-5', 'claude-sonnet-5-5']
32
+ const COMPACTION_BETA = 'compact-2026-01-12'
33
+ /** Models with server-side compaction (`context_management` edit `compact_20260112`). */
34
+ const WITH_COMPACTION = [
35
+ 'claude-fable-5-2',
36
+ 'claude-fable-5-1',
37
+ 'claude-fable-5',
38
+ 'claude-opus-5-5',
39
+ 'claude-opus-5',
40
+ 'claude-opus-4-8',
41
+ 'claude-opus-4-7',
42
+ 'claude-opus-4-6',
43
+ 'claude-sonnet-5-5',
44
+ 'claude-sonnet-5',
45
+ 'claude-sonnet-4-6',
46
+ 'claude-haiku-5-5',
47
+ ]
48
+
49
+ const toAnthropic = (b: Block): unknown =>
50
+ b.type === 'raw'
51
+ ? b.value
52
+ : b.type === 'tool_result'
53
+ ? { type: 'tool_result', tool_use_id: b.toolUseId, content: b.content, ...(b.isError ? { is_error: true } : {}) }
54
+ : b
55
+ const fromAnthropic = (b: Json): Block =>
56
+ b.type === 'text'
57
+ ? { type: 'text', text: String(b.text) }
58
+ : b.type === 'tool_use'
59
+ ? { type: 'tool_use', id: String(b.id), name: String(b.name), input: b.input }
60
+ : { type: 'raw', value: b } // thinking, fallback…: sent back unchanged
61
+
62
+ /** The Claude Messages API over `fetch` (no SDK: cslug has no third-party runtime dependencies). */
63
+ export class AnthropicProvider implements Provider {
64
+ constructor(private readonly config: AnthropicConfig) {}
65
+
66
+ private request(r: ModelRequest, stream: boolean): [string, Record<string, string>, Json] {
67
+ const key = this.config.apiKey ?? process.env.ANTHROPIC_API_KEY
68
+ if (!key) throw new CslugError('ai.no_key', 'Set ANTHROPIC_API_KEY (or providers.<name>.apiKey in config/ai.ts)')
69
+ const fallbacks = this.config.fallbacks !== false && WITH_FALLBACKS.includes(r.model)
70
+ const compact = !!r.compact && WITH_COMPACTION.includes(r.model)
71
+ const betas = [...(fallbacks ? [FALLBACK_BETA] : []), ...(compact ? [COMPACTION_BETA] : [])]
72
+ const format = r.output ? { format: { type: 'json_schema', schema: r.output } } : {}
73
+ const caching = this.config.promptCaching !== false
74
+ const body: Json = {
75
+ model: r.model,
76
+ max_tokens: r.maxTokens ?? (stream ? 64_000 : 16_000),
77
+ messages: r.messages.map((m) => ({ role: m.role, content: m.content.map(toAnthropic) })),
78
+ ...(r.system
79
+ ? {
80
+ system: [
81
+ {
82
+ type: 'text',
83
+ text: r.system,
84
+ ...(caching ? { cache_control: { type: 'ephemeral' } } : {}),
85
+ },
86
+ ],
87
+ }
88
+ : {}),
89
+ ...(r.tools.length
90
+ ? { tools: r.tools.map((t) => ({ name: t.name, description: t.description, input_schema: t.inputSchema })) }
91
+ : {}),
92
+ ...(r.output || r.effort ? { output_config: { ...format, ...(r.effort ? { effort: r.effort } : {}) } } : {}),
93
+ ...(caching && r.messages.length > 1 ? { cache_control: { type: 'ephemeral' } } : {}),
94
+ ...(compact ? { context_management: { edits: [{ type: 'compact_20260112' }] } } : {}),
95
+ ...(fallbacks ? { fallbacks: 'default' } : {}),
96
+ ...(stream ? { stream: true } : {}),
97
+ }
98
+ const headers = {
99
+ 'x-api-key': key,
100
+ 'anthropic-version': API_VERSION,
101
+ ...(betas.length ? { 'anthropic-beta': betas.join(',') } : {}),
102
+ }
103
+ return [`${this.config.baseUrl ?? 'https://api.anthropic.com'}/v1/messages`, headers, body]
104
+ }
105
+
106
+ private response(message: Json): ModelResponse {
107
+ if (message.stop_reason === 'refusal')
108
+ throw new AiRefusalError((message.stop_details as Json | null)?.category as string | undefined)
109
+ const usage = (message.usage ?? {}) as Json
110
+ return {
111
+ content: ((message.content ?? []) as Json[]).map(fromAnthropic),
112
+ stopReason: String(message.stop_reason),
113
+ usage: {
114
+ inputTokens: Number(usage.input_tokens ?? 0),
115
+ outputTokens: Number(usage.output_tokens ?? 0),
116
+ cacheReadTokens: Number(usage.cache_read_input_tokens ?? 0),
117
+ cacheWriteTokens: Number(usage.cache_creation_input_tokens ?? 0),
118
+ },
119
+ }
120
+ }
121
+
122
+ async complete(r: ModelRequest): Promise<ModelResponse> {
123
+ return this.response((await (await postJson(...this.request(r, false))).json()) as Json)
124
+ }
125
+
126
+ /** Text deltas as they arrive; blocks are rebuilt from their deltas (tool inputs from `partial_json`). */
127
+ async *stream(r: ModelRequest): AsyncIterable<StreamEvent> {
128
+ const res = await postJson(...this.request(r, true))
129
+ const message: Json = { content: [] }
130
+ const blocks = message.content as Json[]
131
+ const partial: string[] = []
132
+ for await (const { data } of sseEvents(res.body as ReadableStream<Uint8Array>)) {
133
+ const e = JSON.parse(data) as Json
134
+ if (e.type === 'message_start') Object.assign(message, e.message, { content: blocks })
135
+ else if (e.type === 'content_block_start') blocks[Number(e.index)] = { ...(e.content_block as Json) }
136
+ else if (e.type === 'content_block_delta') {
137
+ const block = blocks[Number(e.index)] as Json
138
+ const delta = e.delta as Json
139
+ if (delta.type === 'input_json_delta')
140
+ partial[Number(e.index)] = (partial[Number(e.index)] ?? '') + delta.partial_json
141
+ else
142
+ for (const [k, v] of Object.entries(delta))
143
+ if (k !== 'type') block[k] = typeof v === 'string' && typeof block[k] === 'string' ? block[k] + v : v
144
+ if (delta.type === 'text_delta') yield { type: 'text', text: String(delta.text) }
145
+ } else if (e.type === 'content_block_stop' && partial[Number(e.index)] !== undefined)
146
+ (blocks[Number(e.index)] as Json).input = JSON.parse(partial[Number(e.index)] || '{}')
147
+ else if (e.type === 'message_delta') {
148
+ Object.assign(message, e.delta)
149
+ message.usage = { ...(message.usage as Json), ...(e.usage as Json) }
150
+ } else if (e.type === 'error') throw new CslugError('ai.provider', JSON.stringify(e.error))
151
+ }
152
+ yield { type: 'done', response: this.response(message) }
153
+ }
154
+ }
155
+
156
+ export type OpenAiCompatibleConfig = { driver: 'openai-compatible'; baseUrl: string; apiKey?: string }
157
+
158
+ /** Any OpenAI-compatible chat completions endpoint (Ollama, vLLM, LM Studio…). */
159
+ export class OpenAiCompatibleProvider implements Provider {
160
+ constructor(private readonly config: OpenAiCompatibleConfig) {}
161
+
162
+ private request(r: ModelRequest, stream: boolean): [string, Record<string, string>, Json] {
163
+ const messages: Json[] = r.system ? [{ role: 'system', content: r.system }] : []
164
+ for (const m of r.messages) {
165
+ const text = m.content.flatMap((b) => (b.type === 'text' ? [b.text] : [])).join('')
166
+ const calls = m.content.flatMap((b) =>
167
+ b.type === 'tool_use'
168
+ ? [{ id: b.id, type: 'function', function: { name: b.name, arguments: JSON.stringify(b.input) } }]
169
+ : [],
170
+ )
171
+ for (const b of m.content)
172
+ if (b.type === 'tool_result') messages.push({ role: 'tool', tool_call_id: b.toolUseId, content: b.content })
173
+ if (text || calls.length)
174
+ messages.push({ role: m.role, content: text, ...(calls.length ? { tool_calls: calls } : {}) })
175
+ }
176
+ const body: Json = {
177
+ model: r.model,
178
+ messages,
179
+ ...(r.maxTokens ? { max_tokens: r.maxTokens } : {}),
180
+ ...(r.tools.length
181
+ ? {
182
+ tools: r.tools.map((t) => ({
183
+ type: 'function',
184
+ function: { name: t.name, description: t.description, parameters: t.inputSchema },
185
+ })),
186
+ }
187
+ : {}),
188
+ ...(r.output
189
+ ? { response_format: { type: 'json_schema', json_schema: { name: 'output', schema: r.output, strict: true } } }
190
+ : {}),
191
+ ...(stream ? { stream: true } : {}),
192
+ }
193
+ const headers: Record<string, string> = this.config.apiKey ? { authorization: `Bearer ${this.config.apiKey}` } : {}
194
+ return [`${this.config.baseUrl.replace(/\/$/, '')}/chat/completions`, headers, body]
195
+ }
196
+
197
+ private response(
198
+ text: string,
199
+ calls: { id: string; name: string; arguments: string }[],
200
+ finish: unknown,
201
+ usage?: Json,
202
+ ) {
203
+ const content: Block[] = text ? [{ type: 'text', text }] : []
204
+ for (const c of calls)
205
+ content.push({ type: 'tool_use', id: c.id, name: c.name, input: JSON.parse(c.arguments || '{}') })
206
+ return {
207
+ content,
208
+ stopReason: calls.length ? 'tool_use' : finish === 'length' ? 'max_tokens' : 'end_turn',
209
+ usage: { inputTokens: Number(usage?.prompt_tokens ?? 0), outputTokens: Number(usage?.completion_tokens ?? 0) },
210
+ }
211
+ }
212
+
213
+ async complete(r: ModelRequest): Promise<ModelResponse> {
214
+ const json = (await (await postJson(...this.request(r, false))).json()) as Json
215
+ const choice = ((json.choices ?? []) as Json[])[0] ?? {}
216
+ const message = (choice.message ?? {}) as Json
217
+ const calls = ((message.tool_calls ?? []) as Json[]).map((c) => {
218
+ const fn = c.function as Json
219
+ return { id: String(c.id), name: String(fn.name), arguments: String(fn.arguments ?? '') }
220
+ })
221
+ return this.response(String(message.content ?? ''), calls, choice.finish_reason, json.usage as Json)
222
+ }
223
+
224
+ async *stream(r: ModelRequest): AsyncIterable<StreamEvent> {
225
+ const res = await postJson(...this.request(r, true))
226
+ let text = ''
227
+ let finish: unknown
228
+ const calls: { id: string; name: string; arguments: string }[] = []
229
+ for await (const { data } of sseEvents(res.body as ReadableStream<Uint8Array>)) {
230
+ if (data === '[DONE]') break
231
+ const choice = (((JSON.parse(data) as Json).choices ?? []) as Json[])[0] ?? {}
232
+ const delta = (choice.delta ?? {}) as Json
233
+ if (typeof delta.content === 'string' && delta.content) {
234
+ text += delta.content
235
+ yield { type: 'text', text: delta.content }
236
+ }
237
+ for (const c of (delta.tool_calls ?? []) as Json[]) {
238
+ const fn = (c.function ?? {}) as Json
239
+ const call = calls[Number(c.index)] ?? { id: '', name: '', arguments: '' }
240
+ calls[Number(c.index)] = call
241
+ call.id ||= String(c.id ?? '')
242
+ call.name ||= String(fn.name ?? '')
243
+ call.arguments += String(fn.arguments ?? '')
244
+ }
245
+ finish = choice.finish_reason ?? finish
246
+ }
247
+ yield { type: 'done', response: this.response(text, calls, finish) }
248
+ }
249
+ }