OpenAI SDK v2 完全指南:2026年 Python/JavaScript/Go 最新用法
OpenAI 在 2025 年发布了 SDK v2,接口全面升级,支持更多模型、更简洁的 API、更强大的流式输出。2026 年了,你的代码跟上 v2 了吗?本文详解 Python、JavaScript、Go 的最新用法。
SDK v2 核心变化:统一的消息格式、简化的流式 API、更强大的工具调用支持。v1 SDK 已不再维护,建议尽快迁移。
Python SDK v2(推荐方式)
# 安装
pip install anthropic
# 基础调用
from anthropic import Anthropic
client = Anthropic(
api_key="sk-holysheep-xxx",
base_url="https://api.holysheep.ai/v1"
)
# 对话
message = client.messages.create(
model="gpt-4o",
max_tokens=1024,
messages=[
{"role": "user", "content": "用 Python 写一个快速排序"}
]
)
print(message.content)
JavaScript/TypeScript SDK v2
# 安装
npm install @anthropic-ai/sdk
# 基础调用
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({
apiKey: 'sk-holysheep-xxx',
baseURL: 'https://api.holysheep.ai/v1'
});
async function main() {
const message = await client.messages.create({
model: 'gpt-4o',
max_tokens: 1024,
messages: [
{"role": "user", "content": "用 JavaScript 写一个快速排序"}
]
});
console.log(message.content);
}
main();
Go SDK
// 安装
// go get github.com/sashabaranov/go-openai
package main
import (
"context"
"fmt"
openai "github.com/sashabaranov/go-openai"
)
func main() {
client := openai.NewClient("sk-holysheep-xxx")
client.BaseURL = "https://api.holysheep.ai/v1"
resp, err := client.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
Model: "gpt-4o",
Messages: []openai.ChatCompletionMessage{
{Role: "user", Content: "用 Go 写一个快速排序"},
},
},
)
if err != nil {
panic(err)
}
fmt.Println(resp.Choices[0].Message.Content)
}
流式输出(所有语言)
# Python 流式
with client.messages.stream(
model="gpt-4o",
max_tokens=1024,
messages=[{"role": "user", "content": "写一个 Python 教程"}]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
Function Calling / Tool Use
# Python Function Calling
tools = [
{
"name": "get_weather",
"description": "获取城市天气",
"input_schema": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]
}
}
]
message = client.messages.create(
model="gpt-4o",
max_tokens=1024,
tools=tools,
messages=[{"role": "user", "content": "北京天气怎么样?"}]
)
for tool in message.tool_calls:
print(f"调用工具: {tool.name}")
print(f"参数: {tool.input}")