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

files-source.test.ts

109 lines2.8 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 adapter,
48 messages: [
49 {
50 role: 'user',
51 content: [
52 { type: 'text', content: 'describe' },
53 {
54 type: 'image',
55 source: {
56 type: 'file',
57 value: 'file_anthropic_123',
58 provider: 'anthropic',
59 },
60 },
61 ],
62 },
63 ],
64 }),
65 )
66​
67 const [payload] = mocks.betaMessagesCreate.mock.calls[0]!
68 const userMsg = payload.messages.at(-1)
69 const imageBlock = userMsg.content.find((b: any) => b.type === 'image')
70 expect(imageBlock.source).toEqual({
71 type: 'file',
72 file_id: 'file_anthropic_123',
73 })
74 expect(payload.betas).toContain('files-api-2025-04-14')
75 })
76​
77 it('errors when a foreign provider file handle reaches the anthropic adapter', async () => {
78 mockEmptyStream()
79 const adapter = new AnthropicTextAdapter({ apiKey: 'k' }, 'claude-opus-4-1')
80​
81 const chunks: Array<StreamChunk> = []
82 for await (const chunk of chat({
83 adapter,
84 messages: [
85 {
86 role: 'user',
87 content: [
88 {
89 type: 'image',
90 source: {
91 type: 'file',
92 value: 'file-openai-1',
93 provider: 'openai',
94 },
95 },
96 ],
97 },
98 ],
99 })) {
100 chunks.push(chunk)
101 }
102​
103 const runError = chunks.find((c) => c.type === 'RUN_ERROR')
104 expect(runError).toBeDefined()
105 if (runError?.type === 'RUN_ERROR') {
106 expect(runError.message).toMatch(/anthropic/)
107 }
108 })
109})