@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/speech.ts ADDED
@@ -0,0 +1,158 @@
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 {
5
+ acknowledged,
6
+ type MediaReceipt,
7
+ type MediaReceipts,
8
+ ModelError,
9
+ receivedMedia,
10
+ type Reply,
11
+ type Request,
12
+ submitted,
13
+ } from '@yaks/model'
14
+ import { mediaRoom, type MediaStore } from '@yaks/openai'
15
+ import { deliver, type Output } from './media.js'
16
+ import { encoded } from './bytes.js'
17
+
18
+ let joined = (parts: Uint8Array[], size: number) => {
19
+ let bytes = new Uint8Array(size), at = 0
20
+ for (let part of parts) {
21
+ bytes.set(part, at)
22
+ at += part.length
23
+ }
24
+ return bytes
25
+ }
26
+
27
+ let audio = async (
28
+ res: Response,
29
+ max: number,
30
+ checkpoint: (data: string) => Promise<void>,
31
+ ) => {
32
+ if (!Number.isSafeInteger(max) || max < 1) {
33
+ throw new ModelError('media_limit', 'Invalid media size limit')
34
+ }
35
+ if (!res.body) {
36
+ throw new ModelError('media_response', 'OpenRouter returned no audio')
37
+ }
38
+ let parts: Uint8Array[] = [], size = 0
39
+ for await (let part of res.body) {
40
+ size += part.length
41
+ if (size > max) {
42
+ throw new ModelError(
43
+ 'media_payload',
44
+ 'Media exceeds configured size limit',
45
+ )
46
+ }
47
+ parts.push(part)
48
+ await checkpoint(encoded(joined(parts, size)))
49
+ }
50
+ return encoded(joined(parts, size))
51
+ }
52
+
53
+ export let speech = async (
54
+ req: Request,
55
+ options: {
56
+ key: () => string | Promise<string>
57
+ fetch?: typeof fetch
58
+ signal?: AbortSignal
59
+ media?: MediaStore
60
+ receipts?: MediaReceipts
61
+ },
62
+ ): Promise<Reply> => {
63
+ if (!options.media) {
64
+ throw new ModelError(
65
+ 'media_storage',
66
+ 'Media output requires artifact storage',
67
+ )
68
+ }
69
+ if (req.questions) {
70
+ throw new ModelError('questions', 'Speech models answer no typed questions')
71
+ }
72
+ let input = req.items.findLast((item) => item.kind == 'user')
73
+ if (!input || input.kind != 'user' || !input.text.trim()) {
74
+ throw new ModelError('input', 'Speech models need a text prompt')
75
+ }
76
+ let key = await options.key()
77
+ let body = {
78
+ model: req.model,
79
+ input: input.text,
80
+ response_format: 'mp3',
81
+ }
82
+ let init: RequestInit = {
83
+ method: 'POST',
84
+ headers: {
85
+ authorization: 'Bearer ' + key,
86
+ 'content-type': 'application/json',
87
+ ...req.conversation ? { 'x-session-id': req.conversation } : {},
88
+ },
89
+ body: JSON.stringify(body),
90
+ signal: req.signal && options.signal
91
+ ? AbortSignal.any([req.signal, options.signal])
92
+ : req.signal ?? options.signal,
93
+ }
94
+ let res: Response
95
+ await mediaRoom(options.media)
96
+ await submitted(req)
97
+ try {
98
+ res = await (options.fetch ?? fetch)(
99
+ 'https://openrouter.ai/api/v1/audio/speech',
100
+ init,
101
+ )
102
+ } catch (error) {
103
+ if (
104
+ req.signal?.aborted || options.signal?.aborted ||
105
+ (error instanceof Error && error.name == 'AbortError')
106
+ ) throw error
107
+ throw new ModelError('transport', 'OpenRouter speech connection failed')
108
+ }
109
+ if (!res.ok) {
110
+ throw new ModelError(
111
+ 'http_' + res.status,
112
+ `OpenRouter speech request failed (${res.status})`,
113
+ res.status == 429 || res.status >= 500 ? { after: 0 } : undefined,
114
+ )
115
+ }
116
+ let id = res.headers.get('x-generation-id')
117
+ if (!id) {
118
+ throw new ModelError(
119
+ 'media_response',
120
+ 'OpenRouter returned no generation ID',
121
+ )
122
+ }
123
+ await acknowledged(req, { openrouter: { response_id: id } })
124
+ let receipt = (data: string, complete: boolean): MediaReceipt => {
125
+ let output: Output = {
126
+ kind: 'speech',
127
+ reply: { id, model: req.model, items: [] },
128
+ audio: data,
129
+ mediaType: 'audio/mpeg',
130
+ images: [],
131
+ lookupCost: true,
132
+ }
133
+ return {
134
+ provider: 'openrouter',
135
+ call: req.call ?? id,
136
+ id,
137
+ model: req.model,
138
+ input: body,
139
+ response: output,
140
+ complete,
141
+ }
142
+ }
143
+ let data = await audio(
144
+ res,
145
+ options.media.maxBytes ?? 64 * 1024 * 1024,
146
+ (data) => receivedMedia(req, receipt(data, false), options.receipts),
147
+ )
148
+ let complete = receipt(data, true)
149
+ await receivedMedia(req, complete, options.receipts)
150
+ let reply = await deliver(complete, {
151
+ ...options,
152
+ signal: req.signal && options.signal
153
+ ? AbortSignal.any([req.signal, options.signal])
154
+ : req.signal ?? options.signal,
155
+ })
156
+ await options.receipts?.save({ ...complete, cost: reply.cost, reply })
157
+ return reply
158
+ }
package/vocab.js ADDED
@@ -0,0 +1,16 @@
1
+ // The component declaration, and nothing else: the module a server or a
2
+ // browser page imports at `@yaks/openrouter/vocab`. It makes no HTTP requests
3
+ // and reaches no runtime.
4
+ import doc from './vocab.json' with {
5
+ type: 'json'
6
+ };
7
+ import manifest from './package.json' with {
8
+ type: 'json'
9
+ };
10
+ /** What this adapter records about a reply, in the form `loadVocab` accepts. */ export let openrouterDoc = doc;
11
+ /** What this package is: its manifest's description, the one place it is
12
+ * written, which a host stamps on each document here. */ export let description = manifest.description;
13
+ /** Every document this plugin declares. */ export let docs = [
14
+ openrouterDoc
15
+ ];
16
+ //# sourceMappingURL=vocab.js.map
package/vocab.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vocab.js","sources":["./vocab.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,8EAA8E;AAC9E,0BAA0B;AAG1B,OAAO,SAAS,oBAAoB;EAAE,MAAM;AAAO,EAAC;AACpD,OAAO,cAAc,sBAAsB;EAAE,MAAM;AAAO,EAAC;AAE3D,8EAA8E,GAC9E,OAAO,IAAI,gBAA0B,IAAG;AAExC;uDACuD,GACvD,OAAO,IAAI,cAAsB,SAAS,WAAW,CAAA;AAErD,yCAAyC,GACzC,OAAO,IAAI,OAAmB;EAAC;CAAc,CAAA"}
package/vocab.json ADDED
@@ -0,0 +1,24 @@
1
+ {
2
+ "$id": "urn:uuid:5667b827-4689-439e-b74c-bb439879ee99",
3
+ "title": "openrouter",
4
+ "$defs": {
5
+ "openrouter": {
6
+ "$id": "urn:uuid:5329e80a-39a6-436f-b3e4-24c00cadc962",
7
+ "component": true,
8
+ "journal": false,
9
+ "description": "OpenRouter response metadata; not a server-side continuation handle.",
10
+ "properties": {
11
+ "response_id": {
12
+ "$id": "urn:uuid:2c711d14-0315-4fd9-be8e-a60b654ba1f6",
13
+ "type": "string"
14
+ },
15
+ "cache_expires_at": {
16
+ "$id": "urn:uuid:41b7f256-8f20-4b66-9785-45d85a883a49",
17
+ "type": "string",
18
+ "format": "date-time",
19
+ "description": "the recorded expiry of this request\u2019s cached prefix; provider-reported where present, otherwise request start plus documented provider retention. Missing means unknown, not warm"
20
+ }
21
+ }
22
+ }
23
+ }
24
+ }
package/vocab.ts ADDED
@@ -0,0 +1,17 @@
1
+ // The component declaration, and nothing else: the module a server or a
2
+ // browser page imports at `@yaks/openrouter/vocab`. It makes no HTTP requests
3
+ // and reaches no runtime.
4
+
5
+ import type { VocabDoc } from 'jsr:@yaks/vocab@0.2.36'
6
+ import doc from './vocab.json' with { type: 'json' }
7
+ import manifest from './package.json' with { type: 'json' }
8
+
9
+ /** What this adapter records about a reply, in the form `loadVocab` accepts. */
10
+ export let openrouterDoc: VocabDoc = doc
11
+
12
+ /** What this package is: its manifest's description, the one place it is
13
+ * written, which a host stamps on each document here. */
14
+ export let description: string = manifest.description
15
+
16
+ /** Every document this plugin declares. */
17
+ export let docs: VocabDoc[] = [openrouterDoc]