Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

ollaya.ts

518 lines15.6 KB

1/**
2 * Ollaya — a local server for open decision models (laya, decima, …). It
3 * publishes no OpenAPI document; its normative contract is `docs/api.md` in
4 * ollaya-dev/ollaya. `POST /v1/systemone` is hand-written from §5 and §8.1
5 * there (TypeSafe's wire format, plus Ollaya's array `criteria` and
6 * `ordinal` extensions; no TypeSafe `box` questions or `assets`). The
7 * server runs on the caller's machine, so the server URL is a variable.
8 *
9 * Models come from the public registry: the repo tree names every
10 * `<family>/manifests/<tag>`, and each manifest on ollaya.dev points at a
11 * config blob with the description, context length and release date. No
12 * key; nothing is priced (the models run locally).
13 */
14import { githubRequestInit } from '../github.ts'
15import { cachedDocs, mapConcurrent } from '../model-facts.ts'
16import { fetchJson, fetchText, sha256Text } from '../types.ts'
17import type {
18 ListModelsResult,
19 ModelInfo,
20 OpenApiDocument,
21 ProviderConfig,
22 ProviderConnect,
23 ProviderSecrets,
24 SpecFetchResult,
25} from '../types.ts'
26​
27export const OLLAYA_DOCS_URL =
28 'https://github.com/ollaya-dev/ollaya/blob/main/docs/api.md'
29export const OLLAYA_TREE_URL =
30 'https://api.github.com/repos/ollaya-dev/ollaya/git/trees/main:registry/v2/library?recursive=1'
31export const OLLAYA_CONTRACT_URL =
32 'https://raw.githubusercontent.com/ollaya-dev/ollaya/main/docs/api.md'
33const OLLAYA_REGISTRY = 'https://ollaya.dev/v2/library'
34​
35export const OLLAYA_CONNECT: ProviderConnect = {
36 servers: [
37 {
38 url: '{baseUrl}',
39 description: 'Your Ollaya server (OLLAYA_HOST).',
40 variables: {
41 baseUrl: {
42 default: 'http://127.0.0.1:11435',
43 description:
44 'Origin of the Ollaya server. It runs locally on 127.0.0.1:11435 unless OLLAYA_HOST says otherwise.',
45 },
46 },
47 },
48 ],
49 securitySchemes: {
50 bearerAuth: {
51 type: 'http',
52 scheme: 'bearer',
53 description:
54 'Only checked when the server sets OLLAYA_API_KEY: `Authorization: Bearer <key>`.',
55 },
56 },
57 // Either no auth (the default) or the bearer key.
58 security: [{}, { bearerAuth: [] }],
60​
61type Schema = Record<string, unknown>
62​
63/** string | object | array, as TypeSafe's `x-accepts` spells it. */
64const textLike = (description: string): Schema => ({
65 description,
66 anyOf: [
67 { type: 'string' },
68 { type: 'object', additionalProperties: true },
69 { type: 'array', items: {} },
70 ],
71})
72const optionalTextLike = (description: string): Schema => ({
73 description,
74 anyOf: [
75 { type: 'string' },
76 { type: 'object', additionalProperties: true },
77 { type: 'array', items: {} },
78 { type: 'null' },
79 ],
80})
81​
82const instructions = optionalTextLike(
83 'What the model should decide. Absent or null: the question id is read in its place.',
85​
86const choiceQuestion: Schema = {
87 type: 'object',
88 required: ['type', 'criteria'],
89 properties: {
90 type: { type: 'string', const: 'choice' },
91 instructions,
92 criteria: {
93 description:
94 'Labels, 2–255: an object label → description, or (Ollaya extension) an array of label strings.',
95 anyOf: [
96 {
97 type: 'object',
98 minProperties: 2,
99 maxProperties: 255,
100 additionalProperties: optionalTextLike('When this label applies.'),
101 },
102 {
103 type: 'array',
104 minItems: 2,
105 maxItems: 255,
106 items: { type: 'string' },
107 },
108 ],
109 },
110 ordinal: {
111 type: ['boolean', 'null'],
112 description:
113 'Labels are in order (Ollaya extension, 2–10 labels). Only models with an ordinal head (Decima) accept true; others return 422.',
114 },
115 },
117​
118const scoreQuestion: Schema = {
119 type: 'object',
120 required: ['type', 'criteria'],
121 properties: {
122 type: { type: 'string', const: 'score' },
123 instructions,
124 criteria: {
125 type: 'array',
126 minItems: 2,
127 maxItems: 10,
128 description: 'Level descriptions, level 0 first.',
129 items: textLike('One level.'),
130 },
131 },
133​
134const noulQuestion: Schema = {
135 type: 'object',
136 required: ['type'],
137 properties: {
138 type: { type: 'string', const: 'noul' },
139 instructions,
140 criteria: {
141 description:
142 'Optional descriptions of when the statement is true or false.',
143 anyOf: [
144 {
145 type: 'object',
146 properties: {
147 true: optionalTextLike('When the statement holds.'),
148 false: optionalTextLike('When it does not.'),
149 },
150 },
151 { type: 'null' },
152 ],
153 },
154 },
156​
157const question: Schema = {
158 oneOf: [
159 { $ref: '#/components/schemas/ChoiceQuestion' },
160 { $ref: '#/components/schemas/ScoreQuestion' },
161 { $ref: '#/components/schemas/NoulQuestion' },
162 ],
163 discriminator: {
164 propertyName: 'type',
165 mapping: {
166 choice: '#/components/schemas/ChoiceQuestion',
167 score: '#/components/schemas/ScoreQuestion',
168 noul: '#/components/schemas/NoulQuestion',
169 },
170 },
172​
173const systemOneRequest: Schema = {
174 type: 'object',
175 required: ['model', 'state', 'questions'],
176 properties: {
177 model: {
178 type: 'string',
179 minLength: 1,
180 description:
181 'Model name, `[namespace/]model[:tag]`, e.g. `laya` (= `laya:latest`) or `laya:en`. Must be pulled on the server.',
182 },
183 state: textLike(
184 'The content every question is about. At most 65,536 tokens; a state that does not fit the model context is 422 STATE_TRUNCATED.',
185 ),
186 questions: {
187 type: 'object',
188 minProperties: 1,
189 maxProperties: 256,
190 description: 'Question id → question, answered in this order.',
191 additionalProperties: { $ref: '#/components/schemas/Question' },
192 },
193 },
195​
196const probabilities: Schema = {
197 type: 'object',
198 additionalProperties: { type: 'number' },
200​
201const choiceAnswer: Schema = {
202 type: 'object',
203 required: ['type', 'choice', 'confidence', 'probabilities'],
204 properties: {
205 type: { type: 'string', const: 'choice' },
206 choice: { type: 'string', description: 'The most probable label.' },
207 confidence: { type: 'number', minimum: 0, maximum: 1 },
208 probabilities: { ...probabilities, description: 'Label → probability.' },
209 },
211​
212const scoreAnswer: Schema = {
213 type: 'object',
214 required: ['type', 'score', 'confidence', 'legend', 'probabilities'],
215 properties: {
216 type: { type: 'string', const: 'score' },
217 score: {
218 type: 'number',
219 description: 'Expected level Σ i·pᵢ; can fall between levels.',
220 },
221 confidence: { type: 'number', minimum: 0, maximum: 1 },
222 legend: {
223 type: 'object',
224 description: 'Level ("0", "1", …) → its description, verbatim.',
225 additionalProperties: {},
226 },
227 probabilities: { ...probabilities, description: 'Level → probability.' },
228 },
230​
231const noulAnswer: Schema = {
232 type: 'object',
233 required: ['type', 'noul'],
234 properties: {
235 type: { type: 'string', const: 'noul' },
236 noul: {
237 type: 'number',
238 minimum: 0,
239 maximum: 1,
240 description: 'Probability that the statement holds.',
241 },
242 },
244​
245const systemOneResponse: Schema = {
246 type: 'object',
247 required: ['model', 'answers', 'usage'],
248 properties: {
249 model: {
250 type: 'string',
251 description:
252 'Canonical name of the model that answered (a router reports its target, e.g. `laya:en`).',
253 },
254 answers: {
255 type: 'object',
256 description: 'Question id → answer, in question order.',
257 additionalProperties: {
258 oneOf: [
259 { $ref: '#/components/schemas/ChoiceAnswer' },
260 { $ref: '#/components/schemas/ScoreAnswer' },
261 { $ref: '#/components/schemas/NoulAnswer' },
262 ],
263 discriminator: {
264 propertyName: 'type',
265 mapping: {
266 choice: '#/components/schemas/ChoiceAnswer',
267 score: '#/components/schemas/ScoreAnswer',
268 noul: '#/components/schemas/NoulAnswer',
269 },
270 },
271 },
272 },
273 usage: {
274 type: 'object',
275 required: ['input_tokens', 'output_tokens'],
276 properties: {
277 input_tokens: { type: 'integer', minimum: 0 },
278 output_tokens: { type: 'integer', const: 0 },
279 },
280 },
281 },
283​
284const errorBody: Schema = {
285 type: 'object',
286 required: ['error', 'code'],
287 properties: {
288 error: { type: 'string', description: 'Human-readable; do not parse.' },
289 code: {
290 type: 'string',
291 description:
292 'UPPER_SNAKE_CASE, e.g. MODEL_NOT_FOUND, INVALID_REQUEST, STATE_TRUNCATED. The set is open.',
293 },
294 detail: {
295 type: 'array',
296 description:
297 'Validation issues (422 only), in TypeSafe `ValidationError` shape.',
298 items: {
299 type: 'object',
300 required: ['loc', 'msg', 'type'],
301 properties: {
302 loc: {
303 type: 'array',
304 items: { anyOf: [{ type: 'string' }, { type: 'integer' }] },
305 },
306 msg: { type: 'string' },
307 type: { type: 'string' },
308 ctx: { type: 'object', additionalProperties: true },
309 },
310 },
311 },
312 },
314​
315const errorResponse = (description: string) => ({
316 description,
317 content: {
318 'application/json': { schema: { $ref: '#/components/schemas/ErrorBody' } },
319 },
320})
321​
322export function ollayaSpec(): OpenApiDocument {
323 return {
324 openapi: '3.1.0',
325 info: { title: 'Ollaya', version: 'docs/api.md' },
326 paths: {
327 '/v1/systemone': {
328 post: {
329 operationId: 'systemone',
330 summary: 'Answer typed questions about a state',
331 description:
332 'TypeSafe System One, wire-identical. Choice, score and noul questions; no implicit model pull.',
333 requestBody: {
334 required: true,
335 content: {
336 'application/json': {
337 schema: { $ref: '#/components/schemas/SystemOneRequest' },
338 },
339 },
340 },
341 responses: {
342 '200': {
343 description: 'One answer per question.',
344 content: {
345 'application/json': {
346 schema: { $ref: '#/components/schemas/SystemOneResponse' },
347 },
348 },
349 },
350 '400': errorResponse('Body is not a JSON object (INVALID_JSON).'),
351 '401': errorResponse(
352 'OLLAYA_API_KEY is set and the key is missing.',
353 ),
354 '404': errorResponse(
355 'Model not pulled on this server (MODEL_NOT_FOUND).',
356 ),
357 '422': errorResponse(
358 'Validation failed; `detail` lists every issue.',
359 ),
360 '503': errorResponse(
361 'Queue full (QUEUE_FULL); retry after Retry-After.',
362 ),
363 },
364 },
365 },
366 },
367 components: {
368 schemas: {
369 SystemOneRequest: systemOneRequest,
370 Question: question,
371 ChoiceQuestion: choiceQuestion,
372 ScoreQuestion: scoreQuestion,
373 NoulQuestion: noulQuestion,
374 SystemOneResponse: systemOneResponse,
375 ChoiceAnswer: choiceAnswer,
376 ScoreAnswer: scoreAnswer,
377 NoulAnswer: noulAnswer,
378 ErrorBody: errorBody,
379 },
380 },
381 }
383​
384/**
385 * The source hash is the contract's own text, so an edit to docs/api.md
386 * shows as a new source revision even though the schemas are hand-written.
387 */
388async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
389 const contract = await fetchText(OLLAYA_CONTRACT_URL)
390 return {
391 specs: [ollayaSpec()],
392 sources: [{ url: OLLAYA_DOCS_URL, hash: await sha256Text(contract) }],
393 outputStrategy: 'post-200',
394 }
396​
397function isRecord(value: unknown): value is Record<string, unknown> {
398 return typeof value === 'object' && value !== null && !Array.isArray(value)
400​
401const PRECISION_PIN = /-fp(16|32)$/
402​
403/**
404 * `family:tag` names from the registry tree. Digest copies (`sha256-…`) are
405 * not tags, and a precision pin (`en-fp32`) is its base tag's weights with
406 * one graph, so it is listed only when the base tag is missing.
407 */
408export function registryTags(tree: unknown): Array<string> {
409 const entries = isRecord(tree) ? tree.tree : undefined
410 if (!Array.isArray(entries))
411 throw new Error('ollaya: registry tree has no entries')
412 if (isRecord(tree) && tree.truncated === true) {
413 throw new Error('ollaya: registry tree is truncated')
414 }
415 const names = new Set<string>()
416 for (const entry of entries) {
417 if (!isRecord(entry) || entry.type !== 'blob') continue
418 const match = /^([^/]+)\/manifests\/([^/]+)$/.exec(String(entry.path))
419 if (!match?.[1] || !match[2] || match[2].startsWith('sha256-')) continue
420 names.add(`${match[1]}:${match[2]}`)
421 }
422 const tags = [...names].filter((name) => {
423 const base = name.replace(PRECISION_PIN, '')
424 return base === name || !names.has(base)
425 })
426 if (tags.length === 0) throw new Error('ollaya: registry tree lists no tags')
427 return tags.sort()
429​
430/** One registry config blob → a catalog row. */
431export function parseOllayaConfig(rawId: string, config: unknown): ModelInfo {
432 if (!isRecord(config))
433 throw new Error(`ollaya: ${rawId} config is not an object`)
434 const bad = (field: string) =>
435 new Error(`ollaya: ${rawId} config.${field} is unreadable`)
436 // Absent is unstated; a router states 0 (no context of its own).
437 const context = config.context_length ?? 0
438 if (
439 typeof context !== 'number' ||
440 !Number.isInteger(context) ||
441 context < 0
442 ) {
443 throw bad('context_length')
444 }
445 let releasedAt: number | null = null
446 if (config.release_date != null) {
447 const released =
448 typeof config.release_date === 'string'
449 ? Date.parse(config.release_date)
450 : Number.NaN
451 if (!Number.isFinite(released)) throw bad('release_date')
452 releasedAt = Math.floor(released / 1000)
453 }
454 const source = config.source ?? ''
455 if (typeof source !== 'string') throw bad('source')
456 const hf = /^huggingface\.co\/([^/@]+\/[^/@]+)/.exec(source)
457 return {
458 rawId,
459 displayName: null,
460 activity: 'decision',
461 contextWindow: context > 0 ? context : null,
462 releasedAt,
463 openWeights: hf ? true : null,
464 weightsUrl: hf ? `https://huggingface.co/${hf[1]}` : null,
465 providerMetadata: config,
466 }
468​
469async function loadRegistry(env: ProviderSecrets): Promise<Array<ModelInfo>> {
470 const tags = registryTags(
471 await fetchJson(OLLAYA_TREE_URL, githubRequestInit(OLLAYA_TREE_URL, env)),
472 )
473 const configs = new Map<string, Promise<unknown>>()
474 // ponytail: one manifest fetch per tag (~120) plus one per distinct
475 // config, on a cache miss only. A registry index endpoint would make it one.
476 return mapConcurrent(tags, 6, async (rawId) => {
477 const [family, tag] = rawId.split(':')
478 const manifest = await fetchJson(
479 `${OLLAYA_REGISTRY}/${family}/manifests/${tag}`,
480 )
481 const config = isRecord(manifest) ? manifest.config : undefined
482 const urls: unknown = isRecord(config) ? config.urls : undefined
483 const url: unknown = Array.isArray(urls) ? urls[0] : undefined
484 if (typeof url !== 'string') {
485 throw new Error(`ollaya: ${rawId} manifest has no config url`)
486 }
487 let blob = configs.get(url)
488 if (!blob) {
489 blob = fetchJson(url)
490 configs.set(url, blob)
491 }
492 return parseOllayaConfig(rawId, await blob)
493 })
495​
496async function listModels(
497 env: ProviderSecrets,
498 kv?: KVNamespace,
499): Promise<ListModelsResult> {
500 return {
501 models: await cachedDocs(kv, OLLAYA_TREE_URL, () => loadRegistry(env)),
502 }
504​
505export const provider: ProviderConfig = {
506 id: 'ollaya',
507 displayName: 'Ollaya',
508 specSourceUrl: OLLAYA_DOCS_URL,
509 modelsEndpoint: OLLAYA_TREE_URL,
510 defaultDerivation: 'docs-derived',
511 connect: OLLAYA_CONNECT,
512 openModelNames: true,
513 fetchSpec,
514 listModels,
515 classify: (path) => (path === '/v1/systemone' ? 'decision' : null),
516 generationEndpointId: ({ activity }) =>
517 activity === 'decision' ? 'v1/systemone' : null,