@yaks/model 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.
Files changed (126) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +868 -2
  3. package/_dist/afford.d.ts +69 -0
  4. package/_dist/afford.d.ts.map +1 -0
  5. package/_dist/attribute.d.ts +52 -0
  6. package/_dist/attribute.d.ts.map +1 -0
  7. package/_dist/batch.d.ts +28 -0
  8. package/_dist/batch.d.ts.map +1 -0
  9. package/_dist/cache.d.ts +15 -0
  10. package/_dist/cache.d.ts.map +1 -0
  11. package/_dist/deferred.d.ts +9 -0
  12. package/_dist/deferred.d.ts.map +1 -0
  13. package/_dist/graph.d.ts +3 -0
  14. package/_dist/graph.d.ts.map +1 -0
  15. package/_dist/image.d.ts +46 -0
  16. package/_dist/image.d.ts.map +1 -0
  17. package/_dist/inference.d.ts +58 -0
  18. package/_dist/inference.d.ts.map +1 -0
  19. package/_dist/limits.d.ts +142 -0
  20. package/_dist/limits.d.ts.map +1 -0
  21. package/_dist/media.d.ts +28 -0
  22. package/_dist/media.d.ts.map +1 -0
  23. package/_dist/message.d.ts +5 -0
  24. package/_dist/message.d.ts.map +1 -0
  25. package/_dist/mod.d.ts +298 -0
  26. package/_dist/mod.d.ts.map +1 -0
  27. package/_dist/offers.d.ts +19 -0
  28. package/_dist/offers.d.ts.map +1 -0
  29. package/_dist/onward.d.ts +77 -0
  30. package/_dist/onward.d.ts.map +1 -0
  31. package/_dist/prices.d.ts +27 -0
  32. package/_dist/prices.d.ts.map +1 -0
  33. package/_dist/provider.d.ts +49 -0
  34. package/_dist/provider.d.ts.map +1 -0
  35. package/_dist/results.d.ts +21 -0
  36. package/_dist/results.d.ts.map +1 -0
  37. package/_dist/route.d.ts +189 -0
  38. package/_dist/route.d.ts.map +1 -0
  39. package/_dist/sse.d.ts +4 -0
  40. package/_dist/sse.d.ts.map +1 -0
  41. package/_dist/stall.d.ts +47 -0
  42. package/_dist/stall.d.ts.map +1 -0
  43. package/_dist/step.d.ts +71 -0
  44. package/_dist/step.d.ts.map +1 -0
  45. package/_dist/submission.d.ts +7 -0
  46. package/_dist/submission.d.ts.map +1 -0
  47. package/_dist/vocab.d.ts +82 -0
  48. package/_dist/vocab.d.ts.map +1 -0
  49. package/_dist/windows.d.ts +6 -0
  50. package/_dist/windows.d.ts.map +1 -0
  51. package/afford.js +135 -0
  52. package/afford.js.map +1 -0
  53. package/afford.ts +208 -0
  54. package/attribute.js +109 -0
  55. package/attribute.js.map +1 -0
  56. package/attribute.ts +120 -0
  57. package/batch.js +8 -0
  58. package/batch.js.map +1 -0
  59. package/batch.ts +37 -0
  60. package/cache.js +28 -0
  61. package/cache.js.map +1 -0
  62. package/cache.ts +53 -0
  63. package/deferred.js +29 -0
  64. package/deferred.js.map +1 -0
  65. package/deferred.ts +54 -0
  66. package/deno.json +1 -0
  67. package/graph.js +8 -0
  68. package/graph.js.map +1 -0
  69. package/graph.ts +9 -0
  70. package/image.js +118 -0
  71. package/image.js.map +1 -0
  72. package/image.ts +108 -0
  73. package/inference.js +119 -0
  74. package/inference.js.map +1 -0
  75. package/inference.ts +223 -0
  76. package/limits.js +204 -0
  77. package/limits.js.map +1 -0
  78. package/limits.ts +230 -0
  79. package/media.js +76 -0
  80. package/media.js.map +1 -0
  81. package/media.ts +139 -0
  82. package/message.js +21 -0
  83. package/message.js.map +1 -0
  84. package/message.ts +17 -0
  85. package/mod.js +396 -0
  86. package/mod.js.map +1 -0
  87. package/mod.ts +695 -0
  88. package/offers.js +53 -0
  89. package/offers.js.map +1 -0
  90. package/offers.ts +84 -0
  91. package/onward.js +110 -0
  92. package/onward.js.map +1 -0
  93. package/onward.ts +123 -0
  94. package/package.json +53 -4
  95. package/prices.js +61 -0
  96. package/prices.js.map +1 -0
  97. package/prices.json +643 -0
  98. package/prices.ts +60 -0
  99. package/provider.js +6 -0
  100. package/provider.js.map +1 -0
  101. package/provider.ts +89 -0
  102. package/results.js +51 -0
  103. package/results.js.map +1 -0
  104. package/results.ts +47 -0
  105. package/route.js +263 -0
  106. package/route.js.map +1 -0
  107. package/route.ts +359 -0
  108. package/sse.js +71 -0
  109. package/sse.js.map +1 -0
  110. package/sse.ts +82 -0
  111. package/stall.js +166 -0
  112. package/stall.js.map +1 -0
  113. package/stall.ts +201 -0
  114. package/step.js +226 -0
  115. package/step.js.map +1 -0
  116. package/step.ts +265 -0
  117. package/submission.js +38 -0
  118. package/submission.js.map +1 -0
  119. package/submission.ts +38 -0
  120. package/vocab.js +83 -0
  121. package/vocab.js.map +1 -0
  122. package/vocab.json +613 -0
  123. package/vocab.ts +139 -0
  124. package/windows.js +35 -0
  125. package/windows.js.map +1 -0
  126. package/windows.ts +28 -0
