-
Notifications
You must be signed in to change notification settings - Fork 3.2k
feat(openai): support retrieval for code interpreter generated files #9899
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
aayush-kapoor
merged 20 commits into
main
from
aayush/9175-retrieve-code-interpreter-file
Nov 3, 2025
Merged
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
c4d8860
failingn tests
aayush-kapoor 6649d7b
fixes
aayush-kapoor 6d6a756
cs
aayush-kapoor 871c625
updated example
aayush-kapoor 8060103
Merge branch 'main' into aayush/9175-retrieve-code-interpreter-file
aayush-kapoor da3c30b
grammar fix
aayush-kapoor 82679e2
Merge branch 'main' into aayush/9175-retrieve-code-interpreter-file
aayush-kapoor 8e22f9d
Merge branch 'main' into aayush/9175-retrieve-code-interpreter-file
aayush-kapoor 9dca93f
updating tests to use real repsonses/fixtures
aayush-kapoor ad918d9
pretty
aayush-kapoor a3135a4
new ui example
aayush-kapoor 8030968
api mismatch fix
aayush-kapoor 3c4e95f
pretty
aayush-kapoor 006df57
Merge branch 'main' into aayush/9175-retrieve-code-interpreter-file
aayush-kapoor 9d7f500
Merge branch 'main' into aayush/9175-retrieve-code-interpreter-file
gr2m d35dc87
Merge branch 'main' into aayush/9175-retrieve-code-interpreter-file
aayush-kapoor 060dbaf
test snapshots updated
aayush-kapoor fb217aa
var + langauge change
aayush-kapoor 20b82f4
Merge branch 'main' into aayush/9175-retrieve-code-interpreter-file
aayush-kapoor 996ea11
Merge branch 'main' into aayush/9175-retrieve-code-interpreter-file
aayush-kapoor 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/openai': patch | ||
| --- | ||
|
|
||
| feat(openai): support openai code-interpreter annotations |
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
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
91 changes: 91 additions & 0 deletions
91
examples/next-openai/app/api/chat-openai-code-interpreter-annotation-download/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,91 @@ | ||
| import { openai, OpenAIResponsesProviderOptions } from '@ai-sdk/openai'; | ||
| import { | ||
| convertToModelMessages, | ||
| InferUITools, | ||
| streamText, | ||
| ToolSet, | ||
| UIDataTypes, | ||
| UIMessage, | ||
| validateUIMessages, | ||
| } from 'ai'; | ||
|
|
||
| const tools = { | ||
| code_interpreter: openai.tools.codeInterpreter(), | ||
| } satisfies ToolSet; | ||
|
|
||
| export type OpenAICodeInterpreterMessage = UIMessage< | ||
| { | ||
| downloadLinks?: Array<{ | ||
| filename: string; | ||
| url: string; | ||
| }>; | ||
| }, | ||
| UIDataTypes, | ||
| InferUITools<typeof tools> | ||
| >; | ||
|
|
||
| export async function POST(req: Request) { | ||
| const { messages } = await req.json(); | ||
| const uiMessages = await validateUIMessages({ messages }); | ||
|
|
||
| // Collect sources with container file citations as they're generated | ||
| const containerFileSources: Array<{ | ||
| containerId: string; | ||
| fileId: string; | ||
| filename: string; | ||
| }> = []; | ||
|
|
||
| const result = streamText({ | ||
| model: openai('gpt-5-nano'), | ||
| tools, | ||
| messages: convertToModelMessages(uiMessages), | ||
| onStepFinish: async ({ sources, request }) => { | ||
| console.log(JSON.stringify(request.body, null, 2)); | ||
|
|
||
| // Collect container file citations from sources | ||
| for (const source of sources) { | ||
| if ( | ||
| source.sourceType === 'document' && | ||
| source.providerMetadata?.openai?.containerId && | ||
| source.providerMetadata?.openai?.fileId | ||
| ) { | ||
| const containerId = String( | ||
| source.providerMetadata.openai.containerId || '', | ||
| ); | ||
| const fileId = String(source.providerMetadata.openai.fileId || ''); | ||
| const filename = source.filename || source.title || 'file'; | ||
|
|
||
| // Avoid duplicates | ||
| const exists = containerFileSources.some( | ||
| s => s.containerId === containerId && s.fileId === fileId, | ||
| ); | ||
| if (!exists) { | ||
| containerFileSources.push({ containerId, fileId, filename }); | ||
| } | ||
| } | ||
| } | ||
| }, | ||
| providerOptions: { | ||
| openai: { | ||
| store: true, | ||
| } satisfies OpenAIResponsesProviderOptions, | ||
| }, | ||
| }); | ||
|
|
||
| return result.toUIMessageStreamResponse({ | ||
| originalMessages: uiMessages, | ||
| messageMetadata: ({ part }) => { | ||
| // When streaming finishes, create download links from collected sources | ||
| if (part.type === 'finish' && containerFileSources.length > 0) { | ||
| const downloadLinks = containerFileSources.map(source => ({ | ||
| filename: source.filename, | ||
| url: `/api/download-container-file?container_id=${encodeURIComponent(source.containerId)}&file_id=${encodeURIComponent(source.fileId)}&filename=${encodeURIComponent(source.filename)}`, | ||
| })); | ||
|
|
||
| return { | ||
| downloadLinks, | ||
| }; | ||
| } | ||
| }, | ||
| }); | ||
| } |
46 changes: 46 additions & 0 deletions
46
examples/next-openai/app/api/download-container-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,46 @@ | ||
| export async function GET(req: Request) { | ||
| const { searchParams } = new URL(req.url); | ||
| const containerId = searchParams.get('container_id'); | ||
| const fileId = searchParams.get('file_id'); | ||
| const filename = searchParams.get('filename') || 'file'; | ||
|
|
||
| if (!containerId || !fileId) { | ||
| return new Response('Missing container_id or file_id', { status: 400 }); | ||
| } | ||
|
|
||
| const apiKey = process.env.OPENAI_API_KEY; | ||
| if (!apiKey) { | ||
| return new Response('OPENAI_API_KEY not configured', { status: 500 }); | ||
| } | ||
|
|
||
| try { | ||
| const response = await fetch( | ||
| `https://api.openai.com/v1/containers/${containerId}/files/${fileId}/content`, | ||
| { | ||
| headers: { | ||
| Authorization: `Bearer ${apiKey}`, | ||
| }, | ||
| }, | ||
| ); | ||
|
|
||
| if (!response.ok) { | ||
| return new Response(`Failed to fetch file: ${response.statusText}`, { | ||
| status: response.status, | ||
| }); | ||
| } | ||
|
|
||
| const arrayBuffer = await response.arrayBuffer(); | ||
| const contentType = | ||
| response.headers.get('content-type') || 'application/octet-stream'; | ||
|
|
||
| return new Response(arrayBuffer, { | ||
| headers: { | ||
| 'Content-Type': contentType, | ||
| 'Content-Disposition': `attachment; filename="${filename}"`, | ||
| }, | ||
| }); | ||
| } catch (error) { | ||
| console.error('Error downloading file:', error); | ||
| return new Response('Error downloading file', { status: 500 }); | ||
| } | ||
| } | ||
53 changes: 53 additions & 0 deletions
53
examples/next-openai/app/test-openai-code-interpreter-annotation-download/page.tsx
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,53 @@ | ||
| 'use client'; | ||
|
|
||
| import { useChat } from '@ai-sdk/react'; | ||
| import { DefaultChatTransport } from 'ai'; | ||
| import ChatInput from '@/components/chat-input'; | ||
| import { OpenAICodeInterpreterMessage } from '@/app/api/chat-openai-code-interpreter-annotation-download/route'; | ||
| import CodeInterpreterView from '@/components/tool/openai-code-interpreter-view'; | ||
|
|
||
| export default function TestOpenAIWebSearch() { | ||
| const { status, sendMessage, messages } = | ||
| useChat<OpenAICodeInterpreterMessage>({ | ||
| transport: new DefaultChatTransport({ | ||
| api: '/api/chat-openai-code-interpreter-annotation-download', | ||
| }), | ||
| }); | ||
|
|
||
| return ( | ||
| <div className="flex flex-col py-24 mx-auto w-full max-w-md stretch"> | ||
| <h1 className="mb-4 text-xl font-bold">OpenAI Code Interpreter Test</h1> | ||
|
|
||
| {messages.map(message => ( | ||
| <div key={message.id} className="whitespace-pre-wrap"> | ||
| {message.role === 'user' ? 'User: ' : 'AI: '} | ||
| {message.parts.map((part, index) => { | ||
| switch (part.type) { | ||
| case 'text': | ||
| return <div key={index}>{part.text}</div>; | ||
| case 'tool-code_interpreter': | ||
| return <CodeInterpreterView key={index} invocation={part} />; | ||
| } | ||
| })} | ||
| {message.metadata?.downloadLinks && | ||
| message.metadata.downloadLinks.length > 0 && ( | ||
| <div className="mt-2 space-y-1"> | ||
| {message.metadata.downloadLinks.map((link, idx) => ( | ||
| <a | ||
| key={idx} | ||
| href={link.url} | ||
| download={link.filename} | ||
| className="text-blue-600 hover:underline block" | ||
| > | ||
| 📥 Download {link.filename} | ||
| </a> | ||
| ))} | ||
| </div> | ||
| )} | ||
| </div> | ||
| ))} | ||
|
|
||
| <ChatInput status={status} onSubmit={text => sendMessage({ text })} /> | ||
| </div> | ||
| ); | ||
| } |
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
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.