@yaks/anthropic 0.0.0-stage → 0.2.36
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/LICENSE +202 -0
- package/README.md +114 -2
- package/_dist/batches.d.ts +77 -0
- package/_dist/batches.d.ts.map +1 -0
- package/_dist/mark.d.ts +6 -0
- package/_dist/mark.d.ts.map +1 -0
- package/_dist/mod.d.ts +63 -0
- package/_dist/mod.d.ts.map +1 -0
- package/_dist/provider.d.ts +8 -0
- package/_dist/provider.d.ts.map +1 -0
- package/_dist/reads.d.ts +2 -0
- package/_dist/reads.d.ts.map +1 -0
- package/_dist/vocab.d.ts +6 -0
- package/_dist/vocab.d.ts.map +1 -0
- package/_dist/wire.d.ts +94 -0
- package/_dist/wire.d.ts.map +1 -0
- package/batches.js +110 -0
- package/batches.js.map +1 -0
- package/batches.ts +136 -0
- package/deno.json +1 -0
- package/mark.js +16 -0
- package/mark.js.map +1 -0
- package/mark.ts +18 -0
- package/mod.js +546 -0
- package/mod.js.map +1 -0
- package/mod.ts +523 -0
- package/package.json +38 -4
- package/provider.js +37 -0
- package/provider.js.map +1 -0
- package/provider.ts +58 -0
- package/reads.js +18 -0
- package/reads.js.map +1 -0
- package/reads.ts +19 -0
- package/vocab.js +16 -0
- package/vocab.js.map +1 -0
- package/vocab.json +24 -0
- package/vocab.ts +17 -0
- package/web.js +48 -0
- package/web.js.map +1 -0
- package/web.ts +44 -0
- package/wire.js +136 -0
- package/wire.js.map +1 -0
- package/wire.ts +266 -0
package/mod.ts
ADDED
|
@@ -0,0 +1,523 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @yaks/anthropic implements @yaks/model's {@link Model} over Anthropic's
|
|
3
|
+
* Messages API, spoken over fetch. Every request streams: output text
|
|
4
|
+
* reaches `onText` as it is written, `signal` stops the request, and tool
|
|
5
|
+
* calls come back as `call` items for the caller to run.
|
|
6
|
+
*
|
|
7
|
+
* ```ts
|
|
8
|
+
* import { messages } from '@yaks/anthropic'
|
|
9
|
+
*
|
|
10
|
+
* let model = messages({ key: () => 'the key, from the vault' })
|
|
11
|
+
* // let reply = await model({
|
|
12
|
+
* // model: 'claude-sonnet-5-5',
|
|
13
|
+
* // items: [{ kind: 'user', text: 'Hello' }],
|
|
14
|
+
* // tools: [],
|
|
15
|
+
* // })
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* The API keeps nothing between requests, so every request carries the whole
|
|
19
|
+
* conversation, and automatic prompt caching (`cache_control` on the request)
|
|
20
|
+
* reads the prefix the last request wrote. Thinking blocks are not carried
|
|
21
|
+
* back: the API answers a history without them, and the reasoning is private.
|
|
22
|
+
*
|
|
23
|
+
* @module
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import {
|
|
27
|
+
acknowledged,
|
|
28
|
+
began,
|
|
29
|
+
type Item,
|
|
30
|
+
type Listed,
|
|
31
|
+
listPrice,
|
|
32
|
+
message,
|
|
33
|
+
type Model,
|
|
34
|
+
ModelError,
|
|
35
|
+
type Request,
|
|
36
|
+
submitted,
|
|
37
|
+
type Tool,
|
|
38
|
+
type Usage,
|
|
39
|
+
} from '@yaks/model'
|
|
40
|
+
import { stallMs, watched } from '@yaks/model/stall'
|
|
41
|
+
import { type Scope, sharing } from '@yaks/fp'
|
|
42
|
+
import { anthropicDoc } from './vocab.js'
|
|
43
|
+
import { mark } from './mark.js'
|
|
44
|
+
import { READS } from './reads.js'
|
|
45
|
+
import { HOSTED, web } from './web.js'
|
|
46
|
+
import {
|
|
47
|
+
type ApiUsage,
|
|
48
|
+
type Block,
|
|
49
|
+
built,
|
|
50
|
+
type CacheControl,
|
|
51
|
+
type Citation,
|
|
52
|
+
type Content,
|
|
53
|
+
events,
|
|
54
|
+
failure,
|
|
55
|
+
type HostedParam,
|
|
56
|
+
type Message,
|
|
57
|
+
type ModelInfo,
|
|
58
|
+
type Page,
|
|
59
|
+
type Param,
|
|
60
|
+
send,
|
|
61
|
+
type ToolParam,
|
|
62
|
+
type ToolSystem,
|
|
63
|
+
} from './wire.js'
|
|
64
|
+
|
|
65
|
+
export { anthropicDoc, failure, mark, READS }
|
|
66
|
+
|
|
67
|
+
export type Options = {
|
|
68
|
+
/** Obtain an Anthropic API key at the moment of the call. */
|
|
69
|
+
key: () => string | Promise<string>
|
|
70
|
+
fetch?: typeof fetch
|
|
71
|
+
/** The API's root, `https://api.anthropic.com` by default. */
|
|
72
|
+
base?: string
|
|
73
|
+
/** Offer the API's own web search and page fetch. */
|
|
74
|
+
web?: boolean
|
|
75
|
+
/** who may share a read under way (@yaks/model `Lent.scope`) */
|
|
76
|
+
scope?: Scope
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// A reply's ceiling where the request names none: streamed, so no timeout.
|
|
80
|
+
let TOKENS = 64_000
|
|
81
|
+
let EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max']
|
|
82
|
+
|
|
83
|
+
/** Where the conversation begins: at its first item that is no instruction.
|
|
84
|
+
* Every instruction before it opens the system prompt, whatever follows, so a
|
|
85
|
+
* checkpoint's summary stays where the last request sent it and the cached
|
|
86
|
+
* prefix holds. */
|
|
87
|
+
let leadOf = (req: Request) => {
|
|
88
|
+
let lead = req.items.findIndex((i) => i.kind != 'instruction')
|
|
89
|
+
return lead < 0 ? req.items.length : lead
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The turn a conversation opens with where it opens with none of the
|
|
93
|
+
* person's (a checkpoint that summarized every line, then its replies), since
|
|
94
|
+
* the API takes a conversation only from a user message. It is the same each
|
|
95
|
+
* request, so the next request's prefix is this one's. */
|
|
96
|
+
export let OPENER: string = message(
|
|
97
|
+
{ kind: 'user', text: 'Continue from the instructions above.' },
|
|
98
|
+
'the system',
|
|
99
|
+
).text
|
|
100
|
+
|
|
101
|
+
/** Instructions open the system prompt; one met later in the conversation is
|
|
102
|
+
* said as text in the turn it falls in, which every model accepts. */
|
|
103
|
+
export let system = (req: Request): string | undefined => {
|
|
104
|
+
let said = req.items.slice(0, leadOf(req))
|
|
105
|
+
.map((i) => (i as { text: string }).text)
|
|
106
|
+
let text = [req.instructions, ...said].filter(Boolean).join('\n\n')
|
|
107
|
+
return text || undefined
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
let blocks = (i: Item): ['user' | 'assistant', Block[]] | undefined => {
|
|
111
|
+
switch (i.kind) {
|
|
112
|
+
case 'user':
|
|
113
|
+
case 'instruction':
|
|
114
|
+
return i.text ? ['user', [{ type: 'text', text: i.text }]] : undefined
|
|
115
|
+
case 'assistant':
|
|
116
|
+
return i.text
|
|
117
|
+
? ['assistant', [{ type: 'text', text: i.text }]]
|
|
118
|
+
: undefined
|
|
119
|
+
// Named first, so Claude knows which file it is looking at.
|
|
120
|
+
case 'image':
|
|
121
|
+
case 'document': {
|
|
122
|
+
let source = { type: 'base64' as const, data: base64(i.bytes) }
|
|
123
|
+
return ['user', [
|
|
124
|
+
...i.label ? [{ type: 'text' as const, text: i.label }] : [],
|
|
125
|
+
i.kind == 'image'
|
|
126
|
+
? { type: 'image', source: { ...source, media_type: i.mediaType } }
|
|
127
|
+
: {
|
|
128
|
+
type: 'document',
|
|
129
|
+
...i.filename ? { title: i.filename } : {},
|
|
130
|
+
source: i.mediaType == 'text/plain'
|
|
131
|
+
? {
|
|
132
|
+
type: 'text',
|
|
133
|
+
media_type: 'text/plain',
|
|
134
|
+
data: new TextDecoder().decode(i.bytes),
|
|
135
|
+
}
|
|
136
|
+
: { ...source, media_type: i.mediaType },
|
|
137
|
+
},
|
|
138
|
+
]]
|
|
139
|
+
}
|
|
140
|
+
case 'call':
|
|
141
|
+
return ['assistant', [{
|
|
142
|
+
type: 'tool_use',
|
|
143
|
+
id: i.id,
|
|
144
|
+
name: i.name,
|
|
145
|
+
input: parsed(i.args),
|
|
146
|
+
}]]
|
|
147
|
+
case 'result':
|
|
148
|
+
return ['user', [{
|
|
149
|
+
type: 'tool_result',
|
|
150
|
+
tool_use_id: i.id,
|
|
151
|
+
content: i.output,
|
|
152
|
+
}]]
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** The conversation as messages: consecutive blocks of one role share a
|
|
157
|
+
* message, so a turn's tool results answer together. The API takes a
|
|
158
|
+
* message's tool results before anything else in it, so a result placed after
|
|
159
|
+
* an image shown beside an earlier one joins the results ahead of it. */
|
|
160
|
+
export let conversation = (req: Request, rolling?: CacheControl): Param[] => {
|
|
161
|
+
let out: Param[] = []
|
|
162
|
+
let items = [...req.items, ...req.turnContext ?? []]
|
|
163
|
+
let boundary = req.items.length
|
|
164
|
+
for (let at = leadOf(req); at < items.length; at++) {
|
|
165
|
+
if (rolling && at == boundary) {
|
|
166
|
+
let last = out.at(-1)?.content.at(-1)
|
|
167
|
+
if (last) last.cache_control = rolling
|
|
168
|
+
}
|
|
169
|
+
let i = items[at]
|
|
170
|
+
let b = blocks(i)
|
|
171
|
+
if (!b) continue
|
|
172
|
+
let [role, content] = b
|
|
173
|
+
let last = out.at(-1)
|
|
174
|
+
if (last?.role != role) out.push({ role, content })
|
|
175
|
+
else if (i.kind != 'result') last.content.push(...content)
|
|
176
|
+
else {
|
|
177
|
+
let at = last.content.findIndex((c) => c.type != 'tool_result')
|
|
178
|
+
last.content.splice(at < 0 ? last.content.length : at, 0, ...content)
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (out[0]?.role != 'user') {
|
|
182
|
+
out.unshift({ role: 'user', content: [{ type: 'text', text: OPENER }] })
|
|
183
|
+
}
|
|
184
|
+
return out
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Whether a request keeps its cached prefix the hour Anthropic offers
|
|
188
|
+
* beside its default five minutes, at a dearer write. */
|
|
189
|
+
let hour = (req: Request) => (req.cacheRetention ?? 0) >= 3600
|
|
190
|
+
|
|
191
|
+
let caching = (req: Request) => {
|
|
192
|
+
let rolling: CacheControl = {
|
|
193
|
+
type: 'ephemeral',
|
|
194
|
+
...hour(req) ? { ttl: '1h' } : {},
|
|
195
|
+
}
|
|
196
|
+
let prefix = req.cachePrefix
|
|
197
|
+
if (!prefix || !req.instructions) {
|
|
198
|
+
return {
|
|
199
|
+
cache_control: rolling,
|
|
200
|
+
system: system(req),
|
|
201
|
+
messages: conversation(req),
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
let shared: CacheControl = {
|
|
205
|
+
type: 'ephemeral',
|
|
206
|
+
...prefix.retention >= 3600 || hour(req) ? { ttl: '1h' } : {},
|
|
207
|
+
}
|
|
208
|
+
let rest = system({
|
|
209
|
+
...req,
|
|
210
|
+
instructions: req.instructions.slice(prefix.length),
|
|
211
|
+
})
|
|
212
|
+
return {
|
|
213
|
+
...req.turnContext?.length ? {} : { cache_control: rolling },
|
|
214
|
+
system: [
|
|
215
|
+
{
|
|
216
|
+
type: 'text',
|
|
217
|
+
text: req.instructions.slice(0, prefix.length),
|
|
218
|
+
cache_control: shared,
|
|
219
|
+
},
|
|
220
|
+
...rest ? [{ type: 'text', text: rest }] : [],
|
|
221
|
+
],
|
|
222
|
+
messages: conversation(req, rolling),
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Tools in name order, so the cached prefix is the same each request. */
|
|
227
|
+
export let tools = (list: Tool[]): ToolParam[] =>
|
|
228
|
+
[...list].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)
|
|
229
|
+
.map((t) => ({
|
|
230
|
+
name: t.name,
|
|
231
|
+
description: t.description,
|
|
232
|
+
input_schema: { type: 'object', ...t.parameters },
|
|
233
|
+
}))
|
|
234
|
+
|
|
235
|
+
/** Anthropic counts cache reads and writes beside `input_tokens`; here they
|
|
236
|
+
* are parts of it. */
|
|
237
|
+
export let usage = (u: ApiUsage): Usage => {
|
|
238
|
+
let read = u.cache_read_input_tokens ?? 0
|
|
239
|
+
let wrote = u.cache_creation_input_tokens ?? 0
|
|
240
|
+
let hour = u.cache_creation?.ephemeral_1h_input_tokens
|
|
241
|
+
let searched = u.server_tool_use?.web_search_requests
|
|
242
|
+
return {
|
|
243
|
+
input_tokens: (u.input_tokens ?? 0) + read + wrote,
|
|
244
|
+
output_tokens: u.output_tokens,
|
|
245
|
+
cached_tokens: read,
|
|
246
|
+
cache_write_tokens: wrote,
|
|
247
|
+
...hour ? { cache_write_1h_tokens: hour } : {},
|
|
248
|
+
...searched ? { web_searches: searched } : {},
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
let page = (url?: string) => {
|
|
253
|
+
try {
|
|
254
|
+
let u = new URL(url ?? '')
|
|
255
|
+
return u.protocol == 'https:' || u.protocol == 'http:' ? u : undefined
|
|
256
|
+
} catch {
|
|
257
|
+
return undefined
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** A link to each page cited that the text has not linked yet, nor `text`
|
|
262
|
+
* holds, by its title or else its host. */
|
|
263
|
+
let sources = (cited: Citation[] = [], linked: Set<string>, text: string) =>
|
|
264
|
+
cited.map((c) => {
|
|
265
|
+
let url = page(c.url)
|
|
266
|
+
if (!url || linked.has(url.href) || text.includes(url.href)) return ''
|
|
267
|
+
linked.add(url.href)
|
|
268
|
+
let title = (c.title ?? '').replace(/[\[\]\\\r\n]/g, ' ').trim() ||
|
|
269
|
+
url.hostname
|
|
270
|
+
return ` [${title}](<${url.href.replaceAll('>', '%3E')}>)`
|
|
271
|
+
}).join('')
|
|
272
|
+
|
|
273
|
+
/** A reply's items in the order the model wrote them. Text runs on across the
|
|
274
|
+
* blocks its citations split it into and the searches and fetches the API ran
|
|
275
|
+
* within it, and each web page it cites is linked after the text citing it.
|
|
276
|
+
* A call's arguments are its input, or the text of an input cut short. */
|
|
277
|
+
export let items = (content: Content[]): Item[] => {
|
|
278
|
+
let out: Item[] = []
|
|
279
|
+
let linked = new Set<string>()
|
|
280
|
+
let ran = false
|
|
281
|
+
for (let b of content) {
|
|
282
|
+
if (b.type == 'tool_use') {
|
|
283
|
+
out.push({
|
|
284
|
+
kind: 'call',
|
|
285
|
+
id: b.id!,
|
|
286
|
+
name: b.name!,
|
|
287
|
+
args: b.json ?? JSON.stringify(b.input ?? {}),
|
|
288
|
+
})
|
|
289
|
+
} else if (b.type == 'text') {
|
|
290
|
+
let last = out.at(-1)
|
|
291
|
+
if (last?.kind != 'assistant') linked = new Set()
|
|
292
|
+
let said = (last?.kind == 'assistant' ? last.text : '') + (b.text ?? '')
|
|
293
|
+
let text = (b.text ?? '') + sources(b.citations, linked, said)
|
|
294
|
+
if (!text) continue
|
|
295
|
+
if (last?.kind == 'assistant') last.text += (ran ? '\n\n' : '') + text
|
|
296
|
+
else out.push({ kind: 'assistant', text })
|
|
297
|
+
}
|
|
298
|
+
ran = b.type != 'text'
|
|
299
|
+
}
|
|
300
|
+
return out
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** What a reply's thinking blocks said, one paragraph a block, or nothing
|
|
304
|
+
* where it thought nothing it shows. */
|
|
305
|
+
export let thought = (content: Content[]): string | undefined =>
|
|
306
|
+
content.filter((b) => b.type == 'thinking').map((b) => b.thinking?.trim())
|
|
307
|
+
.filter(Boolean).join('\n\n') || undefined
|
|
308
|
+
|
|
309
|
+
/** A model as the API lists it, at the price @yaks/model's list has for its
|
|
310
|
+
* name: the API says no price. */
|
|
311
|
+
export let listed = (m: ModelInfo): Listed => {
|
|
312
|
+
let price = listPrice(m.id)
|
|
313
|
+
return {
|
|
314
|
+
name: m.id,
|
|
315
|
+
label: m.display_name,
|
|
316
|
+
...m.max_input_tokens ? { context: m.max_input_tokens } : {},
|
|
317
|
+
...m.max_tokens ? { output: m.max_tokens } : {},
|
|
318
|
+
modalities: ['text'],
|
|
319
|
+
...price ? { price } : {},
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
let ended = () =>
|
|
324
|
+
new ModelError('busy', 'the stream ended before its message did', {})
|
|
325
|
+
|
|
326
|
+
/** The message a reply's stream builds, told as it is written: its first
|
|
327
|
+
* event acknowledges the request, any block (text, thinking or a tool call)
|
|
328
|
+
* is the reply's output beginning, and text reaches `onText` at its place
|
|
329
|
+
* among the reply's assistant items. A stream that ends before its message
|
|
330
|
+
* does was dropped. */
|
|
331
|
+
let read = async (req: Request, response: Response): Promise<Message> => {
|
|
332
|
+
if (!response.body) throw ended()
|
|
333
|
+
let message: Message | undefined
|
|
334
|
+
// Text runs on until a tool call, as the reply's items say it.
|
|
335
|
+
let ordinal = new Map<number, number>()
|
|
336
|
+
let said = -1
|
|
337
|
+
let prose = false
|
|
338
|
+
for await (let e of events(response.body)) {
|
|
339
|
+
if (e.type == 'message_start') {
|
|
340
|
+
message = { ...e.message!, content: [...e.message!.content] }
|
|
341
|
+
await acknowledged(req, { anthropic: { response_id: message.id } })
|
|
342
|
+
continue
|
|
343
|
+
}
|
|
344
|
+
if (!message) continue
|
|
345
|
+
if (e.type == 'message_stop') return message
|
|
346
|
+
message = built(message, e)
|
|
347
|
+
if (e.type == 'content_block_start') {
|
|
348
|
+
began(req)
|
|
349
|
+
let type = e.content_block?.type
|
|
350
|
+
if (type == 'text') {
|
|
351
|
+
if (!prose) said++
|
|
352
|
+
ordinal.set(e.index!, said)
|
|
353
|
+
prose = true
|
|
354
|
+
}
|
|
355
|
+
if (type == 'tool_use') prose = false
|
|
356
|
+
}
|
|
357
|
+
let text = e.delta?.type == 'text_delta' ? e.delta.text : undefined
|
|
358
|
+
if (text) req.onText?.({ index: ordinal.get(e.index!) ?? 0, text })
|
|
359
|
+
}
|
|
360
|
+
throw ended()
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** A model over the Messages API. Its `info` gives the context window the
|
|
364
|
+
* API lists and the price @yaks/model's list has for the name. Nothing is
|
|
365
|
+
* retried here: the caller retries, since a retry here could buy one request
|
|
366
|
+
* twice. */
|
|
367
|
+
export let messages = (options: Options): Model => {
|
|
368
|
+
let get = async <T>(path: string): Promise<T> =>
|
|
369
|
+
(await send(options, await options.key(), path)).json()
|
|
370
|
+
let known = new Map<string, Listed | undefined>()
|
|
371
|
+
let info = (name: string) =>
|
|
372
|
+
sharing(
|
|
373
|
+
known,
|
|
374
|
+
name,
|
|
375
|
+
() =>
|
|
376
|
+
get<ModelInfo>(`/v1/models/${encodeURIComponent(name)}`).then(listed)
|
|
377
|
+
.catch((e) => {
|
|
378
|
+
if (e instanceof ModelError && e.code == 'model') return undefined
|
|
379
|
+
throw e
|
|
380
|
+
}),
|
|
381
|
+
{ scope: options.scope },
|
|
382
|
+
)
|
|
383
|
+
let list = async () => {
|
|
384
|
+
let out: Listed[] = []
|
|
385
|
+
let after: string | null | undefined
|
|
386
|
+
do {
|
|
387
|
+
let page = await get<Page<ModelInfo>>(
|
|
388
|
+
`/v1/models${after ? `?after_id=${encodeURIComponent(after)}` : ''}`,
|
|
389
|
+
)
|
|
390
|
+
out.push(...page.data.map(listed))
|
|
391
|
+
after = page.has_more ? page.last_id : undefined
|
|
392
|
+
} while (after)
|
|
393
|
+
return out
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
let model: Model = async (req) => {
|
|
397
|
+
if (req.questions) {
|
|
398
|
+
throw new ModelError('questions', 'Claude answers no typed questions')
|
|
399
|
+
}
|
|
400
|
+
if (req.modalities?.some((m) => m != 'text')) {
|
|
401
|
+
throw new ModelError('modalities', 'Claude writes text only')
|
|
402
|
+
}
|
|
403
|
+
let key = await options.key()
|
|
404
|
+
let effort = req.effort && EFFORTS.includes(req.effort)
|
|
405
|
+
? req.effort
|
|
406
|
+
: undefined
|
|
407
|
+
let cached = caching(req)
|
|
408
|
+
let offered = tools(req.tools)
|
|
409
|
+
let shared = new Set(req.cachePrefix?.tools)
|
|
410
|
+
// Models that accept the inline-tools beta on the direct Claude API.
|
|
411
|
+
let inline = req.cachePrefix?.tools && !req.sites &&
|
|
412
|
+
/^claude-(?:opus-(?:4-8|5)|sonnet-5-5|haiku-5-5|fable-5|mythos-5)(?:-|$)/
|
|
413
|
+
.test(req.model)
|
|
414
|
+
let scoped = inline ? offered.filter((t) => !shared.has(t.name)) : []
|
|
415
|
+
let visible: (ToolParam | HostedParam)[] = [
|
|
416
|
+
...inline ? offered.filter((t) => shared.has(t.name)) : offered,
|
|
417
|
+
...options.web ? web(req.model, req.sites) : [],
|
|
418
|
+
]
|
|
419
|
+
let additions: ToolSystem = {
|
|
420
|
+
role: 'system',
|
|
421
|
+
content: scoped.map((definition) => ({
|
|
422
|
+
type: 'tool_addition',
|
|
423
|
+
tool: { type: 'tool_definition', definition },
|
|
424
|
+
})),
|
|
425
|
+
}
|
|
426
|
+
let [first, ...history] = cached.messages
|
|
427
|
+
let tail: Block[] = []
|
|
428
|
+
if (
|
|
429
|
+
scoped.length && !history.length &&
|
|
430
|
+
req.turnContext?.every((i) => i.kind == 'instruction')
|
|
431
|
+
) {
|
|
432
|
+
let count = req.turnContext.filter((i) => i.text).length
|
|
433
|
+
if (count && count < first.content.length) {
|
|
434
|
+
tail = first.content.splice(-count)
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
let body = {
|
|
438
|
+
model: req.model,
|
|
439
|
+
max_tokens: req.tokens ?? TOKENS,
|
|
440
|
+
...cached,
|
|
441
|
+
...scoped.length
|
|
442
|
+
? {
|
|
443
|
+
messages: [
|
|
444
|
+
first,
|
|
445
|
+
additions,
|
|
446
|
+
...history,
|
|
447
|
+
...tail.length ? [{ role: 'system', content: tail }] : [],
|
|
448
|
+
],
|
|
449
|
+
}
|
|
450
|
+
: {},
|
|
451
|
+
...visible.length ? { tools: visible } : {},
|
|
452
|
+
...effort ? { output_config: { effort } } : {},
|
|
453
|
+
stream: true,
|
|
454
|
+
}
|
|
455
|
+
let started = Date.now()
|
|
456
|
+
await submitted(req)
|
|
457
|
+
// The reply streams through a fetch that fails once it goes quiet.
|
|
458
|
+
let watching = {
|
|
459
|
+
...options,
|
|
460
|
+
fetch: watched(options.fetch ?? fetch, stallMs(req)),
|
|
461
|
+
}
|
|
462
|
+
let message = await send(watching, key, '/v1/messages', {
|
|
463
|
+
method: 'POST',
|
|
464
|
+
...scoped.length
|
|
465
|
+
? { headers: { 'anthropic-beta': 'inline-tools-2026-09-15' } }
|
|
466
|
+
: {},
|
|
467
|
+
body: JSON.stringify(body),
|
|
468
|
+
signal: req.signal,
|
|
469
|
+
}).then((r) => read(req, r)).catch((e) => {
|
|
470
|
+
// A stop the caller asked for is thrown on as it came.
|
|
471
|
+
req.signal?.throwIfAborted()
|
|
472
|
+
throw e
|
|
473
|
+
})
|
|
474
|
+
if (message.stop_reason == 'refusal') {
|
|
475
|
+
throw new ModelError(
|
|
476
|
+
'refusal',
|
|
477
|
+
message.stop_details?.explanation ?? 'Claude declined this request',
|
|
478
|
+
)
|
|
479
|
+
}
|
|
480
|
+
// Only a reply stopped at its output limit leaves a call's input unended.
|
|
481
|
+
let cut = message.stop_reason == 'max_tokens'
|
|
482
|
+
if (!cut && message.content.some((b) => b.json != null)) {
|
|
483
|
+
throw new ModelError('malformed_stream', 'a tool call input is not JSON')
|
|
484
|
+
}
|
|
485
|
+
let thinking = thought(message.content)
|
|
486
|
+
return {
|
|
487
|
+
id: message.id,
|
|
488
|
+
model: message.model,
|
|
489
|
+
items: items(message.content),
|
|
490
|
+
...thinking ? { thought: thinking } : {},
|
|
491
|
+
...cut ? { cut } : {},
|
|
492
|
+
usage: usage(message.usage),
|
|
493
|
+
cacheExpiresAt: new Date(started + (hour(req) ? 3600 : 300) * 1000)
|
|
494
|
+
.toISOString(),
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
return Object.assign(model, {
|
|
498
|
+
reads: READS,
|
|
499
|
+
info,
|
|
500
|
+
list,
|
|
501
|
+
vocab: anthropicDoc,
|
|
502
|
+
mark,
|
|
503
|
+
anchor: () => undefined,
|
|
504
|
+
...options.web ? { hosted: HOSTED } : {},
|
|
505
|
+
})
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
let parsed = (args: string): unknown => {
|
|
509
|
+
try {
|
|
510
|
+
let v = JSON.parse(args || '{}')
|
|
511
|
+
return v && typeof v == 'object' ? v : {}
|
|
512
|
+
} catch {
|
|
513
|
+
return {}
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
let base64 = (bytes: Uint8Array) => {
|
|
518
|
+
let s = ''
|
|
519
|
+
for (let i = 0; i < bytes.length; i += 0x8000) {
|
|
520
|
+
s += String.fromCharCode(...bytes.subarray(i, i + 0x8000))
|
|
521
|
+
}
|
|
522
|
+
return btoa(s)
|
|
523
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,40 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yaks/anthropic",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.36",
|
|
4
|
+
"homepage": "https://jsr.io/@yaks/anthropic",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./_dist/mod.d.ts",
|
|
9
|
+
"default": "./mod.js"
|
|
10
|
+
},
|
|
11
|
+
"./vocab": {
|
|
12
|
+
"types": "./_dist/vocab.d.ts",
|
|
13
|
+
"default": "./vocab.js"
|
|
14
|
+
},
|
|
15
|
+
"./mark": {
|
|
16
|
+
"types": "./_dist/mark.d.ts",
|
|
17
|
+
"default": "./mark.js"
|
|
18
|
+
},
|
|
19
|
+
"./reads": {
|
|
20
|
+
"types": "./_dist/reads.d.ts",
|
|
21
|
+
"default": "./reads.js"
|
|
22
|
+
},
|
|
23
|
+
"./provider": {
|
|
24
|
+
"types": "./_dist/provider.d.ts",
|
|
25
|
+
"default": "./provider.js"
|
|
26
|
+
},
|
|
27
|
+
"./batches": {
|
|
28
|
+
"types": "./_dist/batches.d.ts",
|
|
29
|
+
"default": "./batches.js"
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"license": "Apache-2.0",
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"@yaks/fp": "0.2.36",
|
|
35
|
+
"@yaks/model": "0.2.36",
|
|
36
|
+
"@yaks/vocab": "0.2.36"
|
|
37
|
+
},
|
|
38
|
+
"description": "Implements the model interface over Anthropic's Messages API, spoken over fetch: streamed text, tool use, automatic prompt caching and cancellation, with usage that names what the cache read and wrote.",
|
|
39
|
+
"repository": "https://github.com/yak-sh/yak.git"
|
|
40
|
+
}
|
package/provider.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// @yaks/anthropic as a provider a config names (@yaks/model `ProviderFacet`):
|
|
2
|
+
// `anthropic`, on the key the person pasted with `yak auth anthropic`, or the
|
|
3
|
+
// one its options name (`key`), read at each call, searching and fetching the
|
|
4
|
+
// web with the API's own tools unless its options or `HARNESS_WEB=0` turn them
|
|
5
|
+
// off. The model (./mod.ts) loads on the first ask; a reply is marked without
|
|
6
|
+
// it (./mark.ts).
|
|
7
|
+
import { deferredModel, ModelError } from "@yaks/model";
|
|
8
|
+
import { mark } from "./mark.js";
|
|
9
|
+
import { READS } from "./reads.js";
|
|
10
|
+
import { anthropicDoc } from "./vocab.js";
|
|
11
|
+
import { HOSTED } from "./web.js";
|
|
12
|
+
/** `anthropic`, over the host's connections and its key. */ export let providers = (lent, options = {})=>{
|
|
13
|
+
let web = options.web ?? lent.env('HARNESS_WEB') != '0';
|
|
14
|
+
return {
|
|
15
|
+
anthropic: deferredModel(()=>import("./mod.js").then(({ messages })=>messages({
|
|
16
|
+
fetch: lent.fetch,
|
|
17
|
+
key: async ()=>{
|
|
18
|
+
let key = options.key ?? await lent.key('anthropic');
|
|
19
|
+
if (!key) {
|
|
20
|
+
throw new ModelError('no_credential', 'Anthropic is not connected. Run yak auth anthropic.');
|
|
21
|
+
}
|
|
22
|
+
return key;
|
|
23
|
+
},
|
|
24
|
+
web,
|
|
25
|
+
scope: lent.scope
|
|
26
|
+
})), {
|
|
27
|
+
vocab: anthropicDoc,
|
|
28
|
+
info: true,
|
|
29
|
+
mark,
|
|
30
|
+
reads: READS,
|
|
31
|
+
...web ? {
|
|
32
|
+
hosted: HOSTED
|
|
33
|
+
} : {}
|
|
34
|
+
})
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
//# sourceMappingURL=provider.js.map
|
package/provider.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.js","sources":["./provider.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,8EAA8E;AAC9E,8EAA8E;AAC9E,+EAA+E;AAC/E,8EAA8E;AAC9E,kBAAkB;AAElB,SAAS,aAAa,EAAyB,UAAU,2BAAgC;AACzF,SAAS,IAAI,oBAAmB;AAChC,SAAS,KAAK,qBAAoB;AAClC,SAAS,YAAY,qBAAoB;AACzC,SAAS,MAAM,mBAAkB;AAWjC,0DAA0D,GAC1D,OAAO,IAAI,YAAY,CACrB,MACA,UAAmB,CAAC,CAAC;EAErB,IAAI,MAAM,QAAQ,GAAG,IAAI,KAAK,GAAG,CAAC,kBAAkB;EACpD,OAAO;IACL,WAAW,cACT,IACE,MAAM,CAAC,YAAY,IAAI,CAAC,CAAC,EAAE,QAAQ,EAAE,GACnC,SAAS;UACP,OAAO,KAAK,KAAK;UACjB,KAAK;YACH,IAAI,MAAM,QAAQ,GAAG,IAAI,MAAM,KAAK,GAAG,CAAC;YACxC,IAAI,CAAC,KAAK;cACR,MAAM,IAAI,WACR,iBACA;YAEJ;YACA,OAAO;UACT;UACA;UACA,OAAO,KAAK,KAAK;QACnB,KAEJ;MACE,OAAO;MACP,MAAM;MACN;MACA,OAAO;MACP,GAAG,MAAM;QAAE,QAAQ;MAAO,IAAI,CAAC,CAAC;IAClC;EAEJ;AACF,EAAC"}
|
package/provider.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// @yaks/anthropic as a provider a config names (@yaks/model `ProviderFacet`):
|
|
2
|
+
// `anthropic`, on the key the person pasted with `yak auth anthropic`, or the
|
|
3
|
+
// one its options name (`key`), read at each call, searching and fetching the
|
|
4
|
+
// web with the API's own tools unless its options or `HARNESS_WEB=0` turn them
|
|
5
|
+
// off. The model (./mod.ts) loads on the first ask; a reply is marked without
|
|
6
|
+
// it (./mark.ts).
|
|
7
|
+
|
|
8
|
+
import { deferredModel, type Lent, type Model, ModelError } from '@yaks/model'
|
|
9
|
+
import { mark } from './mark.js'
|
|
10
|
+
import { READS } from './reads.js'
|
|
11
|
+
import { anthropicDoc } from './vocab.js'
|
|
12
|
+
import { HOSTED } from './web.js'
|
|
13
|
+
|
|
14
|
+
/** The plugin's options in a config. */
|
|
15
|
+
export type Options = {
|
|
16
|
+
/** the API key to call with, instead of the person's */
|
|
17
|
+
key?: string
|
|
18
|
+
/** offer the API's web search and page fetch (default on, unless
|
|
19
|
+
* `HARNESS_WEB=0`) */
|
|
20
|
+
web?: boolean
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** `anthropic`, over the host's connections and its key. */
|
|
24
|
+
export let providers = (
|
|
25
|
+
lent: Lent,
|
|
26
|
+
options: Options = {},
|
|
27
|
+
): Record<string, Model> => {
|
|
28
|
+
let web = options.web ?? lent.env('HARNESS_WEB') != '0'
|
|
29
|
+
return {
|
|
30
|
+
anthropic: deferredModel(
|
|
31
|
+
() =>
|
|
32
|
+
import('./mod.js').then(({ messages }) =>
|
|
33
|
+
messages({
|
|
34
|
+
fetch: lent.fetch,
|
|
35
|
+
key: async () => {
|
|
36
|
+
let key = options.key ?? await lent.key('anthropic')
|
|
37
|
+
if (!key) {
|
|
38
|
+
throw new ModelError(
|
|
39
|
+
'no_credential',
|
|
40
|
+
'Anthropic is not connected. Run yak auth anthropic.',
|
|
41
|
+
)
|
|
42
|
+
}
|
|
43
|
+
return key
|
|
44
|
+
},
|
|
45
|
+
web,
|
|
46
|
+
scope: lent.scope,
|
|
47
|
+
})
|
|
48
|
+
),
|
|
49
|
+
{
|
|
50
|
+
vocab: anthropicDoc,
|
|
51
|
+
info: true,
|
|
52
|
+
mark,
|
|
53
|
+
reads: READS,
|
|
54
|
+
...web ? { hosted: HOSTED } : {},
|
|
55
|
+
},
|
|
56
|
+
),
|
|
57
|
+
}
|
|
58
|
+
}
|
package/reads.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// What Claude reads as it is, beside text, importable without the model
|
|
2
|
+
// (./mod.ts): a host that loads the model lazily still knows what to hand it.
|
|
3
|
+
// https://platform.claude.com/docs/en/build-with-claude/vision
|
|
4
|
+
// https://platform.claude.com/docs/en/build-with-claude/pdf-support
|
|
5
|
+
// https://platform.claude.com/docs/en/build-with-claude/files
|
|
6
|
+
// First-party API: images are at most 10 MB base64; whole requests 128 MB.
|
|
7
|
+
// PDFs also have a request-wide page cap: 600, or 100 below 1M context tokens.
|
|
8
|
+
// Plain text is the only other native document type; office formats require
|
|
9
|
+
// conversion or code execution and are not document inputs.
|
|
10
|
+
/** Native MIME types and raw-byte ceilings, before other request content. */ export let READS = {
|
|
11
|
+
'image/png': 7.5 * 1024 * 1024,
|
|
12
|
+
'image/jpeg': 7.5 * 1024 * 1024,
|
|
13
|
+
'image/gif': 7.5 * 1024 * 1024,
|
|
14
|
+
'image/webp': 7.5 * 1024 * 1024,
|
|
15
|
+
'application/pdf': 96 * 1024 * 1024,
|
|
16
|
+
'text/plain': 128 * 1024 * 1024
|
|
17
|
+
};
|
|
18
|
+
//# sourceMappingURL=reads.js.map
|
package/reads.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reads.js","sources":["./reads.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,8EAA8E;AAE9E,+DAA+D;AAC/D,oEAAoE;AACpE,8DAA8D;AAC9D,2EAA2E;AAC3E,+EAA+E;AAC/E,4EAA4E;AAC5E,4DAA4D;AAC5D,2EAA2E,GAC3E,OAAO,IAAI,QAAgC;EACzC,aAAa,MAAM,OAAO;EAC1B,cAAc,MAAM,OAAO;EAC3B,aAAa,MAAM,OAAO;EAC1B,cAAc,MAAM,OAAO;EAC3B,mBAAmB,KAAK,OAAO;EAC/B,cAAc,MAAM,OAAO;AAC7B,EAAC"}
|