Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import OpenAI from 'openai'
3import { EventType } from '@tanstack/ai'
4import { resolveDebugOption } from '@tanstack/ai/adapter-internals'
5import { OpenAICompatibleChatAdapter } from '../src/compatible/adapter'
6import type { AdapterYieldChunk } from '@tanstack/ai'
7
8const testLogger = resolveDebugOption(false)
9
10function createAsyncIterable<T>(chunks: Array<T>): AsyncIterable<T> {
11 return {
12 [Symbol.asyncIterator]() {
13 let index = 0
14 return {
15 async next() {
16 if (index < chunks.length) {
17 return { value: chunks[index++]!, done: false }
18 }
19 return { value: undefined as T, done: true }
20 },
21 }
22 },
23 }
24}
25
26function makeAdapter(streamChunks: Array<Record<string, unknown>>) {
27 const client = new OpenAI({ apiKey: 'test-api-key' })
28 client.chat.completions.create = vi
29 .fn()
30 .mockResolvedValue(
31 createAsyncIterable(streamChunks),
32 ) as typeof client.chat.completions.create
33 return new OpenAICompatibleChatAdapter(
34 client,
35 'deepseek-reasoner',
36 'deepseek',
37 )
38}
39
40async function collect(streamChunks: Array<Record<string, unknown>>) {
41 const adapter = makeAdapter(streamChunks)
42 const chunks: Array<AdapterYieldChunk> = []
43 for await (const chunk of adapter.chatStream({
44 threadId: 'thread-1',
45 logger: testLogger,
46 model: 'deepseek-reasoner',
47 messages: [{ role: 'user', content: 'What is 2 + 2?' }],
48 })) {
49 chunks.push(chunk)
50 }
51 return chunks
52}
53
54function reasoningText(chunks: Array<AdapterYieldChunk>) {
55 return chunks
56 .filter(
57 (chunk): chunk is Extract<AdapterYieldChunk, { delta: string }> =>
58 chunk.type === EventType.REASONING_MESSAGE_CONTENT,
59 )
60 .map((chunk) => chunk.delta)
61 .join('')
62}
63
64/**
65 * Issue #982: an OpenAI-compatible reasoning provider streams its thinking on
66 * `delta.reasoning_content` (or `delta.reasoning`), which is outside the OpenAI
67 * wire format. The generic adapter had no reasoning hook, so the thinking was
68 * dropped and the documented workaround was to monkey-patch the prototype.
69 */
70describe('OpenAICompatibleChatAdapter reasoning', () => {
71 const textChunks = [
72 { choices: [{ index: 0, delta: { content: '4' } }] },
73 { choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] },
74 ]
75
76 it('streams reasoning delivered as reasoning_content', async () => {
77 const chunks = await collect([
78 { choices: [{ index: 0, delta: { reasoning_content: 'Two plus two' } }] },
79 { choices: [{ index: 0, delta: { reasoning_content: ' is four.' } }] },
80 ...textChunks,
81 ])
82
83 expect(
84 chunks.some((chunk) => chunk.type === EventType.REASONING_START),
85 ).toBe(true)
86 expect(reasoningText(chunks)).toBe('Two plus two is four.')
87 })
88
89 it('streams reasoning delivered as reasoning', async () => {
90 const chunks = await collect([
91 { choices: [{ index: 0, delta: { reasoning: 'Thinking...' } }] },
92 ...textChunks,
93 ])
94
95 expect(reasoningText(chunks)).toBe('Thinking...')
96 })
97
98 it('prefers reasoning_content when a provider sends both', async () => {
99 const chunks = await collect([
100 {
101 choices: [
102 {
103 index: 0,
104 delta: { reasoning_content: 'canonical', reasoning: 'duplicate' },
105 },
106 ],
107 },
108 ...textChunks,
109 ])
110
111 expect(reasoningText(chunks)).toBe('canonical')
112 })
113
114 it('emits no reasoning events for a provider that sends neither field', async () => {
115 const chunks = await collect(textChunks)
116
117 expect(
118 chunks.some(
119 (chunk) =>
120 chunk.type === EventType.REASONING_START ||
121 chunk.type === EventType.REASONING_MESSAGE_CONTENT,
122 ),
123 ).toBe(false)
124 expect(
125 chunks.some((chunk) => chunk.type === EventType.TEXT_MESSAGE_CONTENT),
126 ).toBe(true)
127 })
128
129 it('skips a usage chunk that has no choices field', async () => {
130 // Some gateways omit `choices` on the usage trailer.
131 const chunks = await collect([
132 ...textChunks,
133 { usage: { prompt_tokens: 3, completion_tokens: 1, total_tokens: 4 } },
134 ])
135
136 expect(chunks.find((c) => c.type === EventType.RUN_ERROR)).toBeUndefined()
137 expect(chunks.find((c) => c.type === EventType.RUN_FINISHED)).toMatchObject(
138 {
139 usage: { totalTokens: 4 },
140 },
141 )
142 })
143})