@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/batches.js ADDED
@@ -0,0 +1,110 @@
1
+ // Anthropic's Message Batches API as @yaks/model's `Batches`, spoken over the
2
+ // same wire as ./mod.ts: many Messages requests sent as one, answered within a
3
+ // day at half the price. Each request's system text is marked for the cache,
4
+ // so a prefix every request shares is written once and read by the rest.
5
+ import { send } from "./wire.js";
6
+ /** A request as a Messages request's body, its system text cached. */ export let entryOf = (a)=>({
7
+ custom_id: a.id,
8
+ params: {
9
+ model: a.model,
10
+ max_tokens: a.max,
11
+ system: [
12
+ {
13
+ type: 'text',
14
+ text: a.system,
15
+ cache_control: {
16
+ type: 'ephemeral'
17
+ }
18
+ }
19
+ ],
20
+ messages: [
21
+ {
22
+ role: 'user',
23
+ content: a.text
24
+ }
25
+ ]
26
+ }
27
+ });
28
+ /**
29
+ * A result as an answer: its text and usage, counted as @yaks/model counts
30
+ * them (input includes what the cache read and wrote).
31
+ *
32
+ * ```ts
33
+ * import { answerOf } from '@yaks/anthropic/batches'
34
+ * import { assertEquals } from '@std/assert'
35
+ *
36
+ * assertEquals(answerOf({
37
+ * custom_id: 'a',
38
+ * result: {
39
+ * type: 'succeeded',
40
+ * message: {
41
+ * content: [{ type: 'text', text: 'hi' }],
42
+ * usage: { input_tokens: 10, output_tokens: 5, cache_read_input_tokens: 90 },
43
+ * },
44
+ * },
45
+ * }), {
46
+ * id: 'a',
47
+ * text: 'hi',
48
+ * usage: { input_tokens: 100, cached_tokens: 90, cache_write_tokens: 0, output_tokens: 5 },
49
+ * })
50
+ * assertEquals(answerOf({ custom_id: 'b', result: { type: 'expired' } }), {
51
+ * id: 'b',
52
+ * error: 'expired',
53
+ * })
54
+ * ```
55
+ */ export let answerOf = (r)=>{
56
+ if (r.result.type != 'succeeded') {
57
+ let why = r.result.error ? ` ${JSON.stringify(r.result.error)}` : '';
58
+ return {
59
+ id: r.custom_id,
60
+ error: r.result.type + why
61
+ };
62
+ }
63
+ let u = r.result.message.usage;
64
+ let read = u.cache_read_input_tokens ?? 0;
65
+ let wrote = u.cache_creation_input_tokens ?? 0;
66
+ let usage = {
67
+ input_tokens: u.input_tokens + read + wrote,
68
+ cached_tokens: read,
69
+ cache_write_tokens: wrote,
70
+ output_tokens: u.output_tokens
71
+ };
72
+ let text = r.result.message.content.filter((b)=>b.type == 'text').map((b)=>b.text ?? '').join('');
73
+ return {
74
+ id: r.custom_id,
75
+ text,
76
+ usage
77
+ };
78
+ };
79
+ /** The batches of one key.
80
+ *
81
+ * ```ts
82
+ * import { batches } from '@yaks/anthropic/batches'
83
+ * import { assertEquals } from '@std/assert'
84
+ *
85
+ * let asked: string[] = []
86
+ * let fetch = (url: string | URL | Request, init?: RequestInit) => {
87
+ * asked.push(`${init?.method ?? 'GET'} ${url}`)
88
+ * return Promise.resolve(Response.json({ id: 'b1', processing_status: 'ended' }))
89
+ * }
90
+ * let api = batches({ fetch: fetch as typeof globalThis.fetch, key: () => 'k' })
91
+ * assertEquals(await api.ended('b1'), true)
92
+ * assertEquals(asked, ['GET https://api.anthropic.com/v1/messages/batches/b1'])
93
+ * ```
94
+ */ export let batches = (wire)=>{
95
+ let at = async (path, init)=>await send(wire, await wire.key(), `/v1/messages/batches${path}`, init);
96
+ let id = (s)=>`/${encodeURIComponent(s)}`;
97
+ let json = async (r)=>await r.json();
98
+ return {
99
+ submit: async (asked)=>(await json(await at('', {
100
+ method: 'POST',
101
+ body: JSON.stringify({
102
+ requests: asked.map(entryOf)
103
+ })
104
+ }))).id,
105
+ ended: async (b)=>(await json(await at(id(b)))).processing_status == 'ended',
106
+ // JSON lines, one result each.
107
+ results: async (b)=>(await (await at(`${id(b)}/results`)).text()).split('\n').filter((l)=>l.trim()).map((l)=>answerOf(JSON.parse(l)))
108
+ };
109
+ };
110
+ //# sourceMappingURL=batches.js.map
package/batches.js.map ADDED
@@ -0,0 +1 @@
1
+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E,SAAS;IAAE;IAAM;EAAM;AACxC,EAAC;AAED;;;;;;;;;;;;;;;CAeC,GACD,OAAO,IAAI,UAAU,CACnB;EAEA,IAAI,KAAK,OAAO,MAAc,OAC5B,MAAM,KAAK,MAAM,MAAM,KAAK,GAAG,IAAI,CAAC,oBAAoB,EAAE,MAAM,EAAE;EACpE,IAAI,KAAK,CAAC,IAAc,CAAC,CAAC,EAAE,mBAAmB,IAAI;EACnD,IAAI,OAAO,OAAU,IAAgB,MAAM,EAAE,IAAI;EACjD,OAAO;IACL,QAAQ,OAAO,QACb,CAAC,MAAM,KACL,MAAM,GAAG,IAAI;QACX,QAAQ;QACR,MAAM,KAAK,SAAS,CAAC;UAAE,UAAU,MAAM,GAAG,CAAC;QAAS;MACtD,GACD,EAAE,EAAE;IACP,OAAO,OAAO,IACZ,CAAC,MAAM,KAAoC,MAAM,GAAG,GAAG,IAAI,EACxD,iBAAiB,IAAI;IAC1B,+BAA+B;IAC/B,SAAS,OAAO,IACd,CAAC,MAAM,CAAC,MAAM,GAAG,GAAG,GAAG,GAAG,QAAQ,CAAC,CAAC,EAAE,IAAI,EAAE,EACzC,KAAK,CAAC,MACN,MAAM,CAAC,CAAC,IAAM,EAAE,IAAI,IACpB,GAAG,CAAC,CAAC,IAAM,SAAS,KAAK,KAAK,CAAC;EACtC;AACF,EAAC"}
package/batches.ts ADDED
@@ -0,0 +1,136 @@
1
+ // Anthropic's Message Batches API as @yaks/model's `Batches`, spoken over the
2
+ // same wire as ./mod.ts: many Messages requests sent as one, answered within a
3
+ // day at half the price. Each request's system text is marked for the cache,
4
+ // so a prefix every request shares is written once and read by the rest.
5
+ import type { Answered, Asked, Batches } from 'jsr:@yaks/model@0.2.36/batch'
6
+ import type { Usage } from 'jsr:@yaks/model@0.2.36'
7
+ import { send, type Wire } from './wire.js'
8
+
9
+ /** One request of a batch as the API takes it: a Messages request's body,
10
+ * named so its result can be found again. */
11
+ export type Entry = { custom_id: string; params: Record<string, unknown> }
12
+
13
+ /** One request's result as the API gives it: its message, or why there is
14
+ * none. */
15
+ export type Result = {
16
+ custom_id: string
17
+ result:
18
+ | {
19
+ type: 'succeeded'
20
+ message: {
21
+ content: { type: string; text?: string }[]
22
+ usage: {
23
+ input_tokens: number
24
+ output_tokens: number
25
+ cache_read_input_tokens?: number | null
26
+ cache_creation_input_tokens?: number | null
27
+ }
28
+ }
29
+ }
30
+ | { type: 'errored' | 'canceled' | 'expired'; error?: unknown }
31
+ }
32
+
33
+ /** A request as a Messages request's body, its system text cached. */
34
+ export let entryOf = (a: Asked): Entry => ({
35
+ custom_id: a.id,
36
+ params: {
37
+ model: a.model,
38
+ max_tokens: a.max,
39
+ system: [{
40
+ type: 'text',
41
+ text: a.system,
42
+ cache_control: { type: 'ephemeral' },
43
+ }],
44
+ messages: [{ role: 'user', content: a.text }],
45
+ },
46
+ })
47
+
48
+ /**
49
+ * A result as an answer: its text and usage, counted as @yaks/model counts
50
+ * them (input includes what the cache read and wrote).
51
+ *
52
+ * ```ts
53
+ * import { answerOf } from '@yaks/anthropic/batches'
54
+ * import { assertEquals } from '@std/assert'
55
+ *
56
+ * assertEquals(answerOf({
57
+ * custom_id: 'a',
58
+ * result: {
59
+ * type: 'succeeded',
60
+ * message: {
61
+ * content: [{ type: 'text', text: 'hi' }],
62
+ * usage: { input_tokens: 10, output_tokens: 5, cache_read_input_tokens: 90 },
63
+ * },
64
+ * },
65
+ * }), {
66
+ * id: 'a',
67
+ * text: 'hi',
68
+ * usage: { input_tokens: 100, cached_tokens: 90, cache_write_tokens: 0, output_tokens: 5 },
69
+ * })
70
+ * assertEquals(answerOf({ custom_id: 'b', result: { type: 'expired' } }), {
71
+ * id: 'b',
72
+ * error: 'expired',
73
+ * })
74
+ * ```
75
+ */
76
+ export let answerOf = (r: Result): Answered => {
77
+ if (r.result.type != 'succeeded') {
78
+ let why = r.result.error ? ` ${JSON.stringify(r.result.error)}` : ''
79
+ return { id: r.custom_id, error: r.result.type + why }
80
+ }
81
+ let u = r.result.message.usage
82
+ let read = u.cache_read_input_tokens ?? 0
83
+ let wrote = u.cache_creation_input_tokens ?? 0
84
+ let usage: Usage = {
85
+ input_tokens: u.input_tokens + read + wrote,
86
+ cached_tokens: read,
87
+ cache_write_tokens: wrote,
88
+ output_tokens: u.output_tokens,
89
+ }
90
+ let text = r.result.message.content.filter((b) => b.type == 'text')
91
+ .map((b) => b.text ?? '').join('')
92
+ return { id: r.custom_id, text, usage }
93
+ }
94
+
95
+ /** The batches of one key.
96
+ *
97
+ * ```ts
98
+ * import { batches } from '@yaks/anthropic/batches'
99
+ * import { assertEquals } from '@std/assert'
100
+ *
101
+ * let asked: string[] = []
102
+ * let fetch = (url: string | URL | Request, init?: RequestInit) => {
103
+ * asked.push(`${init?.method ?? 'GET'} ${url}`)
104
+ * return Promise.resolve(Response.json({ id: 'b1', processing_status: 'ended' }))
105
+ * }
106
+ * let api = batches({ fetch: fetch as typeof globalThis.fetch, key: () => 'k' })
107
+ * assertEquals(await api.ended('b1'), true)
108
+ * assertEquals(asked, ['GET https://api.anthropic.com/v1/messages/batches/b1'])
109
+ * ```
110
+ */
111
+ export let batches = (
112
+ wire: Wire & { key: () => string | Promise<string> },
113
+ ): Batches => {
114
+ let at = async (path: string, init?: RequestInit) =>
115
+ await send(wire, await wire.key(), `/v1/messages/batches${path}`, init)
116
+ let id = (s: string) => `/${encodeURIComponent(s)}`
117
+ let json = async <T>(r: Response) => await r.json() as T
118
+ return {
119
+ submit: async (asked) =>
120
+ (await json<{ id: string }>(
121
+ await at('', {
122
+ method: 'POST',
123
+ body: JSON.stringify({ requests: asked.map(entryOf) }),
124
+ }),
125
+ )).id,
126
+ ended: async (b) =>
127
+ (await json<{ processing_status: string }>(await at(id(b))))
128
+ .processing_status == 'ended',
129
+ // JSON lines, one result each.
130
+ results: async (b) =>
131
+ (await (await at(`${id(b)}/results`)).text())
132
+ .split('\n')
133
+ .filter((l) => l.trim())
134
+ .map((l) => answerOf(JSON.parse(l))),
135
+ }
136
+ }
package/deno.json ADDED
@@ -0,0 +1 @@
1
+ {"publish":{"exclude":["**/*_test.ts"]},"name":"@yaks/anthropic","version":"0.2.36","license":"Apache-2.0","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.","exports":{".":"./mod.ts","./vocab":"./vocab.ts","./mark":"./mark.ts","./reads":"./reads.ts","./provider":"./provider.ts","./batches":"./batches.ts"},"imports":{"@yaks/anthropic":"./mod.ts","@yaks/anthropic/vocab":"./vocab.ts","@yaks/anthropic/mark":"./mark.ts","@yaks/anthropic/reads":"./reads.ts","@yaks/anthropic/provider":"./provider.ts","@yaks/anthropic/batches":"./batches.ts"}}
package/mark.js ADDED
@@ -0,0 +1,16 @@
1
+ // What a host writes on the entry recording a reply, importable without the
2
+ // model (./mod.ts): a host that loads it lazily still marks its replies at once.
3
+ import { prefixCacheMark } from "@yaks/model";
4
+ // The documented lifetime of an ephemeral cache entry, in seconds.
5
+ let RETENTION = 300;
6
+ /** `anthropic{response_id, cache_expires_at}` for a reply: the expiry is the
7
+ * request's start plus the cache's five minutes. */ export let mark = (reply, cache)=>({
8
+ anthropic: {
9
+ response_id: reply.id,
10
+ ...prefixCacheMark(reply, cache && {
11
+ ...cache,
12
+ retention: RETENTION
13
+ })
14
+ }
15
+ });
16
+ //# sourceMappingURL=mark.js.map
package/mark.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mark.js","sources":["./mark.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,iFAAiF;AACjF,SAA4B,eAAe,2BAA4C;AAEvF,mEAAmE;AACnE,IAAI,YAAY;AAEhB;kDACkD,GAClD,OAAO,IAAI,OAAO,CAChB,OACA,QAC2C,CAAC;IAC5C,WAAW;MACT,aAAa,MAAM,EAAE;MACrB,GAAG,gBAAgB,OAAO,SAAS;QAAE,GAAG,KAAK;QAAE,WAAW;MAAU,EAAE;IACxE;EACF,CAAC,EAAC"}
package/mark.ts ADDED
@@ -0,0 +1,18 @@
1
+ // What a host writes on the entry recording a reply, importable without the
2
+ // model (./mod.ts): a host that loads it lazily still marks its replies at once.
3
+ import { type CacheContext, prefixCacheMark, type Reply } from '@yaks/model'
4
+
5
+ // The documented lifetime of an ephemeral cache entry, in seconds.
6
+ let RETENTION = 300
7
+
8
+ /** `anthropic{response_id, cache_expires_at}` for a reply: the expiry is the
9
+ * request's start plus the cache's five minutes. */
10
+ export let mark = (
11
+ reply: Reply,
12
+ cache?: CacheContext,
13
+ ): { anthropic: Record<string, unknown> } => ({
14
+ anthropic: {
15
+ response_id: reply.id,
16
+ ...prefixCacheMark(reply, cache && { ...cache, retention: RETENTION }),
17
+ },
18
+ })