Skip to content

Kimi API Golang 调用:OpenAI Go SDK 不完全兼容的处理方式

问题

使用 OpenAI 官方 Go SDK(github.com/openai/openai-go)调用 Kimi API 时,发现存在不完全兼容的情况。MoonshotAI-Cookbook 仓库只提供了基础 Go demo,没有官方 Go SDK。

解决方案

方式一:使用 langchaingo(推荐)

langchaingo 支持 Kimi API,官方 Cookbook 中也有对应示例:

go
import (
    "github.com/tmc/langchaingo/llms/openai"
)

llm, err := openai.New(
    openai.WithBaseURL("https://api.moonshot.cn/v1"),
    openai.WithToken("your-kimi-api-key"),
    openai.WithModel("kimi-k2.6"),
)

方式二:直接用 net/http 发 HTTP 请求

Kimi API 与 OpenAI 接口规范兼容,直接替换 base URL 即可:

go
import (
    "bytes"
    "encoding/json"
    "net/http"
)

type ChatRequest struct {
    Model    string        `json:"model"`
    Messages []ChatMessage `json:"messages"`
}

type ChatMessage struct {
    Role    string `json:"role"`
    Content string `json:"content"`
}

func callKimi(apiKey, model, userMsg string) (*http.Response, error) {
    body, _ := json.Marshal(ChatRequest{
        Model: model,
        Messages: []ChatMessage{{Role: "user", Content: userMsg}},
    })
    req, _ := http.NewRequest("POST", "https://api.moonshot.cn/v1/chat/completions", bytes.NewBuffer(body))
    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")
    return http.DefaultClient.Do(req)
}

来源MoonshotAI/MoonshotAI-Cookbook #43