Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
D

deepseek-go

> AI 编程
Open source

Go SDK for DeepSeek V4 API — chat, reasoning, Anthropic-compatible endpoint, tool calling, FIM, and streaming. Also supports OpenRouter, Azure, Ollama, and Open

341 stars0 likes3 views
WebsiteGitHub

About

Go SDK for DeepSeek V4 API — chat, reasoning, Anthropic-compatible endpoint, tool calling, FIM, and streaming. Also supports OpenRouter, Azure, Ollama, and Open

Deepseek-Go

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.

Installation

bash
go get github.com/cohesion-org/deepseek-go

deepseek-go currently uses go 1.26.0

Features

  • Chat Completion: Send chat messages and receive responses from DeepSeek's V4 models with streaming support.
  • Anthropic API: Full Anthropic-compatible endpoint support via NewAnthropicClient with content blocks, tool use, and streaming.
  • Thinking Mode: Chain-of-thought reasoning with configurable reasoning_effort ("high" / "max").
  • Tool Calling: Function calling with standard and strict mode (beta, with automatic /beta routing).
  • FIM Completion: Fill-in-the-Middle completions for code generation, with streaming.
  • JSON Output: Structured JSON output with schema extraction via ResponseFormat.
  • External Providers: OpenRouter, Azure, Ollama, and any OpenAI-compatible endpoint.
  • Balance & Models: Check account balance and list available models.
  • Token Estimation: Client-side token counting for Chinese and English text.
  • Modular Design: Reusable components for building, sending, and handling requests and responses.
  • MIT License: Open-source and free for both personal and commercial use.

For API status and uptime, refer to the DeepSeek Status page.

Contents

  • Installation
  • Features
  • Getting Started
    • Supported Models
    • External Providers
  • Examples
  • Getting a DeepSeek Key
  • Ollama Support
  • Running Tests
  • Who Uses deepseek-go
  • License

Getting Started

Here's a quick example of how to use the library:

Prerequisites

Before using the library, ensure you have:

  • A valid Deepseek API key.
  • Go installed on your system.

Supported Models

  • 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.

External Providers

  • 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!

Example for chatting with deepseek

Even more examples are avilable here

…

More Examples:

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. 
go
	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.

go
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.

go
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

go
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():

go
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.

go
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.

go

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:

go
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.


Getting a Deepseek Key

To use the Deepseek API, you need an API key. You can obtain one by signing up on the Deepseek website

Ollama

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.


Running Tests

Setup

  1. Copy the example environment file:

    bash
    cp .env.example .env
  2. Add your DeepSeek API key to .env if you plan to run live integration tests:

    TEST_DEEPSEEK_API_KEY=your_api_key_here
  3. (Optional) Add your OpenRouter key if you plan to run the integration image tests:

    OPENROUTER_API_KEY=your_openrouter_key_here
  4. (Optional) Configure test timeout:

    # Default is 30s, increase for slower connections
    TEST_TIMEOUT=1m

Test Organization

The tests are organized into several files and folders:

Main Package

  • 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 Package

  • utils/requestBuilder_test.go: Tests for the request builder

Running Tests

  1. Run the default offline test suite:

    bash
    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.

  2. Run tests in short mode:

    bash
    go test -v -short ./...
  3. Run tests with race detection:

    bash
    go test -v -race ./...
  4. Run test

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Goaiapideepseekdeepseek-api

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
CategoryAI 编程
PricingOpen source

> Related tools

G
GitHub Copilot
GitHub 官方 AI 编程助手,覆盖补全、Chat 与 Agent 模式。
C
Cursor
AI 原生代码编辑器,对话改代码、多文件 Agent 与规则体系是其核心。
S
skills
Skills for Real Engineers. Straight from my .agents directory.