ll-24-25
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Help
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # code-interpreter Assistants Code Interpreter Beta =================================== Based on your feedback from the Assistants API beta, we've incorporated key improvements into the Responses API. After we achieve full feature parity, we will announce a **deprecation plan** later this year, with a target sunset date in the first half of 2026. [Learn more](/docs/guides/responses-vs-chat-completions). Overview -------- Code Interpreter allows Assistants to write and run Python code in a sandboxed execution environment. This tool can process files with diverse data and formatting, and generate files with data and images of graphs. Code Interpreter allows your Assistant to run code iteratively to solve challenging code and math problems. When your Assistant writes code that fails to run, it can iterate on this code by attempting to run different code until the code execution succeeds. See a quickstart of how to get started with Code Interpreter [here](/docs/assistants/overview#step-1-create-an-assistant?context=with-streaming). How it works ------------ Code Interpreter is charged at $0.03 per session. If your Assistant calls Code Interpreter simultaneously in two different threads (e.g., one thread per end-user), two Code Interpreter sessions are created. Each session is active by default for one hour, which means that you only pay for one session per if users interact with Code Interpreter in the same thread for up to one hour. ### Enabling Code Interpreter Pass `code_interpreter` in the `tools` parameter of the Assistant object to enable Code Interpreter: ```python assistant = client.beta.assistants.create( instructions="You are a personal math tutor. When asked a math question, write and run code to answer the question.", model="gpt-4o", tools=[{"type": "code_interpreter"}] ) ``` ```javascript const assistant = await openai.beta.assistants.create({ instructions: "You are a personal math tutor. When asked a math question, write and run code to answer the question.", model: "gpt-4o", tools: [{"type": "code_interpreter"}] }); ``` ```bash curl https://api.openai.com/v1/assistants \ -u :$OPENAI_API_KEY \ -H 'Content-Type: application/json' \ -H 'OpenAI-Beta: assistants=v2' \ -d '{ "instructions": "You are a personal math tutor. When asked a math question, write and run code to answer the question.", "tools": [ { "type": "code_interpreter" } ], "model": "gpt-4o" }' ``` The model then decides when to invoke Code Interpreter in a Run based on the nature of the user request. This behavior can be promoted by prompting in the Assistant's `instructions` (e.g., “write code to solve this problem”). ### Passing files to Code Interpreter Files that are passed at the Assistant level are accessible by all Runs with this Assistant: ```python # Upload a file with an "assistants" purpose file = client.files.create( file=open("mydata.csv", "rb"), purpose='assistants' ) # Create an assistant using the file ID assistant = client.beta.assistants.create( instructions="You are a personal math tutor. When asked a math question, write and run code to answer the question.", model="gpt-4o", tools=[{"type": "code_interpreter"}], tool_resources={ "code_interpreter": { "file_ids": [file.id] } } ) ``` ```javascript // Upload a file with an "assistants" purpose const file = await openai.files.create({ file: fs.createReadStream("mydata.csv"), purpose: "assistants", }); // Create an assistant using the file ID const assistant = await openai.beta.assistants.create({ instructions: "You are a personal math tutor. When asked a math question, write and run code to answer the question.", model: "gpt-4o", tools: [{"type": "code_interpreter"}], tool_resources: { "code_interpreter": { "file_ids": [file.id] } } }); ``` ```bash # Upload a file with an "assistants" purpose curl https://api.openai.com/v1/files \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -F purpose="assistants" \ -F file="@/path/to/mydata.csv" # Create an assistant using the file ID curl https://api.openai.com/v1/assistants \ -u :$OPENAI_API_KEY \ -H 'Content-Type: application/json' \ -H 'OpenAI-Beta: assistants=v2' \ -d '{ "instructions": "You are a personal math tutor. When asked a math question, write and run code to answer the question.", "tools": [{"type": "code_interpreter"}], "model": "gpt-4o", "tool_resources": { "code_interpreter": { "file_ids": ["file-BK7bzQj3FfZFXr7DbL6xJwfo"] } } }' ``` Files can also be passed at the Thread level. These files are only accessible in the specific Thread. Upload the File using the [File upload](/docs/api-reference/files/create) endpoint and then pass the File ID as part of the Message creation request: ```python thread = client.beta.threads.create( messages=[ { "role": "user", "content": "I need to solve the equation `3x + 11 = 14`. Can you help me?", "attachments": [ { "file_id": file.id, "tools": [{"type": "code_interpreter"}] } ] } ] ) ``` ```javascript const thread = await openai.beta.threads.create({ messages: [ { "role": "user", "content": "I need to solve the equation `3x + 11 = 14`. Can you help me?", "attachments": [ { file_id: file.id, tools: [{type: "code_interpreter"}] } ] } ] }); ``` ```bash curl https://api.openai.com/v1/threads/thread_abc123/messages \ -u :$OPENAI_API_KEY \ -H 'Content-Type: application/json' \ -H 'OpenAI-Beta: assistants=v2' \ -d '{ "role": "user", "content": "I need to solve the equation `3x + 11 = 14`. Can you help me?", "attachments": [ { "file_id": "file-ACq8OjcLQm2eIG0BvRM4z5qX", "tools": [{"type": "code_interpreter"}] } ] }' ``` Files have a maximum size of 512 MB. Code Interpreter supports a variety of file formats including `.csv`, `.pdf`, `.json` and many more. More details on the file extensions (and their corresponding MIME-types) supported can be found in the [Supported files](#supported-files) section below. ### Reading images and files generated by Code Interpreter Code Interpreter in the API also outputs files, such as generating image diagrams, CSVs, and PDFs. There are two types of files that are generated: 1. Images 2. Data files (e.g. a `csv` file with data generated by the Assistant) When Code Interpreter generates an image, you can look up and download this file in the `file_id` field of the Assistant Message response: ```json { "id": "msg_abc123", "object": "thread.message", "created_at": 1698964262, "thread_id": "thread_abc123", "role": "assistant", "content": [ { "type": "image_file", "image_file": { "file_id": "file-abc123" } } ] # ... } ``` The file content can then be downloaded by passing the file ID to the Files API: ```python from openai import OpenAI client = OpenAI() image_data = client.files.content("file-abc123") image_data_bytes = image_data.read() with open("./my-image.png", "wb") as file: file.write(image_data_bytes) ``` ```javascript import fs from "fs"; import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const response = await openai.files.content("file-abc123"); // Extract the binary data from the Response object const image_data = await response.arrayBuffer(); // Convert the binary data to a Buffer const image_data_buffer = Buffer.from(image_data); // Save the image to a specific location fs.writeFileSync("./my-image.png", image_data_buffer); } main(); ``` ```bash curl https://api.openai.com/v1/files/file-abc123/content \ -H "Authorization: Bearer $OPENAI_API_KEY" \ --output image.png ``` When Code Interpreter references a file path (e.g., ”Download this csv file”), file paths are listed as annotations. You can convert these annotations into links to download the file: ```json { "id": "msg_abc123", "object": "thread.message", "created_at": 1699073585, "thread_id": "thread_abc123", "role": "assistant", "content": [ { "type": "text", "text": { "value": "The rows of the CSV file have been shuffled and saved to a new CSV file. You can download the shuffled CSV file from the following link:\\n\\n[Download Shuffled CSV File](sandbox:/mnt/data/shuffled_file.csv)", "annotations": [ { "type": "file_path", "text": "sandbox:/mnt/data/shuffled_file.csv", "start_index": 167, "end_index": 202, "file_path": { "file_id": "file-abc123" } } ... ``` ### Input and output logs of Code Interpreter By listing the steps of a Run that called Code Interpreter, you can inspect the code `input` and `outputs` logs of Code Interpreter: ```python run_steps = client.beta.threads.runs.steps.list( thread_id=thread.id, run_id=run.id ) ``` ```javascript const runSteps = await openai.beta.threads.runs.steps.list( thread.id, run.id ); ``` ```bash curl https://api.openai.com/v1/threads/thread_abc123/runs/RUN_ID/steps \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" \ ``` ```bash { "object": "list", "data": [ { "id": "step_abc123", "object": "thread.run.step", "type": "tool_calls", "run_id": "run_abc123", "thread_id": "thread_abc123", "status": "completed", "step_details": { "type": "tool_calls", "tool_calls": [ { "type": "code", "code": { "input": "# Calculating 2 + 2\\nresult = 2 + 2\\nresult", "outputs": [ { "type": "logs", "logs": "4" } ... } ``` Supported files --------------- |File format|MIME type| |---|---| |.c|text/x-c| |.cs|text/x-csharp| |.cpp|text/x-c++| |.csv|text/csv| |.doc|application/msword| |.docx|application/vnd.openxmlformats-officedocument.wordprocessingml.document| |.html|text/html| |.java|text/x-java| |.json|application/json| |.md|text/markdown| |.pdf|application/pdf| |.php|text/x-php| |.pptx|application/vnd.openxmlformats-officedocument.presentationml.presentation| |.py|text/x-python| |.py|text/x-script.python| |.rb|text/x-ruby| |.tex|text/x-tex| |.txt|text/plain| |.css|text/css| |.js|text/javascript| |.sh|application/x-sh| |.ts|application/typescript| |.csv|application/csv| |.jpeg|image/jpeg| |.jpg|image/jpeg| |.gif|image/gif| |.pkl|application/octet-stream| |.png|image/png| |.tar|application/x-tar| |.xlsx|application/vnd.openxmlformats-officedocument.spreadsheetml.sheet| |.xml|application/xml or "text/xml"| |.zip|application/zip|

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully