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