AGI围城
首页
基础知识
工程实践
所见所思
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

AGI围城

是的,这个世界还是很有趣的。
首页
基础知识
工程实践
所见所思
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • 提示词工程

  • 大模型API调用

  • OpenAI工具

    • 1. 文件检索
    • 2. 代码解释器
      • 2.1 核心概念
      • 2.2 上传文件
      • 2.3 助手创建并关联
      • 2.4 创建对话线程
      • 2.5 运行助手并获取结果
    • 3. 函数调用
  • 嵌入向量

  • 检索增强生成(RAG)

  • 基础知识
  • OpenAI工具
xiao_sl
2025-09-05
目录

2. 代码解释器

# 2.1 核心概念

代码解释器是基于沙盒环境的 Python 代码执行工具,它能够将自然语言指令转换成 Python 代码并自动运行,进而实现数学计算、数据分析、文件处理、数据可视化等任务。其内置代码调试与迭代修正能力,显著提升复杂问题的解决效率和准确性。

# 2.2 上传文件

将待分析文件上传至 OpenAI:

# 上传数据文件(如 Excel)
file = client.files.create(
    file=open("代码解释器测试数据.xlsx", "rb"),
    purpose='assistants'  # 必须指定用途为 assistants
)
1
2
3
4
5

# 2.3 助手创建并关联

通过配置 code_interpreter 工具创建专用助手,并关联数据文件:

from openai import OpenAI
import time

client = OpenAI()

# 创建助手(绑定代码解释器工具)
assistant = client.beta.assistants.create(
    name="代码解释器助手测试",
    instructions="你是一个代码解释器助手,请根据用户的问题与提供的相关资料给出专业的回答",
    model="gpt-4o",
    tools=[{"type": "code_interpreter"}],  # 启用代码解释器
    tool_resources={
        "code_interpreter": {
            "file_ids": [file.id]  # 关联数据文件(需提前上传)
        }
    }
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 2.4 创建对话线程

在用户消息中附加文件,并声明使用代码解释器工具:

# 创建对话线程并附加文件
thread = client.beta.threads.create(
    messages=[
        {
            "role": "user",
            "content": "我希望你帮我计算一下这个表格中姓李的人的平均薪资",
            "attachments": [
                {
                    "file_id": file.id,  # 关联文件到当前对话
                    "tools": [{"type": "code_interpreter"}]  # 指定工具类型
                }
            ]
        }
    ]
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 2.5 运行助手并获取结果

启动代码执行任务,轮询状态直至完成:

# 启动任务运行
run = client.beta.threads.runs.create(
    thread_id=thread.id,
    assistant_id=assistant.id
)

# 轮询检查运行状态
while True:
    run_status = client.beta.threads.runs.retrieve(thread_id=thread.id, run_id=run.id)
    if run_status.status in ["completed", "failed"]:
        break
    time.sleep(1)

# 提取并打印结果
messages = client.beta.threads.messages.list(thread_id=thread.id)
for message in messages.data:
    print(f"{message.role}: {message.content}")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
编辑 (opens new window)
#OpenAI工具
上次更新: 2025/09/18, 08:16:15
1. 文件检索
3. 函数调用

← 1. 文件检索 3. 函数调用→

最近更新
01
2. 朴素RAG
09-17
02
1. RAG基本概念
09-13
03
4. 向量相关参考资料
09-12
更多文章>
Theme by Vdoing | Copyright © 2019-2025 AGI围城 | 桂ICP备2024034950号 | 桂公网安备45142202000030
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式