deepseek

package module
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 10, 2025 License: MIT Imports: 15 Imported by: 36

README

Deepseek-Go

MIT License Go Report Card

Deepseek-Go is a Go-based API wrapper 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

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

deepseek-go currently uses go 1.23.3

Features

  • Chat Completion: Easily send chat messages and receive responses from Deepseek's AI models. It also supports streaming.
  • Modular Design: The library is structured into reusable components for building, sending, and handling requests and responses.
  • MIT License: Open-source and free for both personal and commercial use.

The recent gain in popularity and cybersecurity issues Deepseek has seen makes for many problems while using the API. Please refer to the status page for the current status.

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-chat
    A versatile model designed for conversational tasks.
    Usage: Model: deepseek.DeepSeekChat

  • deepseek-reasoner
    A specialized model for reasoning-based tasks.
    Usage: Model: deepseek.DeepSeekReasoner.
    Note: The reasoner requires unique conditions. Please refer to this issue #8.

External Providers
  • Azure DeepSeekR1
    Same as deepseek-reasoner, but provided by Azure.
    Usage: Model: deepseek.AzureDeepSeekR1

  • OpenRouter DeepSeek1
    Same as deepseek-reasoner, but provided by OpenRouter.
    Usage: Model: deepseek.OpenRouterR1

Chat
Example for chatting with deepseek
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	deepseek "github.com/cohesion-org/deepseek-go"
	constants "github.com/cohesion-org/deepseek-go/constants"
)

func main() {
	// Set up the Deepseek client
    client := deepseek.NewClient(os.Getenv("DEEPSEEK_API_KEY"))

	// Create a chat completion request
	request := &deepseek.ChatCompletionRequest{
		Model: deepseek.DeepSeekChat,
		Messages: []deepseek.ChatCompletionMessage{
			{Role: constants.ChatMessageRoleSystem, Content: "Answer every question using slang."},
			{Role: constants.ChatMessageRoleUser, Content: "Which is the tallest mountain in the world?"},
		},
	}

	// Send the request and handle the response
	ctx := context.Background()
	response, err := client.CreateChatCompletion(ctx, request)
	if err != nil {
		log.Fatalf("error: %v", err)
	}

	// Print the response
	fmt.Println("Response:", response.Choices[0].Message.Content)
}

More Examples:

Using external providers such as Azure or OpenRouter.
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	deepseek "github.com/cohesion-org/deepseek-go"
	constants "github.com/cohesion-org/deepseek-go/constants"
)

func main() {

	// Azure
	baseURL := "https://models.inference.ai.azure.com/"

	// OpenRouter
	// baseURL := "https://openrouter.ai/api/v1/"

	// Set up the Deepseek client
    client := deepseek.NewClient(os.Getenv("PROVIDER_API_KEY"), baseURL)

	// Create a chat completion request
	request := &deepseek.ChatCompletionRequest{
		Model: deepseek.AzureDeepSeekR1,
		// Model: deepseek.OpenRouterDeepSeekR1,
		Messages: []deepseek.ChatCompletionMessage{
			{Role: constants.ChatMessageRoleUser, Content: "Which is the tallest mountain in the world?"},
		},
	}

	// Send the request and handle the response
	ctx := context.Background()
	response, err := client.CreateChatCompletion(ctx, request)
	if err != nil {
		log.Fatalf("error: %v", err)
	}

	// Print the response
	fmt.Println("Response:", response.Choices[0].Message.Content)
}

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.DeepSeekChat,
		Messages: []deepseek.ChatCompletionMessage{
			{Role: constants.ChatMessageRoleUser, Content: "What is the meaning of deepseek"},
			{Role: constants.ChatMessageRoleSystem, Content: "Answer every question using slang"},
		},
		Temperature: 1.0,
		Stop:        []string{"yo", "hello"},
		ResponseFormat: &deepseek.ResponseFormat{
			Type: "text",
		},
	}