package/offers.js ADDED
@@ -0,0 +1,53 @@
1
+ // Which provider serves a model, read off a graph's `serves` edges. The
2
+ // implementations are the host's, keyed by `provider.name`, and these say
3
+ // which of them answers a model.
4
+ import { identityEid } from "@yaks/graph/identity";
5
+ import { line } from "@yaks/query";
6
+ import { ModelError } from "./mod.js";
7
+ import { MODEL } from "./vocab.js";
8
+ /** Every `serves` edge that points at a model, each with the implementation
9
+ * this host has for its provider. */ export let offers = async (g, model, implementations)=>{
10
+ let edges = await g.read(line`.serves .edge.to=${model}`);
11
+ let froms = edges.map((b)=>String(b.edge.from));
12
+ let rows = froms.length ? await g.get(froms) : [];
13
+ let named = new Map(rows.filter(Boolean).map((b)=>[
14
+ b.entity.eid,
15
+ b.provider?.name
16
+ ]));
17
+ return edges.map((b, i)=>{
18
+ let provider = named.get(froms[i]);
19
+ return {
20
+ provider: froms[i],
21
+ model,
22
+ name: String(b.serves.name ?? ''),
23
+ serve: typeof provider == 'string' && Object.hasOwn(implementations, provider) ? implementations[provider] : undefined
24
+ };
25
+ });
26
+ };
27
+ /** The offer a `using` resolves to: the named provider's, which must serve the
28
+ * model, or else the one provider this host can reach that serves it. */ export let offerFor = (all, provider)=>{
29
+ if (provider != null) {
30
+ let named = all.find((o)=>o.provider == provider);
31
+ if (!named) return 'The selected provider does not serve this model';
32
+ return named.serve ? named : 'No implementation configured for the selected provider';
33
+ }
34
+ let reachable = all.filter((o)=>o.serve);
35
+ if (reachable.length == 1) return reachable[0];
36
+ return reachable.length ? 'Several providers serve this model; name one' : 'No implementation configured for a provider of this model';
37
+ };
38
+ /** A host's providers as one model, asked for a model by its own name
39
+ * (`model.name`, the same row in every graph): the one of `implementations`
40
+ * whose provider `g` says serves it answers, under the name that provider
41
+ * calls it. A name none of them serves, or several do, is refused with a
42
+ * `ModelError` coded `provider`. */ export let serving = (g, implementations)=>async (req)=>{
43
+ let model = identityEid(MODEL, [
44
+ req.model
45
+ ]);
46
+ let found = offerFor(await offers(g, model, implementations));
47
+ if (typeof found == 'string') throw new ModelError('provider', found);
48
+ return found.serve({
49
+ ...req,
50
+ model: found.name
51
+ });
52
+ };
53
+ //# sourceMappingURL=offers.js.map
package/offers.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"offers.js","sources":["./offers.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,0EAA0E;AAC1E,iCAAiC;AAGjC,SAAS,WAAW,oCAAyC;AAC7D,SAAS,IAAI,2BAAgC;AAC7C,SAAqB,UAAU,mBAAkB;AACjD,SAAS,KAAK,qBAAoB;AAWlC;mCACmC,GACnC,OAAO,IAAI,SAAS,OAClB,GACA,OACA;EAEA,IAAI,QAAQ,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,MAAM,CAAC;EACxD,IAAI,QAAQ,MAAM,GAAG,CAAC,CAAC,IAAM,OAAO,AAAC,EAAE,IAAI,CAAU,IAAI;EACzD,IAAI,OAAO,MAAM,MAAM,GAAG,MAAM,EAAE,GAAG,CAAC,SAAS,EAAE;EACjD,IAAI,QAAQ,IAAI,IACd,KAAK,MAAM,CAAC,SAAS,GAAG,CAAC,CAAC,IAAM;MAC9B,EAAE,MAAM,CAAC,GAAG;MACX,EAAE,QAAQ,EAAuB;KACnC;EAEH,OAAO,MAAM,GAAG,CAAC,CAAC,GAAG;IACnB,IAAI,WAAW,MAAM,GAAG,CAAC,KAAK,CAAC,EAAE;IACjC,OAAO;MACL,UAAU,KAAK,CAAC,EAAE;MAClB;MACA,MAAM,OAAO,AAAC,EAAE,MAAM,CAAU,IAAI,IAAI;MACxC,OAAO,OAAO,YAAY,YACtB,OAAO,MAAM,CAAC,iBAAiB,YAC/B,eAAe,CAAC,SAAS,GACzB;IACN;EACF;AACF,EAAC;AAED;uEACuE,GACvE,OAAO,IAAI,WAAW,CACpB,KACA;EAEA,IAAI,YAAY,MAAM;IACpB,IAAI,QAAQ,IAAI,IAAI,CAAC,CAAC,IAAM,EAAE,QAAQ,IAAI;IAC1C,IAAI,CAAC,OAAO,OAAO;IACnB,OAAO,MAAM,KAAK,GACd,QACA;EACN;EACA,IAAI,YAAY,IAAI,MAAM,CAAC,CAAC,IAAM,EAAE,KAAK;EACzC,IAAI,UAAU,MAAM,IAAI,GAAG,OAAO,SAAS,CAAC,EAAE;EAC9C,OAAO,UAAU,MAAM,GACnB,iDACA;AACN,EAAC;AAED;;;;kCAIkC,GAClC,OAAO,IAAI,UAAU,CACnB,GACA,kBAEF,OAAO;IACL,IAAI,QAAQ,YAAY,OAAO;MAAC,IAAI,KAAK;KAAC;IAC1C,IAAI,QAAQ,SAAS,MAAM,OAAO,GAAG,OAAO;IAC5C,IAAI,OAAO,SAAS,UAAU,MAAM,IAAI,WAAW,YAAY;IAC/D,OAAO,MAAM,KAAK,CAAE;MAAE,GAAG,GAAG;MAAE,OAAO,MAAM,IAAI;IAAC;EAClD,EAAC"}
package/offers.ts ADDED
@@ -0,0 +1,84 @@
1
+ // Which provider serves a model, read off a graph's `serves` edges. The
2
+ // implementations are the host's, keyed by `provider.name`, and these say
3
+ // which of them answers a model.
4
+
5
+ import type { Comp, Eid, Graph } from 'jsr:@yaks/graph@0.2.36'
6
+ import { identityEid } from '@yaks/graph/identity'
7
+ import { line } from '@yaks/query'
8
+ import { type Model, ModelError } from './mod.js'
9
+ import { MODEL } from './vocab.js'
10
+
11
+ /** One provider's offering of a model: who serves it, under what name, and
12
+ * the implementation this host has for that provider (if any). */
13
+ export type Offer = {
14
+ provider: Eid
15
+ model: Eid
16
+ name: string
17
+ serve?: Model
18
+ }
19
+
20
+ /** Every `serves` edge that points at a model, each with the implementation
21
+ * this host has for its provider. */
22
+ export let offers = async (
23
+ g: Pick<Graph, 'read' | 'get'>,
24
+ model: Eid,
25
+ implementations: Readonly<Record<string, Model>>,
26
+ ): Promise<Offer[]> => {
27
+ let edges = await g.read(line`.serves .edge.to=${model}`)
28
+ let froms = edges.map((b) => String((b.edge as Comp).from))
29
+ let rows = froms.length ? await g.get(froms) : []
30
+ let named = new Map(
31
+ rows.filter(Boolean).map((b) => [
32
+ b.entity.eid,
33
+ (b.provider as Comp | undefined)?.name,
34
+ ]),
35
+ )
36
+ return edges.map((b, i) => {
37
+ let provider = named.get(froms[i])
38
+ return {
39
+ provider: froms[i],
40
+ model,
41
+ name: String((b.serves as Comp).name ?? ''),
42
+ serve: typeof provider == 'string' &&
43
+ Object.hasOwn(implementations, provider)
44
+ ? implementations[provider]
45
+ : undefined,
46
+ }
47
+ })
48
+ }
49
+
50
+ /** The offer a `using` resolves to: the named provider's, which must serve the
51
+ * model, or else the one provider this host can reach that serves it. */
52
+ export let offerFor = (
53
+ all: Offer[],
54
+ provider?: unknown,
55
+ ): Offer | string => {
56
+ if (provider != null) {
57
+ let named = all.find((o) => o.provider == provider)
58
+ if (!named) return 'The selected provider does not serve this model'
59
+ return named.serve
60
+ ? named
61
+ : 'No implementation configured for the selected provider'
62
+ }
63
+ let reachable = all.filter((o) => o.serve)
64
+ if (reachable.length == 1) return reachable[0]
65
+ return reachable.length
66
+ ? 'Several providers serve this model; name one'
67
+ : 'No implementation configured for a provider of this model'
68
+ }
69
+
70
+ /** A host's providers as one model, asked for a model by its own name
71
+ * (`model.name`, the same row in every graph): the one of `implementations`
72
+ * whose provider `g` says serves it answers, under the name that provider
73
+ * calls it. A name none of them serves, or several do, is refused with a
74
+ * `ModelError` coded `provider`. */
75
+ export let serving = (
76
+ g: Pick<Graph, 'read' | 'get'>,
77
+ implementations: Readonly<Record<string, Model>>,
78
+ ): Model =>
79
+ async (req) => {
80
+ let model = identityEid(MODEL, [req.model])
81
+ let found = offerFor(await offers(g, model, implementations))
82
+ if (typeof found == 'string') throw new ModelError('provider', found)
83
+ return found.serve!({ ...req, model: found.name })
84
+ }
package/onward.js ADDED
@@ -0,0 +1,110 @@
1
+ // A step asked of a chain of models: where the provider refuses it, because
2
+ // the model asked is retired or is none it knows, or because its own account
3
+ // has nothing left to spend, or because its credential is unavailable, the
4
+ // step goes on to the next model the chain names.
5
+ import { dry } from "./limits.js";
6
+ import { ModelError } from "./mod.js";
7
+ // The codes a provider's "no such model" is heard as: `model` where a
8
+ // provider package names it so (@yaks/workers-ai, @yaks/anthropic,
9
+ // @yaks/openai's own door), and OpenAI's own `model_not_found`, which an
10
+ // OpenAI-compatible API passes on as it came.
11
+ let GONE = new Set([
12
+ 'model',
13
+ 'model_not_found'
14
+ ]);
15
+ /**
16
+ * Whether `error` is a provider saying it has no model by the name asked: one
17
+ * it retired, or one it never had.
18
+ *
19
+ * ```ts
20
+ * import { gone, ModelError } from '@yaks/model'
21
+ * import { equal } from '@yaks/testing'
22
+ * equal(gone(new ModelError('model', '5028: m was deprecated')), true)
23
+ * equal(gone(new ModelError('model_not_found')), true)
24
+ * equal(gone(new ModelError('busy')), false)
25
+ * equal(gone(new Error('model')), false)
26
+ * ```
27
+ */ export let gone = (error)=>error instanceof ModelError && GONE.has(error.code);
28
+ /**
29
+ * Whether `error` is a provider declining to run the request at all: the
30
+ * model asked is {@link gone}, or the provider's own account is dry (@yaks/model
31
+ * `dry`: its spend limit, billing quota, credit or plan window used up), or
32
+ * the request has no credential. A
33
+ * refused request ran nothing, so it costs nothing and another provider may
34
+ * take it. A caller's own ceiling (`limit`) is no refusal: every provider
35
+ * would meet it.
36
+ *
37
+ * ```ts
38
+ * import { ModelError, refused } from '@yaks/model'
39
+ * import { equal } from '@yaks/testing'
40
+ * equal(refused(new ModelError('model')), true)
41
+ * equal(refused(new ModelError('project_spend_limit_exceeded')), true)
42
+ * equal(refused(new ModelError('credit')), true)
43
+ * equal(refused(new ModelError('no_credential')), true)
44
+ * equal(refused(new ModelError('limit')), false)
45
+ * equal(refused(new ModelError('busy')), false)
46
+ * ```
47
+ */ export let refused = (error)=>gone(error) || error instanceof ModelError && (dry(error) || error.code == 'no_credential');
48
+ /**
49
+ * A model that asks `chain(req)` in order: the first link answers the step,
50
+ * and a link {@link refused} before producing output passes the step to the
51
+ * next, even where the provider acknowledged the request first. `passed`
52
+ * hears each such failure with the name it was asked by. Other failures are
53
+ * thrown as they came.
54
+ *
55
+ * ```ts
56
+ * import { type Model, ModelError, onward } from '@yaks/model'
57
+ * import { equal } from '@yaks/testing'
58
+ * let failing = (code: string): Model => () => Promise.reject(new ModelError(code))
59
+ * let acked = (code: string): Model => async (req) => {
60
+ * await req.onAck?.({ p: { id: 'r' } })
61
+ * throw new ModelError(code)
62
+ * }
63
+ * let started = (code: string): Model => (req) => {
64
+ * req.onFirst?.()
65
+ * return Promise.reject(new ModelError(code))
66
+ * }
67
+ * let ok: Model = (req) =>
68
+ * Promise.resolve({ id: 'r', model: req.model, items: [] })
69
+ * let heard: string[] = []
70
+ * let chain = (links: Model[]) => () =>
71
+ * links.map((model, i) => ({ model, name: 'm' + i }))
72
+ * let ask = (...links: Model[]) =>
73
+ * onward(chain(links), (name) => heard.push(name))(
74
+ * { model: 'm0', items: [], tools: [] },
75
+ * ).then((r) => r.model, (e) => e.code)
76
+ * equal(await ask(failing('model'), ok), 'm1')
77
+ * equal(await ask(acked('project_spend_limit_exceeded'), ok), 'm1')
78
+ * equal(await ask(failing('credit'), failing('model'), ok), 'm2')
79
+ * equal(await ask(failing('busy'), ok), 'busy')
80
+ * equal(await ask(failing('limit'), ok), 'limit')
81
+ * equal(await ask(started('credit'), ok), 'credit')
82
+ * equal(await ask(failing('model')), 'model')
83
+ * equal(heard, ['m0', 'm0', 'm0', 'm1'])
84
+ * ```
85
+ */ export let onward = (chain, passed)=>async (req)=>{
86
+ let links = await chain(req);
87
+ for (let [i, link] of links.entries()){
88
+ let begun = false;
89
+ try {
90
+ return await link.model({
91
+ ...req,
92
+ model: link.name,
93
+ onFirst: ()=>{
94
+ begun = true;
95
+ req.onFirst?.();
96
+ },
97
+ onText: req.onText && ((text)=>{
98
+ begun = true;
99
+ req.onText(text);
100
+ })
101
+ });
102
+ } catch (error) {
103
+ req.signal?.throwIfAborted();
104
+ if (!refused(error) || begun || i == links.length - 1) throw error;
105
+ passed?.(link.name, error);
106
+ }
107
+ }
108
+ throw new ModelError('provider', 'No model answers this step');
109
+ };
110
+ //# sourceMappingURL=onward.js.map
package/onward.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"onward.js","sources":["./onward.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,6EAA6E;AAC7E,2EAA2E;AAC3E,kDAAkD;AAClD,SAAS,GAAG,sBAAqB;AACjC,SAAqB,UAAU,mBAAgC;AAE/D,sEAAsE;AACtE,mEAAmE;AACnE,yEAAyE;AACzE,8CAA8C;AAC9C,IAAI,OAAO,IAAI,IAAI;EAAC;EAAS;CAAkB;AAE/C;;;;;;;;;;;;CAYC,GACD,OAAO,IAAI,OAAO,CAAC,QACjB,iBAAiB,cAAc,KAAK,GAAG,CAAC,MAAM,IAAI,EAAC;AAErD;;;;;;;;;;;;;;;;;;;CAmBC,GACD,OAAO,IAAI,UAAU,CAAC,QACpB,KAAK,UAAU,iBAAiB,cAC9B,CAAC,IAAI,UAAU,MAAM,IAAI,IAAI,eAAe,EAAC;AAKjD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqCC,GACD,OAAO,IAAI,SAAS,CAClB,OACA,SAEF,OAAO;IACL,IAAI,QAAQ,MAAM,MAAM;IACxB,KAAK,IAAI,CAAC,GAAG,KAAK,IAAI,MAAM,OAAO,GAAI;MACrC,IAAI,QAAQ;MACZ,IAAI;QACF,OAAO,MAAM,KAAK,KAAK,CAAC;UACtB,GAAG,GAAG;UACN,OAAO,KAAK,IAAI;UAChB,SAAS;YACP,QAAQ;YACR,IAAI,OAAO;UACb;UACA,QAAQ,IAAI,MAAM,IAAI,CAAC,CAAC;YACtB,QAAQ;YACR,IAAI,MAAM,CAAE;UACd,CAAC;QACH;MACF,EAAE,OAAO,OAAO;QACd,IAAI,MAAM,EAAE;QACZ,IAAI,CAAC,QAAQ,UAAU,SAAS,KAAK,MAAM,MAAM,GAAG,GAAG,MAAM;QAC7D,SAAS,KAAK,IAAI,EAAE;MACtB;IACF;IACA,MAAM,IAAI,WAAW,YAAY;EACnC,EAAC"}
package/onward.ts ADDED
@@ -0,0 +1,123 @@
1
+ // A step asked of a chain of models: where the provider refuses it, because
2
+ // the model asked is retired or is none it knows, or because its own account
3
+ // has nothing left to spend, or because its credential is unavailable, the
4
+ // step goes on to the next model the chain names.
5
+ import { dry } from './limits.js'
6
+ import { type Model, ModelError, type Request } from './mod.js'
7
+
8
+ // The codes a provider's "no such model" is heard as: `model` where a
9
+ // provider package names it so (@yaks/workers-ai, @yaks/anthropic,
10
+ // @yaks/openai's own door), and OpenAI's own `model_not_found`, which an
11
+ // OpenAI-compatible API passes on as it came.
12
+ let GONE = new Set(['model', 'model_not_found'])
13
+
14
+ /**
15
+ * Whether `error` is a provider saying it has no model by the name asked: one
16
+ * it retired, or one it never had.
17
+ *
18
+ * ```ts
19
+ * import { gone, ModelError } from '@yaks/model'
20
+ * import { equal } from '@yaks/testing'
21
+ * equal(gone(new ModelError('model', '5028: m was deprecated')), true)
22
+ * equal(gone(new ModelError('model_not_found')), true)
23
+ * equal(gone(new ModelError('busy')), false)
24
+ * equal(gone(new Error('model')), false)
25
+ * ```
26
+ */
27
+ export let gone = (error: unknown): error is ModelError =>
28
+ error instanceof ModelError && GONE.has(error.code)
29
+
30
+ /**
31
+ * Whether `error` is a provider declining to run the request at all: the
32
+ * model asked is {@link gone}, or the provider's own account is dry (@yaks/model
33
+ * `dry`: its spend limit, billing quota, credit or plan window used up), or
34
+ * the request has no credential. A
35
+ * refused request ran nothing, so it costs nothing and another provider may
36
+ * take it. A caller's own ceiling (`limit`) is no refusal: every provider
37
+ * would meet it.
38
+ *
39
+ * ```ts
40
+ * import { ModelError, refused } from '@yaks/model'
41
+ * import { equal } from '@yaks/testing'
42
+ * equal(refused(new ModelError('model')), true)
43
+ * equal(refused(new ModelError('project_spend_limit_exceeded')), true)
44
+ * equal(refused(new ModelError('credit')), true)
45
+ * equal(refused(new ModelError('no_credential')), true)
46
+ * equal(refused(new ModelError('limit')), false)
47
+ * equal(refused(new ModelError('busy')), false)
48
+ * ```
49
+ */
50
+ export let refused = (error: unknown): error is ModelError =>
51
+ gone(error) || error instanceof ModelError &&
52
+ (dry(error) || error.code == 'no_credential')
53
+
54
+ /** One model of a chain: what asks it, and the name it is asked by. */
55
+ export type Link = { model: Model; name: string }
56
+
57
+ /**
58
+ * A model that asks `chain(req)` in order: the first link answers the step,
59
+ * and a link {@link refused} before producing output passes the step to the
60
+ * next, even where the provider acknowledged the request first. `passed`
61
+ * hears each such failure with the name it was asked by. Other failures are
62
+ * thrown as they came.
63
+ *
64
+ * ```ts
65
+ * import { type Model, ModelError, onward } from '@yaks/model'
66
+ * import { equal } from '@yaks/testing'
67
+ * let failing = (code: string): Model => () => Promise.reject(new ModelError(code))
68
+ * let acked = (code: string): Model => async (req) => {
69
+ * await req.onAck?.({ p: { id: 'r' } })
70
+ * throw new ModelError(code)
71
+ * }
72
+ * let started = (code: string): Model => (req) => {
73
+ * req.onFirst?.()
74
+ * return Promise.reject(new ModelError(code))
75
+ * }
76
+ * let ok: Model = (req) =>
77
+ * Promise.resolve({ id: 'r', model: req.model, items: [] })
78
+ * let heard: string[] = []
79
+ * let chain = (links: Model[]) => () =>
80
+ * links.map((model, i) => ({ model, name: 'm' + i }))
81
+ * let ask = (...links: Model[]) =>
82
+ * onward(chain(links), (name) => heard.push(name))(
83
+ * { model: 'm0', items: [], tools: [] },
84
+ * ).then((r) => r.model, (e) => e.code)
85
+ * equal(await ask(failing('model'), ok), 'm1')
86
+ * equal(await ask(acked('project_spend_limit_exceeded'), ok), 'm1')
87
+ * equal(await ask(failing('credit'), failing('model'), ok), 'm2')
88
+ * equal(await ask(failing('busy'), ok), 'busy')
89
+ * equal(await ask(failing('limit'), ok), 'limit')
90
+ * equal(await ask(started('credit'), ok), 'credit')
91
+ * equal(await ask(failing('model')), 'model')
92
+ * equal(heard, ['m0', 'm0', 'm0', 'm1'])
93
+ * ```
94
+ */
95
+ export let onward = (
96
+ chain: (req: Request) => Link[] | Promise<Link[]>,
97
+ passed?: (name: string, error: ModelError) => void,
98
+ ): Model =>
99
+ async (req) => {
100
+ let links = await chain(req)
101
+ for (let [i, link] of links.entries()) {
102
+ let begun = false
103
+ try {
104
+ return await link.model({
105
+ ...req,
106
+ model: link.name,
107
+ onFirst: () => {
108
+ begun = true
109
+ req.onFirst?.()
110
+ },
111
+ onText: req.onText && ((text) => {
112
+ begun = true
113
+ req.onText!(text)
114
+ }),
115
+ })
116
+ } catch (error) {
117
+ req.signal?.throwIfAborted()
118
+ if (!refused(error) || begun || i == links.length - 1) throw error
119
+ passed?.(link.name, error)
120
+ }
121
+ }
122
+ throw new ModelError('provider', 'No model answers this step')
123
+ }
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@yaks/model",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.36",
4
+ "homepage": "https://jsr.io/@yaks/model",
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
+ "./batch": {
16
+ "types": "./_dist/batch.d.ts",
17
+ "default": "./batch.js"
18
+ },
19
+ "./graph": {
20
+ "types": "./_dist/graph.d.ts",
21
+ "default": "./graph.js"
22
+ },
23
+ "./sse": {
24
+ "types": "./_dist/sse.d.ts",
25
+ "default": "./sse.js"
26
+ },
27
+ "./stall": {
28
+ "types": "./_dist/stall.d.ts",
29
+ "default": "./stall.js"
30
+ },
31
+ "./step": {
32
+ "types": "./_dist/step.d.ts",
33
+ "default": "./step.js"
34
+ },
35
+ "./route": {
36
+ "types": "./_dist/route.d.ts",
37
+ "default": "./route.js"
38
+ },
39
+ "./image": {
40
+ "types": "./_dist/image.d.ts",
41
+ "default": "./image.js"
42
+ }
43
+ },
44
+ "license": "Apache-2.0",
45
+ "dependencies": {
46
+ "@yaks/blob": "0.2.36",
47
+ "@yaks/edge": "0.2.36",
48
+ "@yaks/fp": "0.2.36",
49
+ "@yaks/graph": "0.2.36",
50
+ "@yaks/query": "0.2.36",
51
+ "@yaks/vocab": "0.2.36"
52
+ },
53
+ "description": "Defines provider-neutral model request and reply types, vocabulary for providers and models, and helpers for billing and recovering generated media. Implements no provider's transport, but decodes the server-sent events providers stream and carries one model step from one host to another's providers.",
54
+ "repository": "https://github.com/yak-sh/yak.git"
55
+ }
package/prices.js ADDED
@@ -0,0 +1,61 @@
1
+ // What a model costs at its vendor's list price, and what a person sees it
2
+ // called, by the name a request gives it, so a graph that meets a model for
3
+ // the first time can weigh what it spent and name it. The table is data,
4
+ // regenerated by bin/prices.ts from OpenRouter's public listing; a `price` or
5
+ // `label` on the model's own row is what a graph uses.
6
+ import table from './prices.json' with {
7
+ type: 'json'
8
+ };
9
+ let PRICES = table.prices;
10
+ let LABELS = table.labels;
11
+ // What a name may carry beyond the model's own: a context window in brackets
12
+ // (`claude-opus-4-8[1m]`), then a release date (`claude-haiku-4-5-20251001`,
13
+ // `gpt-4o-2024-08-06`).
14
+ let EXTRA = [
15
+ /\[[^\]]*\]$/,
16
+ /-\d{8}$/,
17
+ /-\d{4}-\d{2}-\d{2}$/
18
+ ];
19
+ // The entry `list` holds for the model `name` names, shed of what it carries
20
+ // beyond the model's own.
21
+ let listed = (list, name)=>{
22
+ let at = name;
23
+ for (let extra of [
24
+ /^/,
25
+ ...EXTRA
26
+ ]){
27
+ at = at.replace(extra, '');
28
+ if (Object.hasOwn(list, at)) return list[at];
29
+ }
30
+ return undefined;
31
+ };
32
+ /**
33
+ * The list price of the model a request names, if the table holds it.
34
+ *
35
+ * ```ts
36
+ * import { listPrice } from '@yaks/model'
37
+ * import { assertEquals } from '@std/assert'
38
+ *
39
+ * assertEquals(listPrice('claude-haiku-4-5-20251001'), listPrice('claude-haiku-4-5'))
40
+ * assertEquals(listPrice('no-such-model'), undefined)
41
+ * ```
42
+ */ export let listPrice = (name)=>listed(PRICES, name);
43
+ /**
44
+ * What the table calls the model a request names, its window said after it,
45
+ * if the table holds it.
46
+ *
47
+ * ```ts
48
+ * import { listLabel } from '@yaks/model'
49
+ * import { assertEquals } from '@std/assert'
50
+ *
51
+ * assertEquals(listLabel('claude-sonnet-5-5'), 'Sonnet 5.5')
52
+ * assertEquals(listLabel('claude-opus-4-8[1m]'), 'Opus 4.8 1M')
53
+ * assertEquals(listLabel('gpt-6.2-sol'), 'GPT-6.2 Sol')
54
+ * assertEquals(listLabel('no-such-model'), undefined)
55
+ * ```
56
+ */ export let listLabel = (name)=>{
57
+ let label = listed(LABELS, name);
58
+ let window = name.match(/\[([^\]]*)\]$/)?.[1];
59
+ return label && (window ? `${label} ${window.toUpperCase()}` : label);
60
+ };
61
+ //# sourceMappingURL=prices.js.map
package/prices.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prices.js","sources":["./prices.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,4EAA4E;AAC5E,yEAAyE;AACzE,8EAA8E;AAC9E,uDAAuD;AAEvD,OAAO,WAAW,qBAAqB;EAAE,MAAM;AAAO,EAAC;AAGvD,IAAI,SAAgC,MAAM,MAAM;AAChD,IAAI,SAAiC,MAAM,MAAM;AAEjD,6EAA6E;AAC7E,6EAA6E;AAC7E,wBAAwB;AACxB,IAAI,QAAQ;EAAC;EAAe;EAAW;CAAsB;AAE7D,6EAA6E;AAC7E,0BAA0B;AAC1B,IAAI,SAAS,CAAI,MAAyB;EACxC,IAAI,KAAK;EACT,KAAK,IAAI,SAAS;IAAC;OAAQ;GAAM,CAAE;IACjC,KAAK,GAAG,OAAO,CAAC,OAAO;IACvB,IAAI,OAAO,MAAM,CAAC,MAAM,KAAK,OAAO,IAAI,CAAC,GAAG;EAC9C;EACA,OAAO;AACT;AAEA;;;;;;;;;;CAUC,GACD,OAAO,IAAI,YAAY,CAAC,OAAoC,OAAO,QAAQ,MAAK;AAEhF;;;;;;;;;;;;;CAaC,GACD,OAAO,IAAI,YAAY,CAAC;EACtB,IAAI,QAAQ,OAAO,QAAQ;EAC3B,IAAI,SAAS,KAAK,KAAK,CAAC,kBAAkB,CAAC,EAAE;EAC7C,OAAO,SAAS,CAAC,SAAS,GAAG,MAAM,CAAC,EAAE,OAAO,WAAW,IAAI,GAAG,KAAK;AACtE,EAAC"}