Go SDK 适用于 DeepSeek V4 API — 支持聊天、推理、与 Anthropic 兼容的端点、工具调用、FIM 和流式传输。此外还支持 OpenRouter、Azure、Ollama 和 Open
Go SDK 适用于 DeepSeek V4 API — 支持聊天、推理、与 Anthropic 兼容的端点、工具调用、FIM 和流式传输。此外还支持 OpenRouter、Azure、Ollama 和 Open
Deepseek-Go is a Go-based API client for the Deepseek platform. It provides a clean and type-safe interface to interact with Deepseek's AI features, including chat completions with streaming, token usage tracking, and more.
go get github.com/cohesion-org/deepseek-godeepseek-go currently uses go 1.26.0
NewAnthropicClient with content blocks, tool use, and streaming.reasoning_effort ("high" / "max")./beta routing).ResponseFormat.For API status and uptime, refer to the DeepSeek Status page.
Here's a quick example of how to use the library:
Before using the library, ensure you have:
deepseek-v4-flash (current)
Flagship model with 1M context, 384K max output. Supports thinking mode, tool calls, JSON output, FIM, and prefix completion.
Usage: Model: deepseek.DeepSeekV4Flash
deepseek-v4-pro (current)
Premium reasoning model with 1M context, 384K max output. Best for complex reasoning and agent tasks.
Usage: Model: deepseek.DeepSeekV4Pro
deepseek-chat (deprecated, sunset 2026/07/24)
Maps to deepseek-v4-flash non-thinking mode.
Usage: Model: deepseek.DeepSeekV4Flash — emits a deprecation warning to stderr.
deepseek-reasoner (deprecated, sunset 2026/07/24)
Maps to deepseek-v4-flash thinking mode.
Usage: Model: deepseek.DeepSeekReasoner — emits a deprecation warning to stderr.
Azure DeepSeekR1
DeepSeek R1 provided by Azure.
Usage: Model: deepseek.AzureDeepSeekR1
OpenRouter
OpenRouter provides access to DeepSeek R1 and distill models.
Usage: Model: deepseek.OpenRouterDeepSeekR1 (and other OpenRouterDeepSeek* constants)
Ollama Support
Please read Ollama Support for more info about this!
Even more examples are avilable here
…Using external providers such as Azure or OpenRouter.
…Note: If you wish to use other providers that are not supported by us, you can simply extend the baseURL(as shown above), and pass the name of your model as a string to Model while creating the ChatCompletionRequest. This will work as long as the provider follows the same API structure as Azure or OpenRouter.
Sending other params like Temp, Stop
You just need to extend the ChatCompletionMessage with the supported parameters. request := &deepseek.ChatCompletionRequest{
Model: deepseek.DeepSeekV4Flash,
Messages: []deepseek.ChatCompletionMessage{
{Role: deepseek.ChatMessageRoleUser, Content: "What is the meaning of deepseek"},
{Role: deepseek.ChatMessageRoleSystem, Content: "Answer every question using slang"},
},
Temperature: 1.0,
Stop: []string{"yo", "hello"},
ResponseFormat: &deepseek.ResponseFormat{
Type: "text",
},
} Multi-Conversation with Deepseek. …Chat with Streaming
…Get the balance(s) of the user.
package main
import (
"context"
"log"
"os"
deepseek "github.com/cohesion-org/deepseek-go"
)
func main() {
client := deepseek.NewClient(os.Getenv("DEEPSEEK_API_KEY"))
ctx := context.Background()
balance, err := deepseek.GetBalance(client, ctx)
if err != nil {
log.Fatalf("Error getting balance: %v", err)
}
if balance == nil {
log.Fatalf("Balance is nil")
}
if len(balance.BalanceInfos) == 0 {
log.Fatalf("No balance information returned")
}
log.Printf("%+v\n", balance)
}Get the list of All the models the API supports right now. This is different from what deepseek-go might support.
func ListModels() {
client := deepseek.NewClient("DEEPSEEK_API_KEY")
ctx := context.Background()
models, err := deepseek.ListAllModels(client, ctx)
if err != nil {
t.Fatalf("Error listing models: %v", err)
}
fmt.Printf("\n%+v\n", models)
}Get the estimated tokens for the request.
This is adpated from the Deepseek's estimation.
…JSON mode for JSON extraction
…You can see more examples inside the examples folder.
Add more settings to your client with NewClientWithOptions
package main
import (
"fmt"
"log"
"time"
"github.com/cohesion-org/deepseek-go"
)
func main() {
client, err := deepseek.NewClientWithOptions("your-api-key",
deepseek.WithBaseURL("https://custom-api.com/"),
deepseek.WithTimeout(10*time.Second),
)
if err != nil {
log.Fatalf("Error creating client: %v", err)
}
fmt.Printf("Client initialized with BaseURL: %s and Timeout: %v\n", client.BaseURL, client.Timeout)
}Using local model servers without an API key:
By default, NewClientWithOptions requires an API key. If you're connecting to a local model server (e.g., vLLM, llama.cpp, LocalAI) that doesn't require authentication, use WithoutAPIKeyValidation():
client, err := deepseek.NewClientWithOptions("",
deepseek.WithBaseURL(""),
deepseek.WithoutAPIKeyValidation(),
)See the examples folder for more information.
FIM Mode(Beta)
In FIM (Fill In the Middle) completion, users can provide a prefix and a suffix (optional), and the model will complete the content in between. FIM is commonly used for content completion、code completion.
package main
import (
"context"
"fmt"
"log"
"os"
deepseek "github.com/cohesion-org/deepseek-go"
)
func FIM() {
client := deepseek.NewClient(os.Getenv("DEEPSEEK_API_KEY"))
request := &deepseek.FIMCompletionRequest{
Model: deepseek.DeepSeekV4Flash,
Prompt: "def add(a, b):",
}
ctx := context.Background()
response, err := client.CreateFIMCompletion(ctx, request)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Println("\n", response.Choices[0].Text)
}
Chat Prefix Completion (Beta) The chat prefix completion follows the Chat Completion API, where users provide an assistant's prefix message for the model to complete the rest of the message.
package main
import (
"context"
"fmt"
"log"
deepseek "github.com/cohesion-org/deepseek-go"
)
func ChatPrefix() {
client := deepseek.NewClient(
DEEPSEEK_API_KEY,
"https://api.deepseek.com/beta/") // Use the beta endpoint
ctx := context.Background()
request := &deepseek.ChatCompletionRequest{
Model: deepseek.DeepSeekV4Flash,
Messages: []deepseek.ChatCompletionMessage{
{Role: deepseek.ChatMessageRoleUser, Content: "Please write quick sort code"},
{Role: deepseek.ChatMessageRoleAssistant, Content: "```python", Prefix: true},
},
Stop: []string{"```"}, // Stop the prefix when the assistant sends the closing triple backticks
}
response, err := client.CreateChatCompletion(ctx, request)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Println(response.Choices[0].Message.Content)
}
Using external providers with image support (OpenRouter)
…For more advanced examples including streaming and base64 image support, see OpenRouter Images Examples.
Thinking Mode with reasoning_effort
DeepSeek V4 models support chain-of-thought reasoning. Control the reasoning depth with ReasoningEffort:
…Note: When thinking mode is active, temperature, top_p, presence_penalty, and frequency_penalty are accepted but have no effect.
Tool Calling with Strict Mode
Standard function calling and beta strict mode (automatically routes to /beta when Strict: true):
…Anthropic-Compatible API
Use NewAnthropicClient to talk to DeepSeek's Anthropic-compatible endpoint. Claude model names are automatically mapped to DeepSeek models:
…See examples/ for more Anthropic usage patterns including tool use and streaming.
Multi-tenant isolation with user_id
Use UserID to isolate content safety, KVCache, and scheduling per end-user:
request := &deepseek.ChatCompletionRequest{
Model: deepseek.DeepSeekV4Flash,
UserID: "user-42", // [a-zA-Z0-9-_]+, max 512 chars
Messages: []deepseek.ChatCompletionMessage{
{Role: deepseek.ChatMessageRoleUser, Content: "Hello!"},
},
}Do not include user privacy information (emails, names, PII) in user_id.
To use the Deepseek API, you need an API key. You can obtain one by signing up on the Deepseek website
Deepseek-go supports the usage of Ollama, but because of Ollama not following OpenAI policy, there are some extra types you need to be aware about. This is still an experimental feature so please understand that.
You can find all information about it at Ollama Docs.
Copy the example environment file:
cp .env.example .envAdd your DeepSeek API key to .env if you plan to run live integration tests:
TEST_DEEPSEEK_API_KEY=your_api_key_here(Optional) Add your OpenRouter key if you plan to run the integration image tests:
OPENROUTER_API_KEY=your_openrouter_key_here(Optional) Configure test timeout:
# Default is 30s, increase for slower connections
TEST_TIMEOUT=1mThe tests are organized into several files and folders:
client_test.go: Client configuration and error handling
chat_test.go: Chat completion functionality
chat_stream_test.go: Chat streaming functionality
models_test.go: Model listing and retrieval
balance_test.go: Account balance operations
tokens_test.go: Token estimation utilities
json_test.go: JSON mode for extraction
fim_test.go: Tests for the FIM beta implementation
requestHandler_test.go: Tests for the request handler
responseHandler_test.go: Tests for the response handler
utils/requestBuilder_test.go: Tests for the request builderRun the default offline test suite:
go test -v ./...This uses the built-in mock DeepSeek server for the package's API contract tests, so it does not require a DeepSeek API key.
Run tests in short mode:
go test -v -short ./...Run tests with race detection:
go test -v -race ./...Run test
暂无开放 Issues,或尚未同步最近议题。