Multi-Conversation with Deepseek.
package deepseek_examples

import (
	"context"
	"log"

	deepseek "github.com/cohesion-org/deepseek-go"
	"github.com/cohesion-org/deepseek-go/constants"
)

func MultiChat() {
	client := deepseek.NewClient("DEEPSEEK_API_KEY")
	ctx := context.Background()

	messages := []deepseek.ChatCompletionMessage{{
		Role:    constants.ChatMessageRoleUser,
		Content: "Who is the president of the United States? One word response only.",
	}}

	// Round 1: First API call
	response1, err := client.CreateChatCompletion(ctx, &deepseek.ChatCompletionRequest{
		Model:    deepseek.DeepSeekChat,
		Messages: messages,
	})
	if err != nil {
		log.Fatalf("Round 1 failed: %v", err)
	}

	response1Message, err := deepseek.MapMessageToChatCompletionMessage(response1.Choices[0].Message)
	if err != nil {
		log.Fatalf("Mapping to message failed: %v", err)
	}
	messages = append(messages, response1Message)

	log.Printf("The messages after response 1 are: %v", messages)
	// Round 2: Second API call
	messages = append(messages, deepseek.ChatCompletionMessage{
		Role:    constants.ChatMessageRoleUser,
		Content: "Who was the one in the previous term.",
	})

	response2, err := client.CreateChatCompletion(ctx, &deepseek.ChatCompletionRequest{
		Model:    deepseek.DeepSeekChat,
		Messages: messages,
	})
	if err != nil {
		log.Fatalf("Round 2 failed: %v", err)
	}

	response2Message, err := deepseek.MapMessageToChatCompletionMessage(response2.Choices[0].Message)
	if err != nil {
		log.Fatalf("Mapping to message failed: %v", err)
	}
	messages = append(messages, response2Message)
	log.Printf("The messages after response 1 are: %v", messages)

}

Chat with Streaming
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"os"

	deepseek "github.com/cohesion-org/deepseek-go"
	constants "github.com/cohesion-org/deepseek-go/constants"
)

func main() {
	client := deepseek.NewClient(os.Getenv("DEEPSEEK_API_KEY"))
	request := &deepseek.StreamChatCompletionRequest{
		Model: deepseek.DeepSeekChat,
		Messages: []deepseek.ChatCompletionMessage{
			{Role: constants.ChatMessageRoleUser, Content: "Just testing if the streaming feature is working or not!"},
		},
		Stream: true,
	}
	ctx := context.Background()

	stream, err := client.CreateChatCompletionStream(ctx, request)
	if err != nil {
		log.Fatalf("ChatCompletionStream error: %v", err)
	}
	var fullMessage string
	defer stream.Close()
	for {
		response, err := stream.Recv()
		if errors.Is(err, io.EOF) {
			fmt.Println("\nStream finished")
			break
		}
		if err != nil {
			fmt.Printf("\nStream error: %v\n", err)
			break
		}
		for _, choice := range response.Choices {
			fullMessage += choice.Delta.Content // Accumulate chunk content
			log.Println(choice.Delta.Content)
		}
	}
	log.Println("The full message is: ", fullMessage)
}
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.

func Estimation() {
	client := deepseek.NewClient("DEEPSEEK_API_KEY"))
	request := &deepseek.ChatCompletionRequest{
		Model: deepseek.DeepSeekChat,
		Messages: []deepseek.ChatCompletionMessage{
			{Role: constants.ChatMessageRoleSystem, Content: "Just respond with the time it might take you to complete this request."},
			{Role: constants.ChatMessageRoleUser, Content: "The text to evaluate the time is: Who is the greatest singer in the world?"},
		},
	}
	ctx := context.Background()

	tokens := deepseek.EstimateTokensFromMessages(request)
	fmt.Println("Estimated tokens for the request is: ", tokens.EstimatedTokens)
	response, err := client.CreateChatCompletion(ctx, request)

	if err != nil {
		log.Fatalf("error: %v", err)
	}
	
	fmt.Println("Response:", response.Choices[0].Message.Content, "\nActual Tokens Used:", response.Usage.PromptTokens)
}

