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

files-source.test.ts

111 lines2.9 KB

1import { describe, expect, it, vi } from 'vitest'
2import { chat } from '@tanstack/ai'
3import { AnthropicTextAdapter } from '../src/adapters/text'
4import type { StreamChunk } from '@tanstack/ai'
5​
6const mocks = vi.hoisted(() => {
7 const betaMessagesCreate = vi.fn()
8 const client = { beta: { messages: { create: betaMessagesCreate } } }
9 return { betaMessagesCreate, client }
10})
11​
12vi.mock('@anthropic-ai/sdk', () => {
13 const { client } = mocks
14 class MockAnthropic {
15 beta = client.beta
16 constructor(_: { apiKey: string }) {}
17 }
18 return { default: MockAnthropic }
19})
20​
21function mockEmptyStream() {
22 mocks.betaMessagesCreate.mockResolvedValueOnce(
23 (async function* () {
24 yield {
25 type: 'message_delta',
26 delta: { stop_reason: 'end_turn' },
27 usage: { output_tokens: 1 },
28 }
29 yield { type: 'message_stop' }
30 })(),
31 )
33​
34async function drain(iterable: AsyncIterable<unknown>) {
35 for await (const _ of iterable) {
36 // consume
37 }
39​
40describe('anthropic file content source', () => {
41 it('maps an anthropic file handle to a file_id source and sends the Files beta', async () => {
42 mockEmptyStream()
43 const adapter = new AnthropicTextAdapter({ apiKey: 'k' }, 'claude-opus-4-1')
44​
45 await drain(
46 chat({
47 threadId: 'thread-1',
48 adapter,
49 messages: [
50 {
51 role: 'user',
52 content: [
53 { type: 'text', content: 'describe' },
54 {
55 type: 'image',
56 source: {
57 type: 'file',
58 value: 'file_anthropic_123',
59 provider: 'anthropic',
60 },
61 },
62 ],
63 },
64 ],
65 }),
66 )
67​
68 const [payload] = mocks.betaMessagesCreate.mock.calls[0]!
69 const userMsg = payload.messages.at(-1)
70 const imageBlock = userMsg.content.find((b: any) => b.type === 'image')
71 expect(imageBlock.source).toEqual({
72 type: 'file',
73 file_id: 'file_anthropic_123',
74 })
75 expect(payload.betas).toContain('files-api-2025-04-14')
76 })
77​
78 it('errors when a foreign provider file handle reaches the anthropic adapter', async () => {
79 mockEmptyStream()
80 const adapter = new AnthropicTextAdapter({ apiKey: 'k' }, 'claude-opus-4-1')
81​
82 const chunks: Array<StreamChunk> = []
83 for await (const chunk of chat({
84 threadId: 'thread-1',
85 adapter,
86 messages: [
87 {
88 role: 'user',
89 content: [
90 {
91 type: 'image',
92 source: {
93 type: 'file',
94 value: 'file-openai-1',
95 provider: 'openai',
96 },
97 },
98 ],
99 },
100 ],
101 })) {
102 chunks.push(chunk)
103 }
104​
105 const runError = chunks.find((c) => c.type === 'RUN_ERROR')
106 expect(runError).toBeDefined()
107 if (runError?.type === 'RUN_ERROR') {
108 expect(runError.message).toMatch(/anthropic/)
109 }
110 })
111})