-
Notifications
You must be signed in to change notification settings - Fork 3.3k
feat(provider/anthropic): add return file_id property for anthropic code-execution-20250825 to download output files
#9669
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
lgrammel
merged 16 commits into
vercel:main
from
tsuzaki430:tsuz/anthropic-code-execute-file-id
Oct 23, 2025
+7,053
−0
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
958952b
add file_id result in code execution
tsuzaki430 6a3c9a7
aicore test
tsuzaki430 c32ca2b
next-openai add download route and ui
tsuzaki430 df4c78f
prettier-fix
tsuzaki430 7216bcd
add test data
tsuzaki430 ce3841a
add test file-id array
tsuzaki430 ac01e5a
snap
tsuzaki430 6722fce
changeset
tsuzaki430 458f19f
Merge remote-tracking branch 'origin/main' into tsuz/anthropic-code-e…
tsuzaki430 9a666e6
fix test
tsuzaki430 83287b1
fix test
tsuzaki430 5ec447b
fix wrong test expect
tsuzaki430 a77de49
cs
lgrammel 8750958
remove the examples from the changeset
tsuzaki430 0716080
Merge branch 'tsuz/anthropic-code-execute-file-id' of https://github.…
tsuzaki430 2db503f
Merge branch 'main' into tsuz/anthropic-code-execute-file-id
lgrammel File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| '@ai-sdk/anthropic': patch | ||
| --- | ||
|
|
||
| add return `file_id` property for anthropic code-execution-20250825 to download output files. |
108 changes: 108 additions & 0 deletions
108
examples/ai-core/src/generate-text/anthropic-code-execution-20250825-downloads.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| import { anthropic } from '@ai-sdk/anthropic'; | ||
| import { generateText } from 'ai'; | ||
| import { run } from '../lib/run'; | ||
| import * as fs from 'fs'; | ||
|
|
||
| run(async () => { | ||
| const result = await generateText({ | ||
| model: anthropic('claude-sonnet-4-5'), | ||
| prompt: | ||
| 'Write a Python script to calculate fibonacci number' + | ||
| ' and then execute it to find the 10th fibonacci number' + | ||
| ' finally output data to excel file and python code.', | ||
| tools: { | ||
| code_execution: anthropic.tools.codeExecution_20250825(), | ||
| }, | ||
| }); | ||
|
|
||
| console.dir(result.content, { depth: Infinity }); | ||
|
|
||
| const fileIdList = result.staticToolResults.flatMap(t => { | ||
| if ( | ||
| t.toolName === 'code_execution' && | ||
| t.output.type === 'bash_code_execution_result' | ||
| ) { | ||
| return t.output.content.map(o => o.file_id); | ||
| } | ||
| return []; | ||
| }); | ||
|
|
||
| await Promise.all(fileIdList.map(fileId => downloadFile(fileId))); | ||
| }); | ||
|
|
||
| async function downloadFile(file: string) { | ||
| try { | ||
| const apiKey = process.env.ANTHROPIC_API_KEY; | ||
|
|
||
| if (!apiKey) { | ||
| throw new Error('ANTHROPIC_API_KEY is not set'); | ||
| } | ||
| const infoUrl = `https://api.anthropic.com/v1/files/${file}`; | ||
| const infoPromise = fetch(infoUrl, { | ||
| method: 'GET', | ||
| headers: { | ||
| 'x-api-key': apiKey, | ||
| 'anthropic-version': '2023-06-01', | ||
| 'anthropic-beta': 'files-api-2025-04-14', | ||
| }, | ||
| }); | ||
|
|
||
| const downloadUrl = `https://api.anthropic.com/v1/files/${file}/content`; | ||
| const downloadPromise = fetch(downloadUrl, { | ||
| method: 'GET', | ||
| headers: { | ||
| 'x-api-key': apiKey, | ||
| 'anthropic-version': '2023-06-01', | ||
| 'anthropic-beta': 'files-api-2025-04-14', | ||
| }, | ||
| }); | ||
|
|
||
| const [infoResponse, downloadResponse] = await Promise.all([ | ||
| infoPromise, | ||
| downloadPromise, | ||
| ]); | ||
|
|
||
| if (!infoResponse.ok) { | ||
| throw new Error( | ||
| `HTTP Error: ${infoResponse.status} ${infoResponse.statusText}`, | ||
| ); | ||
| } | ||
|
|
||
| const { | ||
| filename, | ||
| }: { | ||
| type: 'file'; | ||
| id: string; | ||
| size_bytes: number; | ||
| created_at: Date; | ||
| filename: string; | ||
| mime_type: string; | ||
| downloadable?: boolean; | ||
| } = await infoResponse.json(); | ||
|
|
||
| if (!downloadResponse.ok) { | ||
| throw new Error( | ||
| `HTTP Error: ${downloadResponse.status} ${downloadResponse.statusText}`, | ||
| ); | ||
| } | ||
|
|
||
| // get as binary data | ||
| const arrayBuffer = await downloadResponse.arrayBuffer(); | ||
| const buffer = Buffer.from(arrayBuffer); | ||
|
|
||
| const outputPath = `output/${filename}`; | ||
|
|
||
| fs.writeFileSync(outputPath, buffer); | ||
|
|
||
| console.log(`file saved: ${outputPath}`); | ||
| console.log(`file size: ${buffer.length} bytes`); | ||
|
|
||
| return { | ||
| path: outputPath, | ||
| size: buffer.length, | ||
| }; | ||
| } catch (error) { | ||
| console.error('error:', error); | ||
| throw error; | ||
| } | ||
| } |
136 changes: 136 additions & 0 deletions
136
examples/ai-core/src/stream-text/anthropic-code-execution-20250825-downloads.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| import { anthropic } from '@ai-sdk/anthropic'; | ||
| import { streamText } from 'ai'; | ||
| import { run } from '../lib/run'; | ||
| import * as fs from 'fs'; | ||
|
|
||
| run(async () => { | ||
| const result = streamText({ | ||
| model: anthropic('claude-sonnet-4-5'), | ||
| prompt: | ||
| 'Write a Python script to calculate fibonacci number' + | ||
| ' and then execute it to find the 10th fibonacci number' + | ||
| ' finally output data to excel file and python code.', | ||
| tools: { | ||
| code_execution: anthropic.tools.codeExecution_20250825(), | ||
| }, | ||
| }); | ||
|
|
||
| for await (const part of result.fullStream) { | ||
| switch (part.type) { | ||
| case 'text-delta': { | ||
| process.stdout.write(part.text); | ||
| break; | ||
| } | ||
|
|
||
| case 'tool-call': { | ||
| process.stdout.write( | ||
| `\n\nTool call: '${part.toolName}'\nInput: ${JSON.stringify(part.input, null, 2)}\n`, | ||
| ); | ||
| break; | ||
| } | ||
|
|
||
| case 'tool-result': { | ||
| process.stdout.write( | ||
| `\nTool result: '${part.toolName}'\nOutput: ${JSON.stringify(part.output, null, 2)}\n`, | ||
| ); | ||
| break; | ||
| } | ||
|
|
||
| case 'error': { | ||
| console.error('\n\nCode execution error:', part.error); | ||
| break; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| process.stdout.write('\n\n'); | ||
|
|
||
| const fileIdList = (await result.staticToolResults).flatMap(t => { | ||
| if ( | ||
| t.toolName === 'code_execution' && | ||
| t.output.type === 'bash_code_execution_result' | ||
| ) { | ||
| return t.output.content.map(o => o.file_id); | ||
| } | ||
| return []; | ||
| }); | ||
|
|
||
| await Promise.all(fileIdList.map(fileId => downloadFile(fileId))); | ||
| }); | ||
|
|
||
| async function downloadFile(file: string) { | ||
| try { | ||
| const apiKey = process.env.ANTHROPIC_API_KEY; | ||
|
|
||
| if (!apiKey) { | ||
| throw new Error('ANTHROPIC_API_KEY is not set'); | ||
| } | ||
| const infoUrl = `https://api.anthropic.com/v1/files/${file}`; | ||
| const infoPromise = fetch(infoUrl, { | ||
| method: 'GET', | ||
| headers: { | ||
| 'x-api-key': apiKey, | ||
| 'anthropic-version': '2023-06-01', | ||
| 'anthropic-beta': 'files-api-2025-04-14', | ||
| }, | ||
| }); | ||
|
|
||
| const downloadUrl = `https://api.anthropic.com/v1/files/${file}/content`; | ||
| const downloadPromise = fetch(downloadUrl, { | ||
| method: 'GET', | ||
| headers: { | ||
| 'x-api-key': apiKey, | ||
| 'anthropic-version': '2023-06-01', | ||
| 'anthropic-beta': 'files-api-2025-04-14', | ||
| }, | ||
| }); | ||
|
|
||
| const [infoResponse, downloadResponse] = await Promise.all([ | ||
| infoPromise, | ||
| downloadPromise, | ||
| ]); | ||
|
|
||
| if (!infoResponse.ok) { | ||
| throw new Error( | ||
| `HTTP Error: ${infoResponse.status} ${infoResponse.statusText}`, | ||
| ); | ||
| } | ||
|
|
||
| const { | ||
| filename, | ||
| }: { | ||
| type: 'file'; | ||
| id: string; | ||
| size_bytes: number; | ||
| created_at: Date; | ||
| filename: string; | ||
| mime_type: string; | ||
| downloadable?: boolean; | ||
| } = await infoResponse.json(); | ||
|
|
||
| if (!downloadResponse.ok) { | ||
| throw new Error( | ||
| `HTTP Error: ${downloadResponse.status} ${downloadResponse.statusText}`, | ||
| ); | ||
| } | ||
|
|
||
| // get as binary data | ||
| const arrayBuffer = await downloadResponse.arrayBuffer(); | ||
| const buffer = Buffer.from(arrayBuffer); | ||
|
|
||
| const outputPath = `output/${filename}`; | ||
|
|
||
| fs.writeFileSync(outputPath, buffer); | ||
|
|
||
| console.log(`file saved: ${outputPath}`); | ||
| console.log(`file size: ${buffer.length} bytes`); | ||
|
|
||
| return { | ||
| path: outputPath, | ||
| size: buffer.length, | ||
| }; | ||
| } catch (error) { | ||
| console.error('error:', error); | ||
| throw error; | ||
| } | ||
| } |
89 changes: 89 additions & 0 deletions
89
examples/next-openai/app/api/code-execution-files/anthropic/[file]/route.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| import 'dotenv/config'; | ||
|
|
||
| const dynamic = 'force-dynamic'; | ||
|
|
||
| const execute = async ( | ||
| _req: Request, | ||
| { | ||
| params, | ||
| }: { | ||
| params: Promise<{ | ||
| file: string; | ||
| }>; | ||
| }, | ||
| ) => { | ||
| const { file } = await params; | ||
|
|
||
| const apiKey = process.env.ANTHROPIC_API_KEY; | ||
|
|
||
| if (!apiKey) { | ||
| throw new Error('ANTHROPIC_API_KEY is not set'); | ||
| } | ||
|
|
||
| const infoUrl = `https://api.anthropic.com/v1/files/${file}`; | ||
| const infoPromise = fetch(infoUrl, { | ||
| method: 'GET', | ||
| headers: { | ||
| 'x-api-key': apiKey, | ||
| 'anthropic-version': '2023-06-01', | ||
| 'anthropic-beta': 'files-api-2025-04-14', | ||
| }, | ||
| }); | ||
|
|
||
| const downloadUrl = `https://api.anthropic.com/v1/files/${file}/content`; | ||
| const downloadPromise = fetch(downloadUrl, { | ||
| method: 'GET', | ||
| headers: { | ||
| 'x-api-key': apiKey, | ||
| 'anthropic-version': '2023-06-01', | ||
| 'anthropic-beta': 'files-api-2025-04-14', | ||
| }, | ||
| }); | ||
|
|
||
| const [infoResponse, downloadResponse] = await Promise.all([ | ||
| infoPromise, | ||
| downloadPromise, | ||
| ]); | ||
|
|
||
| if (!infoResponse.ok) { | ||
| throw new Error( | ||
| `HTTP Error: ${infoResponse.status} ${infoResponse.statusText}`, | ||
| ); | ||
| } | ||
|
|
||
| if (!downloadResponse.ok) { | ||
| throw new Error( | ||
| `HTTP Error: ${downloadResponse.status} ${downloadResponse.statusText}`, | ||
| ); | ||
| } | ||
|
|
||
| // https://github.com/anthropics/anthropic-sdk-typescript/blob/main/src/resources/beta/files.ts | ||
| const { | ||
| filename, | ||
| size_bytes, | ||
| }: { | ||
| type: 'file'; | ||
| id: string; | ||
| size_bytes: number; | ||
| created_at: Date; | ||
| filename: string; | ||
| mime_type: string; | ||
| downloadable?: boolean; | ||
| } = await infoResponse.json(); | ||
|
|
||
| // get as binary data | ||
| const arrayBuffer = await downloadResponse.arrayBuffer(); | ||
| const buffer = Buffer.from(arrayBuffer); | ||
|
|
||
| return new Response(buffer, { | ||
| status: 200, | ||
| headers: { | ||
| 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(filename)}`, | ||
| 'Content-Type': 'application/octet-stream', | ||
| 'Content-Length': size_bytes.toString(), | ||
| 'X-File-Name': encodeURIComponent(filename), | ||
| }, | ||
| }); | ||
| }; | ||
|
|
||
| export { dynamic, execute as GET, execute as POST }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.