JSON mode for JSON extraction
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/cohesion-org/deepseek-go"
	"github.com/cohesion-org/deepseek-go/constants"
)

func JsonMode() {
	// Book represents a book in a library
	type Book struct {
		ISBN            string `json:"isbn"`
		Title           string `json:"title"`
		Author          string `json:"author"`
		Genre           string `json:"genre"`
		PublicationYear int    `json:"publication_year"`
		Available       bool   `json:"available"`
	}

	type Books struct {
		Books []Book `json:"books"`
	}
	// Creating a new client using OpenRouter; you can use your own API key and endpoint.
	client := deepseek.NewClient(
		os.Getenv("OPENROUTER_API_KEY"),
		"https://openrouter.ai/api/v1/",
	)
	ctx := context.Background()

	prompt := `Provide book details in JSON format. Generate 10 JSON objects. 
	Please provide the JSON in the following format: { "books": [...] }
	Example: {"isbn": "978-0321765723", "title": "The Lord of the Rings", "author": "J.R.R. Tolkien", "genre": "Fantasy", "publication_year": 1954, "available": true}`

	resp, err := client.CreateChatCompletion(ctx, &deepseek.ChatCompletionRequest{
		Model: "mistralai/codestral-2501", // Or another suitable model
		Messages: []deepseek.ChatCompletionMessage{
			{Role: constants.ChatMessageRoleUser, Content: prompt},
		},
		JSONMode: true,
	})
	if err != nil {
		log.Fatalf("Failed to create chat completion: %v", err)
	}
	if resp == nil || len(resp.Choices) == 0 {
		log.Fatal("No response or choices found")
	}

	log.Printf("Response: %s", resp.Choices[0].Message.Content)

	extractor := deepseek.NewJSONExtractor(nil)
	var books Books
	if err := extractor.ExtractJSON(resp, &books); err != nil {
		log.Fatal(err)
	}

	fmt.Printf("\n\nExtracted Books: %+v\n\n", books)

	// Basic validation to check if we got some books
	if len(books.Books) == 0 {
		log.Print("No books were extracted from the JSON response")
	} else {
		fmt.Println("Successfully extracted", len(books.Books), "books.")
	}

}

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)
}

See the examples folder for more information.


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


Running Tests

