如何在Jupyter Notebook中运行GPT API命令且无需合并多行字符串参数
Jupyter Notebook中运行多行JSON参数的GPT API curl命令方案
以下几种方法可以避免将JSON合并为单行,同时保证命令正常执行:
方法1:给JSON内的每行末尾加反斜杠转义
在JSON的每一行末尾添加反斜杠,让shell正确识别多行结构:
!curl https://api.openai.com/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ \ "model": "gpt-3.5-turbo", \ "messages": [{"role": "user", "content": "Say this is a test!"}], \ "temperature": 0.7 \ }'
方法2:用Python变量存储格式化后的JSON
先在Notebook中定义Python变量存储结构化的JSON数据,再转换为字符串传递给curl,兼顾可读性和可维护性:
import json # 定义结构化的请求体 payload = { "model": "gpt-3.5-turbo", "messages": [{"role": "user", "content": "Say this is a test!"}], "temperature": 0.7 } # 转换为JSON字符串 payload_json = json.dumps(payload)
接着执行curl命令:
!curl https://api.openai.com/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d "$payload_json"
方法3:使用%%bash魔法命令
利用Jupyter的单元格级bash魔法命令,直接编写原生shell格式的curl命令,无需额外转义:
# 先将Python环境的API密钥导出到shell环境(如果密钥存在Python变量中) import os os.environ['OPENAI_API_KEY'] = "你的API密钥内容"
然后新建单元格执行:
%%bash curl https://api.openai.com/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "gpt-3.5-turbo", "messages": [{"role": "user", "content": "Say this is a test!"}], "temperature": 0.7 }'
内容的提问来源于stack exchange,提问作者questionto42
相关产品推荐
相关产品推荐

