import "cnb.cool/S.o/z-ai-sdk-go/client"
// 从配置文件创建(推荐)
zai, err := client.Create()
// 使用配置对象创建
cfg := &config.Config{
BaseURL: "https://api.example.com/v1",
APIKey: "your-api-key",
}
zai := client.New(cfg)
zai := client.New(cfg,
client.WithTimeout(30*time.Second),
client.WithHTTPClient(customHTTPClient),
)
创建聊天补全。
resp, err := zai.CreateChatCompletion(ctx, &types.CreateChatCompletionRequest{
Model: "gpt-3.5-turbo",
Messages: []types.ChatMessage{
{Role: "system", Content: "You are a helpful assistant."},
{Role: "user", Content: "Hello!"},
},
Temperature: 0.7,
MaxTokens: 1000,
})
请求参数:
| 参数 | 类型 | 必需 | 说明 |
|---|---|---|---|
| Model | string | 否 | 模型名称 |
| Messages | []ChatMessage | 是 | 消息列表 |
| Temperature | float64 | 否 | 采样温度(0-2) |
| MaxTokens | int | 否 | 最大生成 token 数 |
| Thinking | *Thinking | 否 | 思维链配置 |
响应结构:
type CreateChatCompletionResponse struct {
ID string `json:"id"`
Object string `json:"object"`
Created int64 `json:"created"`
Model string `json:"model"`
Choices []ChatCompletionChoice `json:"choices"`
Usage *Usage `json:"usage,omitempty"`
}
type ChatCompletionChoice struct {
Index int `json:"index"`
Message ChatMessage `json:"message"`
FinishReason string `json:"finish_reason"`
}
创建流式聊天补全,返回 SSE 流。
stream, _, err := zai.CreateChatCompletionStream(ctx, req)
if err != nil {
// handle error
}
defer stream.Close()
// 手动处理 SSE 流
scanner := bufio.NewScanner(stream)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "data: ") {
// 解析 SSE 数据
}
}
使用处理器回调处理流式响应(推荐)。
err := zai.ProcessChatStream(ctx, req, func(chunk *client.StreamChunk) error {
for _, choice := range chunk.Choices {
fmt.Print(choice.Delta.Content)
}
return nil
})
收集流式响应为完整响应。
resp, err := zai.CollectChatStream(ctx, req)
fmt.Println(resp.Choices[0].Message.Content)
创建多模态聊天补全,支持图片、视频、文件输入。
resp, err := zai.CreateChatCompletionVision(ctx, &types.CreateChatCompletionVisionRequest{
Model: "gpt-4-vision-preview",
Messages: []types.VisionMessage{
{
Role: "user",
Items: []types.VisionMultimodalContentItem{
{Type: "text", Text: "描述这张图片"},
{Type: "image_url", ImageURL: &types.MediaURL{URL: "https://example.com/image.jpg"}},
{Type: "video_url", VideoURL: &types.MediaURL{URL: "https://example.com/video.mp4"}},
{Type: "file_url", FileURL: &types.MediaURL{URL: "https://example.com/document.pdf"}},
},
},
},
})
支持的内容类型:
| Type | 说明 | 示例 |
|---|---|---|
| text | 文本内容 | {"type": "text", "text": "描述图片"} |
| image_url | 图片 URL | {"type": "image_url", "image_url": {"url": "..."}} |
| video_url | 视频 URL(mp4, mkv, mov) | {"type": "video_url", "video_url": {"url": "..."}} |
| file_url | 文件 URL(pdf, txt, docx, xlsx, pptx) | {"type": "file_url", "file_url": {"url": "..."}} |
流式视觉聊天。
stream, _, err := zai.CreateChatCompletionVisionStream(ctx, req)
defer stream.Close()
io.Copy(os.Stdout, stream)
文字转语音。
resp, err := zai.CreateAudioTTS(ctx, &types.CreateAudioTTSRequest{
Input: "你好,世界!",
Voice: "tongtong",
Speed: 1.0,
ResponseFormat: "wav",
Stream: false,
})
defer resp.Body.Close()
// resp.Body 包含音频二进制数据
data, _ := io.ReadAll(resp.Body)
os.WriteFile("output.wav", data, 0644)
请求参数:
| 参数 | 类型 | 必需 | 说明 |
|---|---|---|---|
| Input | string | 是 | 要转换的文本 |
| Voice | string | 否 | 声音类型(默认: tongtong) |
| Speed | float64 | 否 | 语速(0.5-2.0,默认: 1.0) |
| ResponseFormat | string | 否 | 输出格式(wav/mp3/pcm,默认: wav) |
| Stream | bool | 否 | 是否流式输出(流式时仅支持 pcm) |
语音转文字。
resp, err := zai.CreateAudioASR(ctx, &types.CreateAudioASRRequest{
FileBase64: base64EncodedAudio,
})
fmt.Println(resp.Text)
请求参数:
| 参数 | 类型 | 必需 | 说明 |
|---|---|---|---|
| FileBase64 | string | 是* | 音频文件的 base64 编码 |
| File | string | 是* | 音频文件路径 |
*FileBase64 与 File 二选一
生成图片。
resp, err := zai.CreateImageGeneration(ctx, &types.CreateImageGenerationRequest{
Prompt: "一只可爱的小猫",
Size: "1024x1024",
})
// resp.Data[0].Base64 包含 base64 编码的 PNG 图片
data, _ := base64.StdEncoding.DecodeString(resp.Data[0].Base64)
os.WriteFile("cat.png", data, 0644)
请求参数:
| 参数 | 类型 | 必需 | 说明 |
|---|---|---|---|
| Prompt | string | 是 | 图片描述文本 |
| Size | string | 否 | 图片尺寸(默认: 1024x1024) |
支持的尺寸:
1024x1024 - 默认768x1344 - 竖版864x1152 - 竖版1344x768 - 横版1152x864 - 横版1440x720 - 宽屏720x1440 - 竖版宽屏编辑图片。
resp, err := zai.CreateImageEdit(ctx, &types.CreateImageEditRequest{
Prompt: "添加彩虹",
Image: base64EncodedImage,
Size: "1024x1024",
})
搜索图片。
resp, err := zai.CreateImageSearch(ctx, &types.CreateImageSearchRequest{
Query: "日落 海洋",
Count: 10,
})
for _, result := range resp.Results {
fmt.Println(result.OriginalURL)
}
生成视频(异步任务)。
resp, err := zai.CreateVideoGeneration(ctx, &types.CreateVideoGenerationRequest{
Prompt: "A cat playing with a ball",
Quality: "speed",
Size: "1920x1080",
FPS: 30,
Duration: 5,
})
// resp.ID 是任务 ID,需要异步查询结果
fmt.Println("Task ID:", resp.ID)
fmt.Println("Task Status:", resp.TaskStatus)
请求参数:
| 参数 | 类型 | 必需 | 说明 |
|---|---|---|---|
| Prompt | string | 否 | 视频的文本描述 |
| ImageURL | string | 否 | 图片 URL(单张图片) |
| ImageURLs | []string | 否 | 图片 URL 列表(首尾帧模式,2张图片) |
| Quality | string | 否 | 输出模式(speed/quality,默认: speed) |
| WithAudio | bool | 否 | 是否生成 AI 音效(默认: false) |
| Size | string | 否 | 视频分辨率,如 "1920x1080" |
| FPS | int | 否 | 视频帧率(30/60,默认: 30) |
| Duration | int | 否 | 视频时长(秒)(5/10,默认: 5) |
查询异步任务结果。
result, err := zai.QueryAsyncResult(ctx, taskID)
switch result.TaskStatus {
case "SUCCESS":
fmt.Println("Video URL:", result.VideoResult[0].URL)
case "PROCESSING":
fmt.Println("Still processing...")
case "FAIL":
fmt.Println("Task failed")
}
响应结构:
type AsyncResultResponse struct {
ID string `json:"id"`
TaskStatus string `json:"task_status"` // PROCESSING, SUCCESS, FAIL
VideoResult []VideoResultItem `json:"video_result,omitempty"`
VideoURL string `json:"video_url,omitempty"`
URL string `json:"url,omitempty"`
Video string `json:"video,omitempty"`
}
通用函数调用。
result, err := zai.InvokeFunction(ctx, "web_search", map[string]any{
"query": "Golang 教程",
"num": 5,
"recency_days": 10,
})
网页搜索(便捷方法)。
result, err := zai.WebSearch(ctx, &types.SearchFunctionArgs{
Query: "Golang 教程",
Num: 5,
RecencyDays: 10,
})
网页内容读取(便捷方法)。
result, err := zai.PageReader(ctx, &types.PageReaderFunctionArgs{
URL: "https://example.com",
})
fmt.Println("标题:", result.Data.Title)
fmt.Println("URL:", result.Data.URL)
fmt.Println("发布时间:", result.Data.PublishedTime)
fmt.Println("HTML:", result.Data.HTML)
支持的函数:
| 函数名 | 说明 | 参数 |
|---|---|---|
| web_search | 网页搜索 | query, num, recency_days |
| page_reader | 网页阅读器 | url |
import "cnb.cool/S.o/z-ai-sdk-go/server"
zai, _ := client.Create()
srv := server.New(zai, server.WithAddr(":8080"))
srv.Run()
| 方法 | 路径 | 说明 |
|---|---|---|
| POST | /api/v1/chat/completions | 聊天补全 |
| POST | /api/v1/chat/completions/vision | 视觉聊天 |
| POST | /api/v1/audio/tts | 文字转语音 |
| POST | /api/v1/audio/asr | 语音转文字 |
| POST | /api/v1/images/generate | 图片生成 |
| POST | /api/v1/images/edit | 图片编辑 |
| POST | /api/v1/images/search | 图片搜索 |
| POST | /api/v1/video/generate | 视频生成 |
| GET | /api/v1/async/result | 异步结果查询 |
| POST | /api/v1/functions/invoke | 函数调用 |
# 聊天补全
curl -X POST http://localhost:8080/api/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-3.5-turbo",
"messages": [{"role": "user", "content": "Hello!"}]
}'
# 图片生成
curl -X POST http://localhost:8080/api/v1/images/generate \
-H "Content-Type: application/json" \
-d '{
"prompt": "A beautiful sunset",
"size": "1024x1024"
}'
┌─────────────────┐
│ Proxy Gateway │
│ (WebSocket) │
└────────┬────────┘
│
┌────────────────┼────────────────┐
│ │ │
┌─────▼─────┐ ┌────▼────┐ ┌─────▼─────┐
│ Client 1 │ │ Client 2│ │ Client 3 │
│(本地 API) │ │(本地API)│ │(本地 API) │
└───────────┘ └─────────┘ └───────────┘
环境变量:
| 变量 | 说明 | 默认值 |
|---|---|---|
| PROXY_ADDR | 监听地址 | :8090 |
| PROXY_API_KEY | API 密钥 | 空(无认证模式) |
API 端点:
| 路径 | 说明 |
|---|---|
| /tunnel | WebSocket 隧道(客户端接入) |
| / | HTTP 代理转发 |
| /healthz | 健康检查 |
| /stats | Pool 级统计 |
| /sessions | Session 列表 |
| /sessions/{id} | Session 详情 + 活跃 Streams |
启动示例:
# 生产模式(需要认证)
PROXY_API_KEY=your-secret-key proxy-gateway
# 开发模式(无认证)
PROXY_API_KEY= proxy-gateway
环境变量:
| 变量 | 说明 | 默认值 |
|---|---|---|
| PROXY_GATEWAY_URL | Gateway URL | wss://zai.nat.08128.net/tunnel |
| PROXY_API_KEY | API 密钥 | 必需 |
| PROXY_NODE_ID | 节点 ID | 主机名 |
| PROXY_NODE_LABEL | 节点标签 | 同节点 ID |
| PROXY_ZONE | 可用区 | - |
| PROXY_VERSION | 版本 | - |
| PROXY_WEIGHT | 权重 | 1 |
| PROXY_MAX_STREAMS | 最大并发流数 | 0(无限制) |
| PROXY_RETRY_DELAY | 重连延迟 | 5s |
启动示例:
PROXY_GATEWAY_URL=wss://gateway.example.com/tunnel \
PROXY_API_KEY=your-secret-key \
PROXY_NODE_ID=node-001 \
proxy-client
Gateway 使用 Affinity + LeastConn 负载均衡策略:
X-Client-ID > X-Forwarded-For > Cookie > User-Agent# Pool 级统计
curl http://gateway:8090/stats
# Session 列表
curl http://gateway:8090/sessions
# Session 详情(含 Streams)
curl http://gateway:8090/sessions/node-001
所有 API 调用可能返回 *types.APIError:
resp, err := zai.CreateChatCompletion(ctx, req)
if err != nil {
if apiErr, ok := err.(*types.APIError); ok {
fmt.Printf("API error: %d - %s\n", apiErr.StatusCode, apiErr.Message)
} else {
fmt.Printf("Other error: %v\n", err)
}
return
}
APIError 结构:
type APIError struct {
StatusCode int `json:"status_code"`
Message string `json:"message"`
Code string `json:"code,omitempty"`
}
SDK 按以下顺序查找 .z-ai-config 文件:
./.z-ai-config)~/.z-ai-config)/etc/.z-ai-config){
"baseUrl": "https://api.example.com/v1",
"apiKey": "your-api-key",
"chatId": "optional-chat-id",
"userId": "optional-user-id"
}
可以使用环境变量覆盖配置:
export ZAI_BASE_URL=https://api.example.com/v1
export ZAI_API_KEY=your-api-key