一、核心环境准备
- 安装依赖:通过 pip install openai 安装官方 SDK,若环境存在多版本问题,建议使用 pip3。
|
Python
from openai import OpenAI
client = OpenAI(
api_key="你的API Key",
base_url="https://chat.intern-ai.org.cn/api/v1/"
) |
✅ 注意:api_key 必须用字符串包裹,否则会触发语法错误;如果使用 getpass 动态输入,就不要再在代码里写死 api_key,避免冲突。
二、基础文本交互
1. 普通对话
|
Python
completion = client.chat.completions.create(
model="intern-s1",
messages=[
{"role": "user", "content": "写一个关于独角兽的睡前故事,一句话就够了。"}
]
)
print(completion.choices[0].message.content) |
2. 开启思考模式(thinking_mode)
- 当 extra_body={"thinking_mode": True} 时,模型会返回思考过程+最终回答,适合需要推理的场景。
- 当 thinking_mode=False 时,仅返回最终结果,更适合追求简洁输出的场景。
3. 流式输出
通过设置 stream=True 可以实现逐字输出,提升交互体验:
|
Python
stream = client.chat.completions.create(
model="intern-s1",
messages=[{"role": "user", "content": "Say '1 2 3 4 5 6 7' ten times fast."}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True) |
三、多模态能力实践
1. 网络图片输入
|
Python
response = client.chat.completions.create(
model="intern-s1",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "图片里有什么?"},
{
"type": "image_url",
"image_url": {
"url": "https://pic1.imgdb.cn/item/68d24759c5157e1a882b2505.jpg"
}
}
]
}
],
extra_body={"thinking_mode": True}
) |
2. 本地图片输入(Base64编码)
先将本地图片编码为 Base64 字符串,再传给模型,是最稳定的本地图片调用方式:
|
Python
import base64
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
base64_image = encode_image("Gfp-wisconsin-madison-the-nature-boardwalk.jpg")
response = client.chat.completions.create(
model="intern-s1",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "图片里有什么?"},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}"
}
}
]
}
]
) |
四、工具调用(Function Call)
实现模型与外部工具的联动,以天气查询为例:
- 定义工具
|
Python
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current temperature for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City and country e.g. Paris, France"}
},
"required": ["location"]
}
}
}] |
- 触发工具调用
|
Python
completion = client.chat.completions.create(
model="intern-s1",
messages=[{"role": "user", "content": "What is the weather like in Paris today?"}],
tools=tools
)
# 解析工具调用指令
tool_calls = completion.choices[0].message.tool_calls |
- 处理工具返回并生成最终回答
调用外部接口获取天气数据后,将结果拼接回对话历史,发起第二轮请求,即可得到整合了工具结果的最终回答。
五、常见问题与避坑指南
- 语法错误:api_key 未加引号、参数间缺少逗号是高频错误,编写代码时注意检查标点符号。
- 多模态格式不兼容:intern-s1 支持 image_url 格式,但网络链接需确保模型可访问;本地图片建议使用 Base64 编码。
- 认证失败:确保 api_key 正确且未过期,若同时使用 getpass 和硬编码 api_key,会导致认证冲突。
- 路径问题:本地文件读取时,优先使用绝对路径,或确保图片与代码文件在同一目录下,避免相对路径引发的文件找不到问题。
所有评论(0)