Open History to see the last commit
1import OpenAI from 'openai'
2import { buildBaseUsage } from '@tanstack/ai'
3import {
4 BaseEvaluateAdapter,
5 EVALUATE_REFUSAL_CODE,
6 EvaluateError,
7} from '@tanstack/ai/adapters'
8import { toRunErrorPayload } from '@tanstack/ai/adapter-internals'
9import { getOpenAIApiKeyFromEnv } from '../utils/client'
10import type {
11 EvaluateOptions,
12 WireAnswer,
13 WireQuestion,
14} from '@tanstack/ai/adapters'
15import type { Decision, DecisionCreateParams } from 'openai/resources/decisions'
16import type { OpenAIClientConfig } from '../utils/client'
17
18/** Models served by the OpenAI Decisions API. */
19export const OPENAI_EVALUATE_MODELS = ['gpt-6-luna'] as const
20
21export type OpenAIEvaluateModel =
22 | (typeof OPENAI_EVALUATE_MODELS)[number]
23 | (string & {})
24
25/**
26 * Configuration for OpenAI evaluate adapter
27 */
28export interface OpenAIEvaluateConfig extends OpenAIClientConfig {}
29
30type DecisionQuestion = DecisionCreateParams['questions'][number]
31type DecisionAnswer = Decision['answers'][number]
32
33function toText(value: unknown): string {
34 return typeof value === 'string' ? value : JSON.stringify(value)
35}
36
37function toDecisionQuestion(
38 name: string,
39 question: WireQuestion,
40): DecisionQuestion {
41 const instructions = toText(question.instructions)
42 switch (question.type) {
43 case 'choice':
44 return {
45 type: 'choice',
46 name,
47 instructions,
48 choices: Object.entries(question.criteria).map(
49 ([value, description]) => ({
50 value,
51 ...(description !== null && { description }),
52 }),
53 ),
54 }
55 case 'score':
56 return {
57 type: 'score',
58 name,
59 instructions,
60 levels: question.criteria.map((label) => ({ label })),
61 }
62 case 'noul': {
63 // OpenAI predicates have no criteria field, so fold the yes/no meanings
64 // into the instructions.
65 const hints = [
66 question.criteria?.true && `True means: ${question.criteria.true}`,
67 question.criteria?.false && `False means: ${question.criteria.false}`,
68 ].filter(Boolean)
69 return {
70 type: 'predicate',
71 name,
72 instructions: [instructions, ...hints].join('\n'),
73 }
74 }
75 }
76}
77
78function toWireAnswer(answer: DecisionAnswer): WireAnswer | undefined {
79 switch (answer.type) {
80 case 'predicate':
81 return { type: 'noul', noul: answer.probability }
82 case 'choice':
83 return {
84 type: 'choice',
85 choice: String(answer.choice),
86 probabilities: Object.fromEntries(
87 answer.probabilities.map((p) => [String(p.value), p.probability]),
88 ),
89 confidence: answer.confidence,
90 }
91 case 'score':
92 return {
93 type: 'score',
94 score: answer.score,
95 legend: Object.fromEntries(
96 answer.probabilities.map((p) => [String(p.value), p.label]),
97 ),
98 probabilities: Object.fromEntries(
99 answer.probabilities.map((p) => [String(p.value), p.probability]),
100 ),
101 confidence: answer.confidence,
102 }
103 case 'refusal':
104 return undefined
105 }
106}
107
108/**
109 * OpenAI evaluate adapter.
110 *
111 * Asks typed questions about a shared `state` through the OpenAI Decisions
112 * API (`/v1/decisions`). Returns TypeSafe wire answers; `decide()` maps those
113 * to the public shape.
114 */
115export class OpenAIEvaluateAdapter<
116 TModel extends OpenAIEvaluateModel,
117> extends BaseEvaluateAdapter<TModel> {
118 readonly name = 'openai' as const
119
120 protected client: OpenAI
121
122 constructor(config: OpenAIEvaluateConfig, model: TModel) {
123 super({}, model)
124 this.client = new OpenAI(config)
125 }
126
127 async evaluate(options: EvaluateOptions) {
128 const { model, state, questions, abortSignal, logger } = options
129 const questionKeys = Object.keys(questions)
130
131 logger.request(
132 `activity=evaluate provider=${this.name} model=${model} questions=${questionKeys.length}`,
133 { provider: this.name, model },
134 )
135
136 try {
137 const decision = await this.client.decisions.create(
138 {
139 model,
140 input: toText(state),
141 questions: Object.entries(questions).map(([name, question]) =>
142 toDecisionQuestion(name, question),
143 ),
144 },
145 abortSignal ? { signal: abortSignal } : undefined,
146 )
147
148 // Answers come back in question order. `name` is null only for
149 // unnamed questions, and we always send names. Object.fromEntries keeps
150 // a question named "__proto__" as an own key.
151 const refused: Array<string> = []
152 const answers: Record<string, WireAnswer> = Object.fromEntries(
153 decision.answers.flatMap((answer, index) => {
154 const name = answer.name ?? questionKeys[index] ?? String(index)
155 const wire = toWireAnswer(answer)
156 if (!wire) {
157 refused.push(name)
158 return []
159 }
160 return [[name, wire]]
161 }),
162 )
163 const usage = buildBaseUsage({
164 promptTokens: decision.usage.input_tokens,
165 completionTokens: decision.usage.output_tokens,
166 totalTokens: decision.usage.total_tokens,
167 })
168
169 if (refused.length > 0) {
170 throw new EvaluateError({
171 message: `OpenAI declined to answer question "${refused[0]}"`,
172 code: EVALUATE_REFUSAL_CODE,
173 usage,
174 model: decision.model,
175 answers,
176 })
177 }
178
179 return { model: decision.model, answers, usage }
180 } catch (error) {
181 // toRunErrorPayload keeps request headers (and the API key) out of logs.
182 logger.errors(`${this.name}.evaluate fatal`, {
183 error: toRunErrorPayload(error, `${this.name}.evaluate failed`),
184 source: `${this.name}.evaluate`,
185 })
186 throw error
187 }
188 }
189}
190
191/**
192 * Creates an OpenAI evaluate adapter with an explicit API key.
193 *
194 * @param model Decisions model, for example `'gpt-6-luna'`.
195 * @param apiKey OpenAI API key.
196 * @param config Optional OpenAI client options.
197 *
198 * @example
199 * ```typescript
200 * const adapter = createOpenaiDecider('gpt-6-luna', 'sk-...')
201 * ```
202 */
203export function createOpenaiDecider<TModel extends OpenAIEvaluateModel>(
204 model: TModel,
205 apiKey: string,
206 config?: Omit<OpenAIEvaluateConfig, 'apiKey'>,
207) {
208 return new OpenAIEvaluateAdapter({ apiKey, ...config }, model)
209}
210
211/**
212 * Creates an OpenAI evaluate adapter, reading `OPENAI_API_KEY` from the
213 * environment.
214 *
215 * @param model Decisions model, for example `'gpt-6-luna'`.
216 * @param config Optional OpenAI client options.
217 *
218 * @example
219 * ```typescript
220 * import { decide, choice } from '@tanstack/ai'
221 * import { openaiDecider } from '@tanstack/ai-openai'
222 *
223 * const result = await decide({
224 * adapter: openaiDecider('gpt-6-luna'),
225 * state: ticket,
226 * questions: {
227 * queue: choice({
228 * instructions: 'Which team should handle this ticket?',
229 * options: {
230 * billing: 'Payments, invoices, refunds',
231 * tech: 'Bugs, outages, integrations',
232 * },
233 * }),
234 * },
235 * })
236 * ```
237 */
238export function openaiDecider<TModel extends OpenAIEvaluateModel>(
239 model: TModel,
240 config?: Omit<OpenAIEvaluateConfig, 'apiKey'>,
241) {
242 return createOpenaiDecider(model, getOpenAIApiKeyFromEnv(), config)
243}