{"id":23960415,"url":"https://github.com/trustsight-io/deepseek-go","last_synced_at":"2025-10-26T14:38:24.250Z","repository":{"id":270507363,"uuid":"910457859","full_name":"TrustSight-io/deepseek-go","owner":"TrustSight-io","description":"A Deepseek client written for Go - https://www.deepseek.com/","archived":false,"fork":false,"pushed_at":"2025-01-18T06:38:21.000Z","size":61,"stargazers_count":6,"open_issues_count":1,"forks_count":1,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-03-29T22:04:44.591Z","etag":null,"topics":["deepseek","go","llm","wrapper-library"],"latest_commit_sha":null,"homepage":"https://pkg.go.dev/github.com/trustsight-io/deepseek-go","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/TrustSight-io.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-12-31T10:25:52.000Z","updated_at":"2025-03-12T11:03:54.000Z","dependencies_parsed_at":null,"dependency_job_id":"b863b28c-41d6-4c90-9667-9758e95d6620","html_url":"https://github.com/TrustSight-io/deepseek-go","commit_stats":null,"previous_names":["trustsight-io/deepseek-go"],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TrustSight-io%2Fdeepseek-go","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TrustSight-io%2Fdeepseek-go/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TrustSight-io%2Fdeepseek-go/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TrustSight-io%2Fdeepseek-go/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/TrustSight-io","download_url":"https://codeload.github.com/TrustSight-io/deepseek-go/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250367210,"owners_count":21418844,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["deepseek","go","llm","wrapper-library"],"created_at":"2025-01-06T19:28:01.456Z","updated_at":"2025-10-26T14:38:19.225Z","avatar_url":"https://github.com/TrustSight-io.png","language":"Go","readme":"# DeepSeek Go Client\n\nA Go client library for the DeepSeek API.\n\n## Table of Contents\n\n- [DeepSeek Go Client](#deepseek-go-client)\n  - [Table of Contents](#table-of-contents)\n  - [Installation](#installation)\n  - [Usage](#usage)\n    - [Chat Completion](#chat-completion)\n    - [JSON Mode](#json-mode)\n    - [Streaming Chat Completion](#streaming-chat-completion)\n    - [Token Estimation](#token-estimation)\n    - [List Available Models](#list-available-models)\n    - [Check Account Balance](#check-account-balance)\n  - [Running Tests](#running-tests)\n    - [Setup](#setup)\n    - [Test Organization](#test-organization)\n    - [Running Tests](#running-tests-1)\n    - [Test Environment Variables](#test-environment-variables)\n    - [Common Issues](#common-issues)\n  - [Contributing](#contributing)\n  - [License](#license)\n\n## Installation\n\n```bash\ngo get github.com/trustsight-io/deepseek-go\n```\n\n## Usage\n\n### Chat Completion\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n\n    \"github.com/trustsight-io/deepseek-go\"\n)\n\nfunc main() {\n    client, err := deepseek.NewClient(os.Getenv(\"DEEPSEEK_API_KEY\"))\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    resp, err := client.CreateChatCompletion(\n        context.Background(),\n        \u0026deepseek.ChatCompletionRequest{\n            Model: \"deepseek-chat\",\n            Messages: []deepseek.Message{\n                {\n                    Role:    deepseek.RoleUser,\n                    Content: \"Hello!\",\n                },\n            },\n        },\n    )\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    fmt.Println(resp.Choices[0].Message.Content)\n}\n```\n\n### JSON Mode\n\nThe library provides support for extracting structured JSON data from chat completions using the `JSONMode` flag and `JSONExtractor`:\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n\n    \"github.com/trustsight-io/deepseek-go\"\n)\n\n// Product represents a product in an e-commerce system\ntype Product struct {\n    ID          string  `json:\"id\"`\n    Name        string  `json:\"name\"`\n    Description string  `json:\"description\"`\n    Price       float64 `json:\"price\"`\n    Category    string  `json:\"category\"`\n    InStock     bool    `json:\"in_stock\"`\n}\n\nfunc main() {\n    client, err := deepseek.NewClient(os.Getenv(\"DEEPSEEK_API_KEY\"))\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    // Request product information in JSON format\n    resp, err := client.CreateChatCompletion(\n        context.Background(),\n        \u0026deepseek.ChatCompletionRequest{\n            Model: \"deepseek-chat\",\n            Messages: []deepseek.Message{\n                {\n                    Role: deepseek.RoleSystem,\n                    Content: `You are a product information generator. \n                    Generate product information in JSON format following the Product struct schema.`,\n                },\n                {\n                    Role:    deepseek.RoleUser,\n                    Content: \"Generate a product entry for a high-end laptop computer.\",\n                },\n            },\n            JSONMode: true, // Enable JSON mode\n        },\n    )\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    // Create a JSON extractor (optionally with schema validation)\n    extractor := deepseek.NewJSONExtractor(nil)\n    var product Product\n    if err := extractor.ExtractJSON(resp, \u0026product); err != nil {\n        log.Fatal(err)\n    }\n\n    fmt.Printf(\"Product: %s - $%.2f\\n\", product.Name, product.Price)\n}\n```\n\nWith schema validation:\n\n```go\n// Create a JSON extractor with schema validation\nschema := json.RawMessage(`{\n    \"type\": \"object\",\n    \"properties\": {\n        \"id\": {\"type\": \"string\"},\n        \"name\": {\"type\": \"string\"},\n        \"description\": {\"type\": \"string\"},\n        \"price\": {\"type\": \"number\"},\n        \"category\": {\"type\": \"string\"},\n        \"in_stock\": {\"type\": \"boolean\"}\n    },\n    \"required\": [\"id\", \"name\", \"price\"]\n}`)\n\nextractor := deepseek.NewJSONExtractor(schema)\nvar product Product\nif err := extractor.ExtractJSON(resp, \u0026product); err != nil {\n    log.Fatal(err)\n}\n```\n\nThe `JSONExtractor` can handle JSON responses in various formats:\n- Direct JSON content\n- JSON within code blocks (```json)\n- JSON within regular code blocks (```)\n- JSON embedded in text\n\n### Streaming Chat Completion\n\n```go\nstream, err := client.CreateChatCompletionStream(\n    context.Background(),\n    \u0026deepseek.ChatCompletionRequest{\n        Model: \"deepseek-chat\",\n        Messages: []deepseek.Message{\n            {\n                Role:    deepseek.RoleUser,\n                Content: \"Tell me a story.\",\n            },\n        },\n        Stream: true,\n    },\n)\nif err != nil {\n    log.Fatal(err)\n}\ndefer stream.Close()\n\nfor {\n    response, err := stream.Recv()\n    if err == io.EOF {\n        break\n    }\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Print(response.Choices[0].Delta.Content)\n}\n```\n\n### Token Estimation\n\n```go\n// Estimate tokens in text\ntext := \"Hello 世界!\"\nestimate := client.EstimateTokenCount(text)\nfmt.Printf(\"Estimated tokens: %d\\n\", estimate.EstimatedTokens)\n\n// Estimate tokens in messages\nmessages := []deepseek.Message{\n    {\n        Role:    deepseek.RoleSystem,\n        Content: \"You are a helpful assistant.\",\n    },\n    {\n        Role:    deepseek.RoleUser,\n        Content: \"Hello!\",\n    },\n}\nestimate = client.EstimateTokensFromMessages(messages)\nfmt.Printf(\"Estimated total tokens: %d\\n\", estimate.EstimatedTokens)\n```\n\n### List Available Models\n\n```go\nmodels, err := client.ListModels(context.Background())\nif err != nil {\n    log.Fatal(err)\n}\n\nfor _, model := range models.Data {\n    fmt.Printf(\"- %s:\\n\", model.ID)\n    fmt.Printf(\"  Object: %s\\n\", model.Object)\n    fmt.Printf(\"  Owner: %s\\n\", model.OwnedBy)\n}\n```\n\n### Check Account Balance\n\n```go\nbalance, err := client.GetBalance(context.Background())\nif err != nil {\n    log.Fatal(err)\n}\n\nfmt.Printf(\"Account Status: %v\\n\", balance.IsAvailable)\nfor _, info := range balance.BalanceInfos {\n    fmt.Printf(\"\\nBalance Info for %s:\\n\", info.Currency)\n    fmt.Printf(\"  Total Balance: %s\\n\", info.TotalBalance)\n    fmt.Printf(\"  Granted Balance: %s\\n\", info.GrantedBalance)\n    fmt.Printf(\"  Topped Up Balance: %s\\n\", info.ToppedUpBalance)\n}\n```\n\n## Running Tests\n\n### Setup\n\n1. Copy the example environment file:\n   ```bash\n   cp .env.example .env\n   ```\n\n2. Add your DeepSeek API key to `.env`:\n   ```\n   DEEPSEEK_API_KEY=your_api_key_here\n   ```\n\n   You can get your API key from the [DeepSeek Platform](https://api.deepseek.com).\n\n3. (Optional) Configure test timeout:\n   ```\n   # Default is 30s, increase for slower connections\n   TEST_TIMEOUT=1m\n   ```\n\n### Test Organization\n\nThe tests are organized into several files:\n- `client_test.go`: Client configuration and error handling\n- `chat_test.go`: Chat completion functionality (including streaming)\n- `models_test.go`: Model listing and retrieval\n- `balance_test.go`: Account balance operations\n- `tokens_test.go`: Token estimation utilities\n\n### Running Tests\n\n1. Run all tests (requires API key):\n   ```bash\n   go test -v ./...\n   ```\n\n2. Run tests in short mode (skips API calls):\n   ```bash\n   go test -v -short ./...\n   ```\n\n3. Run tests with race detection:\n   ```bash\n   go test -v -race ./...\n   ```\n\n4. Run tests with coverage:\n   ```bash\n   go test -v -coverprofile=coverage.txt -covermode=atomic ./...\n   ```\n\n   View coverage in browser:\n   ```bash\n   go tool cover -html=coverage.txt\n   ```\n\n5. Run specific test:\n   ```bash\n   # Example: Run only chat completion tests\n   go test -v -run TestCreateChatCompletion ./...\n   ```\n\n### Test Environment Variables\n\n- `DEEPSEEK_API_KEY`: Your DeepSeek API key (required for API tests)\n- `TEST_TIMEOUT`: Test timeout duration (default: 30s)\n\n### Common Issues\n\n1. \"invalid character 'A' looking for beginning of value\":\n   - This usually means the API returned HTML instead of JSON\n   - Check if your API key is valid\n   - Verify you're using the correct API base URL\n\n2. \"context deadline exceeded\":\n   - Increase test timeout in `.env`: `TEST_TIMEOUT=60s`\n   - Check your internet connection\n\n3. \"unexpected end of JSON input\":\n   - The API response was truncated\n   - Could indicate network issues\n   - Try increasing the timeout\n\n4. Tests are skipped:\n   - Make sure `DEEPSEEK_API_KEY` is set in `.env`\n   - For quick testing, use `-short` flag to skip API tests\n\n## Contributing\n\nSee [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to contribute to this project.\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n___\n\n\u003ca href='https://ko-fi.com/O5O31892PV' target='_blank'\u003e\u003cimg height='36' style='border:0px;height:36px;' src='https://storage.ko-fi.com/cdn/kofi6.png?v=6' border='0' alt='Buy Me a Coffee at ko-fi.com' /\u003e\u003c/a\u003e\n\nCreated by [pocok](https://pocok.dev) @ [TrustSight](https://trustsight.io/)\n","funding_links":["https://ko-fi.com/O5O31892PV'"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftrustsight-io%2Fdeepseek-go","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftrustsight-io%2Fdeepseek-go","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftrustsight-io%2Fdeepseek-go/lists"}