# Go (/docs/zh-CN/sdk/golang)

官方 [OpenAI Go SDK](https://github.com/openai/openai-go) 无需改动即可接入 OhMyGPT：设置 base URL 和 Key，同一个客户端就能调用模型列表里的所有对话模型。示例使用 `openai-go` v3 和 Chat Completions。

## 安装 [#安装]

```bash
go get github.com/openai/openai-go/v3
```

## 创建对话补全 [#创建对话补全]

```go title="main.go"
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/openai/openai-go/v3"
	"github.com/openai/openai-go/v3/option"
)

func main() {
	client := openai.NewClient(
		option.WithBaseURL("https://api.ohmygpt.com/v1"),
		option.WithAPIKey(os.Getenv("OHMYGPT_API_KEY")),
	)

	completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{
		Model: "zhipu/glm-5.3-flash",
		Messages: []openai.ChatCompletionMessageParamUnion{
			openai.UserMessage("Write a haiku about the sea."),
		},
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(completion.Choices[0].Message.Content)
}
```

```text
Waves kiss the shoreline,
salt air carries old stories—
the tide pulls me home.
```

把 `Model` 设为 `"ohmygpt/mock"` 即可免费测试，它会返回一段固定的回复。`GET /v1/models` 中的任意模型 ID 都可以填在这里。

## 流式输出 [#流式输出]

```go
stream := client.Chat.Completions.NewStreaming(context.Background(), openai.ChatCompletionNewParams{
	Model: "zhipu/glm-5.3-flash",
	Messages: []openai.ChatCompletionMessageParamUnion{
		openai.UserMessage("Write a haiku about the sea."),
	},
})
for stream.Next() {
	chunk := stream.Current()
	if len(chunk.Choices) > 0 {
		fmt.Print(chunk.Choices[0].Delta.Content)
	}
}
if err := stream.Err(); err != nil {
	panic(err)
}
```

## 选择供应商 [#选择供应商]

SDK 里没有对应 OhMyGPT `provider` 路由对象的字段，用 `option.WithJSONSet` 把它加进请求体：

```go
completion, err := client.Chat.Completions.New(ctx, params,
	option.WithJSONSet("provider", map[string]any{"sort": "price"}),
)
```

字段列表见[供应商路由](/docs/zh-CN/provider-routing)。

## 读取费用 [#读取费用]

非流式响应在 `X-Cost-Credits` 头里给出本次费用。用 `option.WithResponseInto` 拿到原始响应：

```go
var resp *http.Response // import "net/http"
completion, err := client.Chat.Completions.New(ctx, params, option.WithResponseInto(&resp))
if err != nil {
	panic(err)
}
fmt.Println(resp.Header.Get("X-Request-Id"), resp.Header.Get("X-Cost-Credits"))
```

```text
01a19b5d-e3c3-71ce-9ef9-68ee39f92a91 5
```

Credits 与美元的换算见[费用](/docs/zh-CN/costs)。