Setup
  1. Copy the example environment file:

    cp .env.example .env
    
  2. Add your DeepSeek API key to .env:

    TEST_DEEPSEEK_API_KEY=your_api_key_here
    
  3. (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
  • 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
Handlers Package
  • handlers/requestHandler_test.go: Tests for the request handler
  • handlers/responseHandler_test.go: Tests for the response handler
Utils Package
  • utils/requestBuilder_test.go: Tests for the request builder
Running Tests
  1. Run all tests (requires API key):

    go test -v ./...
    
  2. Run tests in short mode (skips API calls):

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

    go test -v -race ./...
    
  4. Run tests with coverage:

    go test -v -coverprofile=coverage.txt -covermode=atomic ./...
    

    View coverage in browser:

    go tool cover -html=coverage.txt
    
  5. Run specific test:

    # Example: Run only chat completion tests
    go test -v -run TestCreateChatCompletion ./...
    

License

This project is licensed under the MIT License. See the LICENSE file for details.


Credits


Feel free to contribute, open issues, or submit PRs to help improve Deepseek-Go! Let us know if you encounter any issues.

Documentation

Index

Constants

View Source
const (
	DeepSeekChat     = "deepseek-chat"
	DeepSeekCoder    = "deepseek-coder" // not sure if this exists anymore
	DeepSeekReasoner = "deepseek-reasoner"
)

Official DeepSeek Models

View Source
const (
	AzureDeepSeekR1                     = "DeepSeek-R1"                            // Azure model for DeepSeek R1
	OpenRouterDeepSeekR1                = "deepseek/deepseek-r1"                   // OpenRouter model for DeepSeek R1
	OpenRouterDeepSeekR1DistillLlama70B = "deepseek/deepseek-r1-distill-llama-70b" // DeepSeek R1 Distill Llama 70B
	OpenRouterDeepSeekR1DistillLlama8B  = "deepseek/deepseek-r1-distill-llama-8b"  // DeepSeek R1 Distill Llama 8B
	OpenRouterDeepSeekR1DistillQwen14B  = "deepseek/deepseek-r1-distill-qwen-14b"  // DeepSeek R1 Distill Qwen 14B
	OpenRouterDeepSeekR1DistillQwen1_5B = "deepseek/deepseek-r1-distill-qwen-1.5b" // DeepSeek R1 Distill Qwen 1.5B
	OpenRouterDeepSeekR1DistillQwen32B  = "deepseek/deepseek-r1-distill-qwen-32b"  // DeepSeek R1 Distill Qwen 32B
)

External Models that can be used with the API

View Source
const BaseURL string = "https://api.deepseek.com/v1"

Variables

View Source
var (
	ErrChatCompletionStreamNotSupported = errors.New("streaming is not supported with this method")
	ErrUnexpectedResponseFormat         = errors.New("unexpected response format")
)

Functions

func HandleAPIError

func HandleAPIError(resp *http.Response) error

func HandleNormalRequest added in v1.1.1

func HandleNormalRequest(c Client, req *http.Request) (*http.Response, error)

func HandleSendChatCompletionRequest added in v1.1.1

func HandleSendChatCompletionRequest(c Client, req *http.Request) (*http.Response, error)

func HandleTimeout added in v1.1.1

func HandleTimeout() (time.Duration, error)

Types

type APIError

type APIError struct {
	StatusCode    int    // HTTP status code
	APICode       int    // Business error code from API response
	Message       string // Human-readable error message
	OriginalError error  // Wrapped error for debugging
	ResponseBody  string // Raw JSON response body
}

func (APIError) Error

func (e APIError) Error() string

type APIModels added in v0.1.1

type APIModels struct {
	Object string  `json:"object"` //Object (string)
	Data   []Model `json:"data"`   // List of Models
}

func ListAllModels added in v0.1.1

func ListAllModels(c *Client, ctx context.Context) (*APIModels, error)

Models supported by the API itself

type APIType

type APIType string

type BalanceInfo

type BalanceInfo struct {
	Currency        string `json:"currency"`          //The currency of the balance.
	TotalBalance    string `json:"total_balance"`     //The total available balance, including the granted balance and the topped-up balance.
	GrantedBalance  string `json:"granted_balance"`   //The total not expired granted balance.
	ToppedUpBalance string `json:"topped_up_balance"` //The total topped-up balance.
}

type BalanceResponse

type BalanceResponse struct {
	IsAvailable  bool          `json:"is_available"`  //Whether the user's balance is sufficient for API calls.
	BalanceInfos []BalanceInfo `json:"balance_infos"` //List of Balance infos
}

func GetBalance

func GetBalance(c *Client, ctx context.Context) (*BalanceResponse, error)

type ChatCompletionMessage

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

func MapMessageToChatCompletionMessage

func MapMessageToChatCompletionMessage(m Message) (ChatCompletionMessage, error)

type ChatCompletionRequest

type ChatCompletionRequest struct {
	Model            string                  `json:"model"`                       // Required: Model ID, e.g., "deepseek-chat"
	Messages         []ChatCompletionMessage `json:"messages"`                    // Required: List of messages
	FrequencyPenalty float32                 `json:"frequency_penalty,omitempty"` // Optional: Frequency penalty, >= -2 and <= 2
	MaxTokens        int                     `json:"max_tokens,omitempty"`        // Optional: Maximum tokens, > 1
	PresencePenalty  float32                 `json:"presence_penalty,omitempty"`  // Optional: Presence penalty, >= -2 and <= 2
	Temperature      float32                 `json:"temperature,omitempty"`       // Optional: Sampling temperature, <= 2
	TopP             float32                 `json:"top_p,omitempty"`             // Optional: Nucleus sampling parameter, <= 1
	ResponseFormat   *ResponseFormat         `json:"response_format,omitempty"`   // Optional: Custom response format
	Stop             []string                `json:"stop,omitempty"`              // Optional: Stop signals
	Tools            []Tools                 `json:"tools,omitempty"`             // Optional: List of tools
	LogProbs         bool                    `json:"logprobs,omitempty"`          // Optional: Enable log probabilities
	TopLogProbs      int                     `json:"top_logprobs,omitempty"`      // Optional: Number of top tokens with log probabilities, <= 20
	JSONMode         bool                    `json:"json,omitempty"`              // Optional: Enable JSON mode. If you're using the JSON mode, please mention "json" anywhere in your prompt, and also include the JSON schema in the request.
}

make a different struct for streaming with streaming options parameter

type ChatCompletionResponse added in v1.1.1

type ChatCompletionResponse struct {
	ID                string   `json:"id"`                           // Unique identifier for the chat completion.
	Object            string   `json:"object"`                       // Type of the object, typically "chat.completion".
	Created           int64    `json:"created"`                      // Timestamp when the chat completion was created.
	Model             string   `json:"model"`                        // The model used for generating the completion.
	Choices           []Choice `json:"choices"`                      // List of completion choices generated by the model.
	Usage             Usage    `json:"usage"`                        // Token usage statistics.
	SystemFingerprint *string  `json:"system_fingerprint,omitempty"` // Fingerprint of the system configuration.
}

func HandleChatCompletionResponse added in v1.1.1

func HandleChatCompletionResponse(resp *http.Response) (*ChatCompletionResponse, error)

type ChatCompletionStream

type ChatCompletionStream interface {
	Recv() (*StreamChatCompletionResponse, error)
	Close() error
}

ChatCompletionStream is an interface for receiving streaming chat completion responses.

type Choice added in v1.1.1

type Choice struct {
	Index        int       `json:"index"`              // Index of the choice in the list of choices.
	Message      Message   `json:"message"`            // The message generated by the model.
	LogProbs     *LogProbs `json:"logprobs,omitempty"` // Log probabilities of the tokens, if available.
	FinishReason string    `json:"finish_reason"`      // Reason why the completion finished.
}

type Client

type Client struct {
	AuthToken string        // The authentication token for the API
	BaseURL   string        // The base URL for the API
	Timeout   time.Duration // The timeout for the current Client
}

func NewClient

func NewClient(AuthToken string, baseURL ...string) *Client

NewClient creates a new client with an authentication token and an optional custom baseURL. If no baseURL is provided, it defaults to "https://api.deepseek.com/".

func NewClientWithOptions added in v1.1.1

func NewClientWithOptions(authToken string, opts ...Option) (*Client, error)

NewClient creates a new client with required authentication token and optional configurations. Defaults: - BaseURL: "https://api.deepseek.com/" - Timeout: 5 minutes

func (*Client) CreateChatCompletion

func (c *Client) CreateChatCompletion(
	ctx context.Context,
	request *ChatCompletionRequest,
) (*ChatCompletionResponse, error)

CreateChatCompletion sends a chat completion request and returns the generated response.

func (*Client) CreateChatCompletionStream

func (c *Client) CreateChatCompletionStream(
	ctx context.Context,
	request *StreamChatCompletionRequest,
) (ChatCompletionStream, error)

CreateStreamChatCompletion send a chat completion request with stream = true and returns the delta

type Function

type Function struct {
	Name        string      `json:"name"`                 // The name of the function (required)
	Description string      `json:"description"`          // Description of the function (required)
	Parameters  *Parameters `json:"parameters,omitempty"` // Parameters schema (optional)
}

Function defines the structure of a function tool

type HTTPDoer

type HTTPDoer interface {
	Do(req *http.Request) (*http.Response, error)
}

type JSONExtractor added in v1.1.1

type JSONExtractor struct {
	// contains filtered or unexported fields
}

JSONExtractor helps extract structured data from LLM responses

func NewJSONExtractor added in v1.1.1

func NewJSONExtractor(schema json.RawMessage) *JSONExtractor

NewJSONExtractor creates a new JSONExtractor instance

func (*JSONExtractor) ExtractJSON added in v1.1.1

func (je *JSONExtractor) ExtractJSON(response *ChatCompletionResponse, target interface{}) error

ExtractJSON attempts to extract and parse JSON from an LLM response

type LogProbs added in v1.1.1

type LogProbs struct {
	Tokens        []string             `json:"tokens,omitempty"`         // List of tokens.
	TokenLogProbs []float64            `json:"token_logprobs,omitempty"` // Log probabilities of each token.
	TopLogProbs   []map[string]float64 `json:"top_logprobs,omitempty"`   // Top log probabilities for each token.
}

type Message added in v1.1.1

type Message struct {
	Role             string `json:"role"`                        // Role of the message sender (e.g., "user", "assistant").
	Content          string `json:"content"`                     // Content of the message.
	ReasoningContent string `json:"reasoning_content,omitempty"` // Optional reasoning content.
}

type Model added in v0.1.1

type Model struct {
	ID      string `json:"id"`       //The id of the model (string)
	Object  string `json:"object"`   //The object of the model (string)
	OwnedBy string `json:"owned_by"` //The owner of the model(usally deepseek)
}

type Option added in v1.1.1

type Option func(*Client) error

Option configures a Client instance

func WithBaseURL added in v1.1.1

func WithBaseURL(url string) Option

WithBaseURL sets the base URL for the API client

func WithTimeout added in v1.1.1

func WithTimeout(d time.Duration) Option

WithTimeout sets the timeout for API requests

func WithTimeoutString added in v1.1.1

func WithTimeoutString(s string) Option

WithTimeoutString parses a duration string and sets the timeout Example valid values: "5s", "2m", "1h"

type Parameters

type Parameters struct {
	Type       string                 `json:"type"` // Type of the parameters, e.g., "object" (required)
	Properties map[string]interface{} `json:"properties,omitempty"`
	Required   []string               `json:"required,omitempty"`
}

type ResponseFormat

type ResponseFormat struct {
	Type string `json:"type"` //either text or json_object. If json_object, please mention "json" anywhere in your prompt.
}

type StreamChatCompletionMessage

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

StreamChatCompletionMessage represents a single message in a chat completion stream.

type StreamChatCompletionRequest

type StreamChatCompletionRequest struct {
	Stream           bool                    `json:"stream,omitempty"`            //Comments: Defaults to true, since it's "STREAM"
	Model            string                  `json:"model"`                       // Required: Model ID, e.g., "deepseek-chat"
	Messages         []ChatCompletionMessage `json:"messages"`                    // Required: List of messages
	FrequencyPenalty float32                 `json:"frequency_penalty,omitempty"` // Optional: Frequency penalty, >= -2 and <= 2
	MaxTokens        int                     `json:"max_tokens,omitempty"`        // Optional: Maximum tokens, > 1
	PresencePenalty  float32                 `json:"presence_penalty,omitempty"`  // Optional: Presence penalty, >= -2 and <= 2
	Temperature      float32                 `json:"temperature,omitempty"`       // Optional: Sampling temperature, <= 2
	TopP             float32                 `json:"top_p,omitempty"`             // Optional: Nucleus sampling parameter, <= 1
	ResponseFormat   *ResponseFormat         `json:"response_format,omitempty"`   // Optional: Custom response format: just don't try, it breaks rn ;)
	Stop             []string                `json:"stop,omitempty"`              // Optional: Stop signals
	Tools            []Tools                 `json:"tools,omitempty"`             // Optional: List of tools
	LogProbs         bool                    `json:"logprobs,omitempty"`          // Optional: Enable log probabilities
	TopLogProbs      int                     `json:"top_logprobs,omitempty"`      // Optional: Number of top tokens with log probabilities, <= 20
}

StreamChatCompletionRequest represents the request body for a streaming chat completion API call.

type StreamChatCompletionResponse

type StreamChatCompletionResponse struct {
	ID      string          `json:"id"`              // ID of the response.
	Object  string          `json:"object"`          // Type of object.
	Created int64           `json:"created"`         // Creation timestamp.
	Model   string          `json:"model"`           // Model used.
	Choices []StreamChoices `json:"choices"`         // Choices generated.
	Usage   *StreamUsage    `json:"usage,omitempty"` // Usage statistics (optional).
}

StreamChatCompletionResponse represents a single response from a streaming chat completion API call.

type StreamChoices

type StreamChoices struct {
	Index        int         `json:"index"` // Index of the choice.
	Delta        StreamDelta // Delta information.
	FinishReason string      `json:"finish_reason"` // Reason for finishing the generation.
}

StreamChoices represents a choice in the chat completion stream.

type StreamDelta

type StreamDelta struct {
	Role    string `json:"role,omitempty"` // Role of the message.
	Content string `json:"content"`        // Content of the message.
}

StreamDelta represents a delta in the chat completion stream.

type StreamOptions

type StreamOptions struct {
	IncludeUsage bool
}

type StreamUsage

type StreamUsage struct {
	PromptTokens     int `json:"prompt_tokens"`     // Number of tokens in the prompt.
	CompletionTokens int `json:"completion_tokens"` // Number of tokens in the completion.
	TotalTokens      int `json:"total_tokens"`      // Total number of tokens used.
}

StreamUsage represents token usage statistics for a streaming chat completion response. You will get {0 0 0} up until the last stream delta.

type TokenEstimate added in v0.1.1

type TokenEstimate struct {
	EstimatedTokens int `json:"estimated_tokens"` //the total estimated prompt tokens. These are different form total tokens used.
}

TokenEstimate represents an estimated token count

func EstimateTokenCount added in v0.1.1

func EstimateTokenCount(text string) *TokenEstimate

EstimateTokenCount estimates the number of tokens in a text based on character type ratios

func EstimateTokensFromMessages added in v0.1.1

func EstimateTokensFromMessages(messages *ChatCompletionRequest) *TokenEstimate

EstimateTokensFromMessages estimates the number of tokens in a list of chat messages

type Tools

type Tools struct {
	Type     string   `json:"type"`     // Type of the tool, e.g., "function" (required)
	Function Function `json:"function"` // The function details (required)
}

Tool defines the structure for a tool

type Usage added in v1.1.1

type Usage struct {
	PromptTokens          int `json:"prompt_tokens"`            // Number of tokens used in the prompt.
	CompletionTokens      int `json:"completion_tokens"`        // Number of tokens used in the completion.
	TotalTokens           int `json:"total_tokens"`             // Total number of tokens used.
	PromptCacheHitTokens  int `json:"prompt_cache_hit_tokens"`  // Number of tokens served from cache.
	PromptCacheMissTokens int `json:"prompt_cache_miss_tokens"` // Number of tokens not served from cache.
}

Directories

Path Synopsis
internal
testutil
Package testutil provides testing utilities for the DeepSeek client.
Package testutil provides testing utilities for the DeepSeek client.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL