一、核心环境准备
- 安装依赖:通过 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://www.wsisp.com/helps/wp-content/uploads/2026/01/20260125184056-697663b8b9f18.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 |
调用外部接口获取天气数据后,将结果拼接回对话历史,发起第二轮请求,即可得到整合了工具结果的最终回答。
五、常见问题与避坑指南
网硕互联帮助中心






评论前必须登录!
注册