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

evaluate.ts

158 lines4.8 KB

1import { BaseEvaluateAdapter } from '@tanstack/ai/adapters'
2import type { EvaluateOptions } from '@tanstack/ai/adapters'
3import type { TokenUsage, WireAnswer } from '@tanstack/ai'
4import { resolveOllayaTransport } from '../utils/client'
5import type { OllayaClientConfig } from '../utils/client'
6import type { OllayaEvaluateModel } from '../model-meta'
7​
8/** Shape of the Ollaya `POST /v1/systemone` response we depend on. */
9interface OllayaEvaluateResponse {
10 model: string
11 answers: Record<string, WireAnswer>
12 usage: { input_tokens: number; output_tokens: number }
14​
15function isRecord(value: unknown): value is Record<string, unknown> {
16 return typeof value === 'object' && value !== null && !Array.isArray(value)
18​
19function isOllayaEvaluateResponse(
20 value: unknown,
21): value is OllayaEvaluateResponse {
22 if (!isRecord(value)) return false
23 const usage = value['usage']
24 const answers = value['answers']
25 return (
26 typeof value['model'] === 'string' &&
27 isRecord(answers) &&
28 isRecord(usage) &&
29 typeof usage['input_tokens'] === 'number' &&
30 typeof usage['output_tokens'] === 'number'
31 )
33​
34/**
35 * Ollaya evaluate adapter.
36 *
37 * Talks to a local Ollaya server's `POST /v1/systemone` endpoint over raw
38 * `fetch` — no SDK. Ollaya serves the `laya` decision models and speaks the
39 * same wire contract as TypeSafe's Jev, so the `decide()` activity maps the
40 * returned wire answers to the unified public result.
41 */
42export class OllayaEvaluateAdapter<
43 TModel extends OllayaEvaluateModel,
44> extends BaseEvaluateAdapter<TModel> {
45 readonly name = 'ollaya' as const
46​
47 private readonly apiKey: string | undefined
48 private readonly baseUrl: string
49 private readonly headers: Record<string, string>
50 private readonly fetchFn: typeof fetch | undefined
51​
52 constructor(config: OllayaClientConfig, model: TModel) {
53 super({}, model)
54 this.apiKey = config.apiKey
55 const transport = resolveOllayaTransport(config)
56 this.baseUrl = transport.baseUrl
57 this.headers = transport.headers
58 this.fetchFn = config.fetch
59 }
60​
61 /**
62 * POST `{ model, state, questions }` to Ollaya and return wire answers plus
63 * mapped token usage. Does not invent unified `.value` fields.
64 */
65 async evaluate(options: EvaluateOptions) {
66 const { model, state, questions, abortSignal, logger } = options
67 const body = { model, state, questions }
68 const fetchFn = this.fetchFn ?? globalThis.fetch
69​
70 logger.request(`activity=evaluate provider=${this.name} model=${model}`, {
71 provider: this.name,
72 model,
73 })
74​
75 let response: Response
76 try {
77 response = await fetchFn(`${this.baseUrl}/v1/systemone`, {
78 method: 'POST',
79 headers: {
80 'Content-Type': 'application/json',
81 // ponytail: local Ollaya needs no key; only send auth behind a proxy
82 ...(this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : {}),
83 ...this.headers,
84 },
85 body: JSON.stringify(body),
86 ...(abortSignal ? { signal: abortSignal } : {}),
87 })
88 } catch (error) {
89 logger.errors(`${this.name}.evaluate fatal`, {
90 error,
91 source: `${this.name}.evaluate`,
92 })
93 throw error
94 }
95​
96 if (!response.ok) {
97 const detail = await response.text().catch(() => '')
98 const error = new Error(
99 `Ollaya evaluate request failed: ${response.status} ${response.statusText}${
100 detail ? ` — ${detail}` : ''
101 }`,
102 )
103 logger.errors(`${this.name}.evaluate fatal`, {
104 error,
105 source: `${this.name}.evaluate`,
106 })
107 throw error
108 }
109​
110 const json: unknown = await response.json()
111 if (!isOllayaEvaluateResponse(json)) {
112 throw new Error('Ollaya evaluate response had an unexpected shape')
113 }
114​
115 const promptTokens = json.usage.input_tokens
116 const completionTokens = json.usage.output_tokens
117 const usage: TokenUsage = {
118 promptTokens,
119 completionTokens,
120 totalTokens: promptTokens + completionTokens,
121 }
122​
123 return {
124 model: json.model,
125 answers: json.answers,
126 usage,
127 }
128 }
130​
131/**
132 * Creates an Ollaya evaluate adapter.
133 *
134 * @example
135 * ```typescript
136 * import { decide, boolean } from '@tanstack/ai'
137 * import { ollayaDecider } from '@tanstack/ai-ollaya'
138 *
139 * const result = await decide({
140 * adapter: ollayaDecider('laya:latest'),
141 * state: ticket,
142 * questions: {
143 * refund: boolean({
144 * instructions: 'Is the customer asking for a refund?',
145 * }),
146 * },
147 * })
148 * ```
149 *
150 * Talks to `http://127.0.0.1:11435` by default. Point it elsewhere with
151 * `ollayaDecider('laya:latest', { baseURL: 'http://my-host:11435' })`.
152 */
153export function ollayaDecider<TModel extends OllayaEvaluateModel>(
154 model: TModel,
155 config?: OllayaClientConfig,
156) {
157 return new OllayaEvaluateAdapter({ ...config }, model)