@yaks/openrouter 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/prompt.js ADDED
@@ -0,0 +1,171 @@
1
+ /** Stable tool declarations and append-only provider cache boundaries. */ import { input } from "@yaks/openai";
2
+ import { encoded } from "./bytes.js";
3
+ let compare = (a, b)=>a < b ? -1 : a > b ? 1 : 0;
4
+ let ordered = (value)=>Array.isArray(value) ? value.map(ordered) : value != null && typeof value == 'object' ? Object.fromEntries(Object.entries(value).sort(([a], [b])=>compare(a, b)).map(([key, v])=>[
5
+ key,
6
+ ordered(v)
7
+ ])) : value;
8
+ /** Object insertion order and tool discovery order are not prompt changes. */ export let tools = (list)=>[
9
+ ...list
10
+ ].sort((a, b)=>compare(a.name, b.name)).map((t)=>({
11
+ name: t.name,
12
+ description: t.description,
13
+ parameters: Object.fromEntries(Object.entries(t.parameters).sort(([a], [b])=>compare(a, b)).map(([key, value])=>[
14
+ key,
15
+ ordered(value)
16
+ ]))
17
+ }));
18
+ // Alibaba's snapshot endpoints are not on its documented explicit-cache list.
19
+ let alibaba = new Set([
20
+ 'deepseek/deepseek-v3.2',
21
+ 'qwen/qwen3-max',
22
+ 'qwen/qwen-plus',
23
+ 'qwen/qwen3.6-plus',
24
+ 'qwen/qwen3-coder-plus',
25
+ 'qwen/qwen3-coder-flash'
26
+ ]);
27
+ export let alibabaCache = (model)=>alibaba.has(model.split(':')[0]);
28
+ export let explicit = (model)=>model.startsWith('anthropic/') || alibabaCache(model);
29
+ let text = (value)=>[
30
+ {
31
+ type: 'text',
32
+ text: value
33
+ }
34
+ ];
35
+ let message = (item)=>item.kind == 'document' ? {
36
+ role: 'user',
37
+ content: [
38
+ ...text(item.label),
39
+ {
40
+ type: 'file',
41
+ file: {
42
+ filename: item.filename ?? item.label,
43
+ file_data: `data:${item.mediaType};base64,${encoded(item.bytes)}`
44
+ }
45
+ }
46
+ ]
47
+ } : item.kind == 'call' ? {
48
+ role: 'assistant',
49
+ tool_calls: [
50
+ {
51
+ id: item.id,
52
+ type: 'function',
53
+ function: {
54
+ name: item.name,
55
+ arguments: item.args
56
+ }
57
+ }
58
+ ]
59
+ } : item.kind == 'result' ? {
60
+ role: 'tool',
61
+ tool_call_id: item.id,
62
+ content: text(item.output)
63
+ } : item.kind == 'image' ? {
64
+ role: 'user',
65
+ content: [
66
+ ...text(item.label),
67
+ {
68
+ type: 'image_url',
69
+ image_url: {
70
+ url: 'data:' + item.mediaType + ';base64,' + encoded(item.bytes)
71
+ }
72
+ }
73
+ ]
74
+ } : {
75
+ role: item.kind == 'instruction' ? 'developer' : item.kind,
76
+ content: text(item.text)
77
+ };
78
+ let mark = (msg)=>{
79
+ let part = msg.content?.at(-1);
80
+ if (part) part.cache_control = {
81
+ type: 'ephemeral'
82
+ };
83
+ };
84
+ /** Request-ending input runs are followed by model output in the transcript.
85
+ * Keep prior ends explicitly: the newest end's 20-block lookback need not
86
+ * reach them. Three rolling ends and the stable instructions fit four slots. */ let boundaries = (items)=>{
87
+ let first = items.findIndex((i)=>i.kind != 'instruction');
88
+ let stable = (first < 0 ? items.length : first) - 1;
89
+ let ends = items.flatMap((i, at)=>(i.kind == 'user' || i.kind == 'image' || i.kind == 'document' || i.kind == 'result') && (!items[at + 1] || items[at + 1].kind == 'assistant' || items[at + 1].kind == 'call' || items[at + 1].kind == 'instruction') ? [
90
+ at
91
+ ] : []);
92
+ let tail = items.length - 1;
93
+ if (tail > stable && !ends.includes(tail)) ends.push(tail);
94
+ return [
95
+ ...stable >= 0 ? [
96
+ stable
97
+ ] : [],
98
+ ...ends.slice(-3)
99
+ ];
100
+ };
101
+ let transcript = (req)=>[
102
+ ...req.instructions ? [
103
+ {
104
+ kind: 'instruction',
105
+ text: req.instructions
106
+ }
107
+ ] : [],
108
+ ...req.items
109
+ ];
110
+ /** Never regroup earlier messages when later tool results arrive. */ export let messages = (req)=>{
111
+ let items = transcript(req);
112
+ let out = items.map(message);
113
+ if (explicit(req.model)) {
114
+ for (let at of boundaries(items))mark(out[at]);
115
+ }
116
+ return out;
117
+ };
118
+ let record = (value)=>value != null && typeof value == 'object' && !Array.isArray(value);
119
+ /** Responses exposes prompt_cache_breakpoint, not per-block cache_control.
120
+ * OpenRouter translates it to Anthropic's default five-minute breakpoint.
121
+ * Text tool outputs use the supported content-array shape from the start. */ export let responseBody = (req, body)=>{
122
+ let items = transcript(req);
123
+ let cache = explicit(req.model);
124
+ let marked = cache ? new Set(boundaries(items)) : new Set();
125
+ let projected = input(items).map((raw, at)=>{
126
+ if (!record(raw) || !cache) return raw;
127
+ let item = items[at];
128
+ let content = item.kind == 'result' ? [
129
+ {
130
+ type: 'input_text',
131
+ text: item.output
132
+ }
133
+ ] : item.kind == 'assistant' ? [
134
+ {
135
+ type: 'input_text',
136
+ text: item.text
137
+ }
138
+ ] : raw.content;
139
+ if (!Array.isArray(content)) return raw;
140
+ let blocks = item.kind == 'image' ? [
141
+ ...content
142
+ ].reverse() : content;
143
+ let last = blocks.findLastIndex((p)=>record(p) && p.type == 'input_text');
144
+ let parts = blocks.map((p, index)=>marked.has(at) && index == last && record(p) ? {
145
+ ...p,
146
+ prompt_cache_breakpoint: {
147
+ mode: 'explicit'
148
+ }
149
+ } : p);
150
+ return item.kind == 'result' ? {
151
+ ...raw,
152
+ output: parts
153
+ } : {
154
+ ...raw,
155
+ content: parts
156
+ };
157
+ });
158
+ let { instructions: _instructions, prompt_cache_options: _cache, ...rest } = body;
159
+ return {
160
+ ...rest,
161
+ input: projected,
162
+ ...req.conversation ? {
163
+ session_id: req.conversation
164
+ } : {}
165
+ };
166
+ };
167
+ /** Chat tool declarations use the same deterministic ordering as Responses. */ export let chatTools = (req)=>tools(req.tools).map((t)=>({
168
+ type: 'function',
169
+ function: t
170
+ }));
171
+ //# sourceMappingURL=prompt.js.map
package/prompt.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompt.js","sources":["./prompt.ts"],"names":[],"mappings":"AA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,OAAO,KAAK,CAAC,GAAG;IACpB,IAAI,UAAU,KAAK,IAAI,IAAI,WACvB;MAAC;QAAE,MAAM;QAAc,MAAM,KAAK,MAAM;MAAC;KAAE,GAC3C,KAAK,IAAI,IAAI,cACb;MAAC;QAAE,MAAM;QAAc,MAAM,KAAK,IAAI;MAAC;KAAE,GACzC,IAAI,OAAO;IACf,IAAI,CAAC,MAAM,OAAO,CAAC,UAAU,OAAO;IACpC,IAAI,SAAS,KAAK,IAAI,IAAI,UAAU;SAAI;KAAQ,CAAC,OAAO,KAAK;IAC7D,IAAI,OAAO,OAAO,aAAa,CAAC,CAAC,IAAM,OAAO,MAAM,EAAE,IAAI,IAAI;IAC9D,IAAI,QAAQ,OAAO,GAAG,CAAC,CAAC,GAAG,QACzB,OAAO,GAAG,CAAC,OAAO,SAAS,QAAQ,OAAO,KACtC;QAAE,GAAG,CAAC;QAAE,yBAAyB;UAAE,MAAM;QAAW;MAAE,IACtD;IAEN,OAAO,KAAK,IAAI,IAAI,WAChB;MAAE,GAAG,GAAG;MAAE,QAAQ;IAAM,IACxB;MAAE,GAAG,GAAG;MAAE,SAAS;IAAM;EAC/B;EACA,IAAI,EAAE,cAAc,aAAa,EAAE,sBAAsB,MAAM,EAAE,GAAG,MAAM,GACxE;EACF,OAAO;IACL,GAAG,IAAI;IACP,OAAO;IACP,GAAG,IAAI,YAAY,GAAG;MAAE,YAAY,IAAI,YAAY;IAAC,IAAI,CAAC,CAAC;EAC7D;AACF,EAAC;AAED,6EAA6E,GAC7E,OAAO,IAAI,YAAY,CAAC,MACtB,MAAM,IAAI,KAAK,EAAE,GAAG,CAAC,CAAC,IAAM,CAAC;MAAE,MAAM;MAAY,UAAU;IAAE,CAAC,GAAE"}
package/prompt.ts ADDED
@@ -0,0 +1,182 @@
1
+ /** Stable tool declarations and append-only provider cache boundaries. */
2
+ import { type Item, type Request, type Tool } from '@yaks/model'
3
+ import { input, type ResponseRequest } from '@yaks/openai'
4
+ import { encoded } from './bytes.js'
5
+
6
+ type Part = {
7
+ type: 'text' | 'image_url' | 'file'
8
+ text?: string
9
+ image_url?: { url: string }
10
+ file?: { filename: string; file_data: string }
11
+ cache_control?: { type: 'ephemeral' }
12
+ }
13
+ type Message = {
14
+ role: string
15
+ content?: Part[]
16
+ tool_call_id?: string
17
+ tool_calls?: {
18
+ id: string
19
+ type: 'function'
20
+ function: { name: string; arguments: string }
21
+ }[]
22
+ }
23
+
24
+ let compare = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0
25
+ let ordered = (value: unknown): unknown =>
26
+ Array.isArray(value)
27
+ ? value.map(ordered)
28
+ : value != null && typeof value == 'object'
29
+ ? Object.fromEntries(
30
+ Object.entries(value).sort(([a], [b]) => compare(a, b))
31
+ .map(([key, v]) => [key, ordered(v)]),
32
+ )
33
+ : value
34
+
35
+ /** Object insertion order and tool discovery order are not prompt changes. */
36
+ export let tools = (list: Tool[]): Tool[] =>
37
+ [...list].sort((a, b) => compare(a.name, b.name)).map((t) => ({
38
+ name: t.name,
39
+ description: t.description,
40
+ parameters: Object.fromEntries(
41
+ Object.entries(t.parameters).sort(([a], [b]) => compare(a, b))
42
+ .map(([key, value]) => [key, ordered(value)]),
43
+ ),
44
+ }))
45
+
46
+ // Alibaba's snapshot endpoints are not on its documented explicit-cache list.
47
+ let alibaba = new Set([
48
+ 'deepseek/deepseek-v3.2',
49
+ 'qwen/qwen3-max',
50
+ 'qwen/qwen-plus',
51
+ 'qwen/qwen3.6-plus',
52
+ 'qwen/qwen3-coder-plus',
53
+ 'qwen/qwen3-coder-flash',
54
+ ])
55
+ export let alibabaCache = (model: string) => alibaba.has(model.split(':')[0])
56
+ export let explicit = (model: string) =>
57
+ model.startsWith('anthropic/') || alibabaCache(model)
58
+
59
+ let text = (value: string): Part[] => [{ type: 'text', text: value }]
60
+ let message = (item: Item): Message =>
61
+ item.kind == 'document'
62
+ ? {
63
+ role: 'user',
64
+ content: [
65
+ ...text(item.label),
66
+ {
67
+ type: 'file',
68
+ file: {
69
+ filename: item.filename ?? item.label,
70
+ file_data: `data:${item.mediaType};base64,${encoded(item.bytes)}`,
71
+ },
72
+ },
73
+ ],
74
+ }
75
+ : item.kind == 'call'
76
+ ? {
77
+ role: 'assistant',
78
+ tool_calls: [{
79
+ id: item.id,
80
+ type: 'function',
81
+ function: { name: item.name, arguments: item.args },
82
+ }],
83
+ }
84
+ : item.kind == 'result'
85
+ ? { role: 'tool', tool_call_id: item.id, content: text(item.output) }
86
+ : item.kind == 'image'
87
+ ? {
88
+ role: 'user',
89
+ content: [
90
+ ...text(item.label),
91
+ {
92
+ type: 'image_url',
93
+ image_url: {
94
+ url: 'data:' + item.mediaType + ';base64,' + encoded(item.bytes),
95
+ },
96
+ },
97
+ ],
98
+ }
99
+ : {
100
+ role: item.kind == 'instruction' ? 'developer' : item.kind,
101
+ content: text(item.text),
102
+ }
103
+ let mark = (msg: Message) => {
104
+ let part = msg.content?.at(-1)
105
+ if (part) part.cache_control = { type: 'ephemeral' }
106
+ }
107
+
108
+ /** Request-ending input runs are followed by model output in the transcript.
109
+ * Keep prior ends explicitly: the newest end's 20-block lookback need not
110
+ * reach them. Three rolling ends and the stable instructions fit four slots. */
111
+ let boundaries = (items: Item[]) => {
112
+ let first = items.findIndex((i) => i.kind != 'instruction')
113
+ let stable = (first < 0 ? items.length : first) - 1
114
+ let ends = items.flatMap((i, at) =>
115
+ (i.kind == 'user' || i.kind == 'image' || i.kind == 'document' ||
116
+ i.kind == 'result') &&
117
+ (!items[at + 1] || items[at + 1].kind == 'assistant' ||
118
+ items[at + 1].kind == 'call' || items[at + 1].kind == 'instruction')
119
+ ? [at]
120
+ : []
121
+ )
122
+ let tail = items.length - 1
123
+ if (tail > stable && !ends.includes(tail)) ends.push(tail)
124
+ return [...stable >= 0 ? [stable] : [], ...ends.slice(-3)]
125
+ }
126
+ let transcript = (req: Request): Item[] => [
127
+ ...req.instructions
128
+ ? [{ kind: 'instruction' as const, text: req.instructions }]
129
+ : [],
130
+ ...req.items,
131
+ ]
132
+
133
+ /** Never regroup earlier messages when later tool results arrive. */
134
+ export let messages = (req: Request): Message[] => {
135
+ let items = transcript(req)
136
+ let out = items.map(message)
137
+ if (explicit(req.model)) { for (let at of boundaries(items)) mark(out[at]) }
138
+ return out
139
+ }
140
+
141
+ let record = (value: unknown): value is Record<string, unknown> =>
142
+ value != null && typeof value == 'object' && !Array.isArray(value)
143
+
144
+ /** Responses exposes prompt_cache_breakpoint, not per-block cache_control.
145
+ * OpenRouter translates it to Anthropic's default five-minute breakpoint.
146
+ * Text tool outputs use the supported content-array shape from the start. */
147
+ export let responseBody = (req: Request, body: ResponseRequest) => {
148
+ let items = transcript(req)
149
+ let cache = explicit(req.model)
150
+ let marked = cache ? new Set(boundaries(items)) : new Set()
151
+ let projected = input(items).map((raw, at) => {
152
+ if (!record(raw) || !cache) return raw
153
+ let item = items[at]
154
+ let content = item.kind == 'result'
155
+ ? [{ type: 'input_text', text: item.output }]
156
+ : item.kind == 'assistant'
157
+ ? [{ type: 'input_text', text: item.text }]
158
+ : raw.content
159
+ if (!Array.isArray(content)) return raw
160
+ let blocks = item.kind == 'image' ? [...content].reverse() : content
161
+ let last = blocks.findLastIndex((p) => record(p) && p.type == 'input_text')
162
+ let parts = blocks.map((p, index) =>
163
+ marked.has(at) && index == last && record(p)
164
+ ? { ...p, prompt_cache_breakpoint: { mode: 'explicit' } }
165
+ : p
166
+ )
167
+ return item.kind == 'result'
168
+ ? { ...raw, output: parts }
169
+ : { ...raw, content: parts }
170
+ })
171
+ let { instructions: _instructions, prompt_cache_options: _cache, ...rest } =
172
+ body
173
+ return {
174
+ ...rest,
175
+ input: projected,
176
+ ...req.conversation ? { session_id: req.conversation } : {},
177
+ }
178
+ }
179
+
180
+ /** Chat tool declarations use the same deterministic ordering as Responses. */
181
+ export let chatTools = (req: Request) =>
182
+ tools(req.tools).map((t) => ({ type: 'function', function: t }))
package/provider.js ADDED
@@ -0,0 +1,34 @@
1
+ // @yaks/openrouter as a provider a config names (@yaks/model `ProviderFacet`):
2
+ // `openrouter`, on the key the person's OpenRouter sign-in keeps, with the
3
+ // media its models generate kept in the host's artifact store.
4
+ import { deferredModel, prefixCacheMark } from "@yaks/model";
5
+ import { openrouterDoc } from "./vocab.js";
6
+ /** `openrouter`, over the host's connections and the person's key. */ export let providers = (lent)=>({
7
+ openrouter: deferredModel(()=>import("./mod.js").then(({ responses })=>responses({
8
+ fetch: lent.fetch,
9
+ media: {
10
+ store: lent.store
11
+ },
12
+ receipts: lent.receipts,
13
+ scope: lent.scope,
14
+ key: async ()=>{
15
+ let key = await lent.key('openrouter');
16
+ if (!key) {
17
+ throw new Error('OpenRouter is not connected. Run yak auth openrouter.');
18
+ }
19
+ return key;
20
+ }
21
+ })), {
22
+ vocab: openrouterDoc,
23
+ info: true,
24
+ mark: (reply, cache)=>({
25
+ openrouter: {
26
+ response_id: reply.id,
27
+ ...prefixCacheMark(reply, cache)
28
+ }
29
+ }),
30
+ recover: true,
31
+ reads: true
32
+ })
33
+ });
34
+ //# sourceMappingURL=provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.js","sources":["./provider.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,2EAA2E;AAC3E,+DAA+D;AAE/D,SACE,aAAa,EAGb,eAAe,2BACc;AAC/B,SAAS,aAAa,qBAAoB;AAE1C,oEAAoE,GACpE,OAAO,IAAI,YAAY,CAAC,OAAsC,CAAC;IAC7D,YAAY,cACV,IACE,MAAM,CAAC,YAAY,IAAI,CAAC,CAAC,EAAE,SAAS,EAAE,GACpC,UAAU;UACR,OAAO,KAAK,KAAK;UACjB,OAAO;YAAE,OAAO,KAAK,KAAK;UAAC;UAC3B,UAAU,KAAK,QAAQ;UACvB,OAAO,KAAK,KAAK;UACjB,KAAK;YACH,IAAI,MAAM,MAAM,KAAK,GAAG,CAAC;YACzB,IAAI,CAAC,KAAK;cACR,MAAM,IAAI,MACR;YAEJ;YACA,OAAO;UACT;QACF,KAEJ;MACE,OAAO;MACP,MAAM;MACN,MAAM,CAAC,OAAO,QAAU,CAAC;UACvB,YAAY;YACV,aAAa,MAAM,EAAE;YACrB,GAAG,gBAAgB,OAAO,MAAM;UAClC;QACF,CAAC;MACD,SAAS;MACT,OAAO;IACT;EAEJ,CAAC,EAAC"}
package/provider.ts ADDED
@@ -0,0 +1,47 @@
1
+ // @yaks/openrouter as a provider a config names (@yaks/model `ProviderFacet`):
2
+ // `openrouter`, on the key the person's OpenRouter sign-in keeps, with the
3
+ // media its models generate kept in the host's artifact store.
4
+
5
+ import {
6
+ deferredModel,
7
+ type Lent,
8
+ type Model,
9
+ prefixCacheMark,
10
+ } from '@yaks/model'
11
+ import { openrouterDoc } from './vocab.js'
12
+
13
+ /** `openrouter`, over the host's connections and the person's key. */
14
+ export let providers = (lent: Lent): Record<string, Model> => ({
15
+ openrouter: deferredModel(
16
+ () =>
17
+ import('./mod.js').then(({ responses }) =>
18
+ responses({
19
+ fetch: lent.fetch,
20
+ media: { store: lent.store },
21
+ receipts: lent.receipts,
22
+ scope: lent.scope,
23
+ key: async () => {
24
+ let key = await lent.key('openrouter')
25
+ if (!key) {
26
+ throw new Error(
27
+ 'OpenRouter is not connected. Run yak auth openrouter.',
28
+ )
29
+ }
30
+ return key
31
+ },
32
+ })
33
+ ),
34
+ {
35
+ vocab: openrouterDoc,
36
+ info: true,
37
+ mark: (reply, cache) => ({
38
+ openrouter: {
39
+ response_id: reply.id,
40
+ ...prefixCacheMark(reply, cache),
41
+ },
42
+ }),
43
+ recover: true,
44
+ reads: true,
45
+ },
46
+ ),
47
+ })
package/reads.js ADDED
@@ -0,0 +1,21 @@
1
+ // https://openrouter.ai/docs/guides/overview/multimodal/image-understanding
2
+ // https://openrouter.ai/docs/guides/overview/multimodal/pdfs
3
+ // Native image/file support comes from each model's input_modalities. PDF
4
+ // parsing for other models is an OpenRouter service, not a native model input.
5
+ // OpenRouter publishes no common byte cap: its upstream model validates that
6
+ // limit. Infinity means no provider-wide byte ceiling has been documented.
7
+ /** Native inputs advertised by one model in OpenRouter's catalogue. */ export let reads = (modalities)=>({
8
+ ...modalities.includes('image') ? Object.fromEntries([
9
+ 'image/png',
10
+ 'image/jpeg',
11
+ 'image/webp',
12
+ 'image/gif'
13
+ ].map((type)=>[
14
+ type,
15
+ Infinity
16
+ ])) : {},
17
+ ...modalities.includes('file') ? {
18
+ 'application/pdf': Infinity
19
+ } : {}
20
+ });
21
+ //# sourceMappingURL=reads.js.map
package/reads.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reads.js","sources":["./reads.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,6DAA6D;AAC7D,0EAA0E;AAC1E,+EAA+E;AAC/E,6EAA6E;AAC7E,2EAA2E;AAC3E,qEAAqE,GACrE,OAAO,IAAI,QAAQ,CAAC,aAAiD,CAAC;IACpE,GAAG,WAAW,QAAQ,CAAC,WACnB,OAAO,WAAW,CAClB;MAAC;MAAa;MAAc;MAAc;KAAY,CAAC,GAAG,CAAC,CACzD,OACG;QAAC;QAAM;OAAS,KAErB,CAAC,CAAC;IACN,GAAG,WAAW,QAAQ,CAAC,UAAU;MAAE,mBAAmB;IAAS,IAAI,CAAC,CAAC;EACvE,CAAC,EAAC"}
package/reads.ts ADDED
@@ -0,0 +1,17 @@
1
+ // https://openrouter.ai/docs/guides/overview/multimodal/image-understanding
2
+ // https://openrouter.ai/docs/guides/overview/multimodal/pdfs
3
+ // Native image/file support comes from each model's input_modalities. PDF
4
+ // parsing for other models is an OpenRouter service, not a native model input.
5
+ // OpenRouter publishes no common byte cap: its upstream model validates that
6
+ // limit. Infinity means no provider-wide byte ceiling has been documented.
7
+ /** Native inputs advertised by one model in OpenRouter's catalogue. */
8
+ export let reads = (modalities: string[]): Record<string, number> => ({
9
+ ...modalities.includes('image')
10
+ ? Object.fromEntries(
11
+ ['image/png', 'image/jpeg', 'image/webp', 'image/gif'].map((
12
+ type,
13
+ ) => [type, Infinity]),
14
+ )
15
+ : {},
16
+ ...modalities.includes('file') ? { 'application/pdf': Infinity } : {},
17
+ })
package/speech.js ADDED
@@ -0,0 +1,129 @@
1
+ // OpenRouter's speech door answers audio bytes rather than a chat message.
2
+ // The adapter keeps those bytes in the caller's artifact store before the
3
+ // session records their address.
4
+ import { acknowledged, ModelError, receivedMedia, submitted } from "@yaks/model";
5
+ import { mediaRoom } from "@yaks/openai";
6
+ import { deliver } from "./media.js";
7
+ import { encoded } from "./bytes.js";
8
+ let joined = (parts, size)=>{
9
+ let bytes = new Uint8Array(size), at = 0;
10
+ for (let part of parts){
11
+ bytes.set(part, at);
12
+ at += part.length;
13
+ }
14
+ return bytes;
15
+ };
16
+ let audio = async (res, max, checkpoint)=>{
17
+ if (!Number.isSafeInteger(max) || max < 1) {
18
+ throw new ModelError('media_limit', 'Invalid media size limit');
19
+ }
20
+ if (!res.body) {
21
+ throw new ModelError('media_response', 'OpenRouter returned no audio');
22
+ }
23
+ let parts = [], size = 0;
24
+ for await (let part of res.body){
25
+ size += part.length;
26
+ if (size > max) {
27
+ throw new ModelError('media_payload', 'Media exceeds configured size limit');
28
+ }
29
+ parts.push(part);
30
+ await checkpoint(encoded(joined(parts, size)));
31
+ }
32
+ return encoded(joined(parts, size));
33
+ };
34
+ export let speech = async (req, options)=>{
35
+ if (!options.media) {
36
+ throw new ModelError('media_storage', 'Media output requires artifact storage');
37
+ }
38
+ if (req.questions) {
39
+ throw new ModelError('questions', 'Speech models answer no typed questions');
40
+ }
41
+ let input = req.items.findLast((item)=>item.kind == 'user');
42
+ if (!input || input.kind != 'user' || !input.text.trim()) {
43
+ throw new ModelError('input', 'Speech models need a text prompt');
44
+ }
45
+ let key = await options.key();
46
+ let body = {
47
+ model: req.model,
48
+ input: input.text,
49
+ response_format: 'mp3'
50
+ };
51
+ let init = {
52
+ method: 'POST',
53
+ headers: {
54
+ authorization: 'Bearer ' + key,
55
+ 'content-type': 'application/json',
56
+ ...req.conversation ? {
57
+ 'x-session-id': req.conversation
58
+ } : {}
59
+ },
60
+ body: JSON.stringify(body),
61
+ signal: req.signal && options.signal ? AbortSignal.any([
62
+ req.signal,
63
+ options.signal
64
+ ]) : req.signal ?? options.signal
65
+ };
66
+ let res;
67
+ await mediaRoom(options.media);
68
+ await submitted(req);
69
+ try {
70
+ res = await (options.fetch ?? fetch)('https://openrouter.ai/api/v1/audio/speech', init);
71
+ } catch (error) {
72
+ if (req.signal?.aborted || options.signal?.aborted || error instanceof Error && error.name == 'AbortError') throw error;
73
+ throw new ModelError('transport', 'OpenRouter speech connection failed');
74
+ }
75
+ if (!res.ok) {
76
+ throw new ModelError('http_' + res.status, `OpenRouter speech request failed (${res.status})`, res.status == 429 || res.status >= 500 ? {
77
+ after: 0
78
+ } : undefined);
79
+ }
80
+ let id = res.headers.get('x-generation-id');
81
+ if (!id) {
82
+ throw new ModelError('media_response', 'OpenRouter returned no generation ID');
83
+ }
84
+ await acknowledged(req, {
85
+ openrouter: {
86
+ response_id: id
87
+ }
88
+ });
89
+ let receipt = (data, complete)=>{
90
+ let output = {
91
+ kind: 'speech',
92
+ reply: {
93
+ id,
94
+ model: req.model,
95
+ items: []
96
+ },
97
+ audio: data,
98
+ mediaType: 'audio/mpeg',
99
+ images: [],
100
+ lookupCost: true
101
+ };
102
+ return {
103
+ provider: 'openrouter',
104
+ call: req.call ?? id,
105
+ id,
106
+ model: req.model,
107
+ input: body,
108
+ response: output,
109
+ complete
110
+ };
111
+ };
112
+ let data = await audio(res, options.media.maxBytes ?? 64 * 1024 * 1024, (data)=>receivedMedia(req, receipt(data, false), options.receipts));
113
+ let complete = receipt(data, true);
114
+ await receivedMedia(req, complete, options.receipts);
115
+ let reply = await deliver(complete, {
116
+ ...options,
117
+ signal: req.signal && options.signal ? AbortSignal.any([
118
+ req.signal,
119
+ options.signal
120
+ ]) : req.signal ?? options.signal
121
+ });
122
+ await options.receipts?.save({
123
+ ...complete,
124
+ cost: reply.cost,
125
+ reply
126
+ });
127
+ return reply;
128
+ };
129
+ //# sourceMappingURL=speech.js.map
package/speech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