{"id":34143731,"url":"https://github.com/bkovacki/gopenrouter","last_synced_at":"2026-03-09T22:02:55.716Z","repository":{"id":301536011,"uuid":"980912572","full_name":"bkovacki/gopenrouter","owner":"bkovacki","description":"The GOpenRouter library provides convenient access to the OpenRouter REST API from applications written in Go.","archived":false,"fork":false,"pushed_at":"2025-06-03T20:13:49.000Z","size":93,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-12-17T16:33:02.347Z","etag":null,"topics":["ai","ai-models","go","golang","http-client","library","llm","openrouter","rest-api"],"latest_commit_sha":null,"homepage":"","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/bkovacki.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"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,"zenodo":null}},"created_at":"2025-05-10T00:07:03.000Z","updated_at":"2025-06-12T20:26:30.000Z","dependencies_parsed_at":"2025-06-27T11:51:15.088Z","dependency_job_id":null,"html_url":"https://github.com/bkovacki/gopenrouter","commit_stats":null,"previous_names":["bkovacki/gopenrouter"],"tags_count":4,"template":false,"template_full_name":null,"purl":"pkg:github/bkovacki/gopenrouter","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bkovacki%2Fgopenrouter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bkovacki%2Fgopenrouter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bkovacki%2Fgopenrouter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bkovacki%2Fgopenrouter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/bkovacki","download_url":"https://codeload.github.com/bkovacki/gopenrouter/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bkovacki%2Fgopenrouter/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30314397,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-09T20:05:46.299Z","status":"ssl_error","status_checked_at":"2026-03-09T19:57:04.425Z","response_time":61,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"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":["ai","ai-models","go","golang","http-client","library","llm","openrouter","rest-api"],"created_at":"2025-12-15T03:28:49.345Z","updated_at":"2026-03-09T22:02:55.710Z","avatar_url":"https://github.com/bkovacki.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# GOpenRouter\n\nThe GOpenRouter library provides convenient access to the [OpenRouter](https://openrouter.ai/) REST API from applications written in Go. OpenRouter is a unified API that provides access to various AI models from different providers, including OpenAI, Anthropic, Google, and more.\n\n[![Go Reference](https://pkg.go.dev/badge/github.com/bkovacki/gopenrouter.svg)](https://pkg.go.dev/github.com/bkovacki/gopenrouter)\n[![GitHub Release](https://img.shields.io/github/v/release/bkovacki/gopenrouter)](https://github.com/bkovacki/gopenrouter/releases)\n[![CI](https://github.com/bkovacki/gopenrouter/workflows/CI/badge.svg)](https://github.com/bkovacki/gopenrouter/actions)\n[![codecov](https://codecov.io/gh/bkovacki/gopenrouter/graph/badge.svg?token=vXQDEiWmJI)](https://codecov.io/gh/bkovacki/gopenrouter)\n[![License](https://img.shields.io/github/license/bkovacki/gopenrouter)](https://github.com/bkovacki/gopenrouter/blob/main/LICENSE)\n\n\u003e 🚀 **New Feature**: **Real-time streaming support** is now available for both completion and chat endpoints! Build interactive AI applications with live response generation. See the [**Streaming Documentation**](STREAMING.md) for complete details and examples.\n\n## Quick Navigation\n\n| What you want to do | Go to |\n|---------------------|-------|\n| 🚀 Get started quickly | [Installation](#installation) → [Usage](#usage) |\n| 💬 Build chat applications | [Chat Completions](#chat-completions) |\n| ⚡ Implement real-time streaming | [Streaming Documentation](STREAMING.md) |\n| 🔧 Advanced configuration | [Advanced Provider Routing](#advanced-provider-routing) |\n| 📊 Monitor usage and costs | [Checking Credits](#checking-credits-and-usage) |\n| 🎯 See working examples | [Examples](#examples) |\n| 🐛 Handle errors properly | [Error Handling](#error-handling) |\n\n## Features\n\n- Complete OpenRouter API coverage\n- Text completion and chat completion support\n- **Real-time streaming support** for both completion and chat endpoints\n- Builder pattern for constructing requests\n- Customizable HTTP client with middleware support\n- Proper error handling and detailed error types\n- Context support for request cancellation and timeouts\n- Comprehensive documentation and examples\n\n## Installation\n\n```bash\ngo get github.com/bkovacki/gopenrouter\n```\n\n## Requirements\n\nThis library requires Go 1.24+.\n\n## Usage\n\nImport the package in your Go code:\n\n```go\nimport \"github.com/bkovacki/gopenrouter\"\n```\n\n### Creating a client\n\nTo use this library, create a new client with your OpenRouter API key:\n\n```go\nclient := gopenrouter.New(\"your-api-key\")\n```\n\nYou can also customize the client with optional settings:\n\n```go\nclient := gopenrouter.New(\n    \"your-api-key\",\n    gopenrouter.WithSiteURL(\"https://yourapp.com\"),\n    gopenrouter.WithSiteTitle(\"Your App Name\"),\n    gopenrouter.WithHTTPClient(customHTTPClient),\n)\n```\n\n### Text Completions\n\n```go\n// Create a completion request using the builder pattern\nrequest := gopenrouter.NewCompletionRequestBuilder(\n    \"anthropic/claude-3-opus-20240229\",\n    \"Write a short poem about Go programming.\",\n).WithMaxTokens(150).\n  WithTemperature(0.7).\n  Build()\n\n// Send the completion request\nctx := context.Background()\nresp, err := client.Completion(ctx, *request)\nif err != nil {\n    log.Fatalf(\"Completion error: %v\", err)\n}\n\n// Use the response\nfmt.Println(resp.Choices[0].Text)\n```\n\n### Chat Completions\n\n```go\n// Create conversation messages\nmessages := []gopenrouter.ChatMessage{\n    {\n        Role:    \"system\",\n        Content: \"You are a helpful assistant that provides concise answers.\",\n    },\n    {\n        Role:    \"user\",\n        Content: \"What is the capital of France?\",\n    },\n}\n\n// Build chat completion request\nrequest := gopenrouter.NewChatCompletionRequestBuilder(\"openai/gpt-3.5-turbo\", messages).\n    WithMaxTokens(100).\n    WithTemperature(0.7).\n    WithUsage(true).\n    Build()\n\n// Make the chat completion request\nctx := context.Background()\nresponse, err := client.ChatCompletion(ctx, *request)\nif err != nil {\n    log.Fatalf(\"Chat completion failed: %v\", err)\n}\n\n// Use the response\nfmt.Printf(\"Assistant: %s\\n\", response.Choices[0].Message.Content)\n```\n\n### Streaming Responses\n\nThe library provides comprehensive real-time streaming support for both completion and chat completion endpoints. Streaming allows you to:\n\n- **Reduce perceived latency** by displaying responses as they are generated\n- **Build interactive chat interfaces** with real-time feedback\n- **Handle long responses efficiently** without waiting for complete generation\n- **Implement live AI-powered features** with immediate user feedback\n\nQuick streaming example:\n\n```go\nimport (\n    \"context\"\n    \"fmt\"\n    \"io\"\n    \"log\"\n    \n    \"github.com/bkovacki/gopenrouter\"\n)\n\n// Streaming chat completion\nmessages := []gopenrouter.ChatMessage{\n    {Role: \"user\", Content: \"Tell me a story\"},\n}\n\nrequest := gopenrouter.NewChatCompletionRequestBuilder(\"openai/gpt-3.5-turbo\", messages).Build()\n\nstream, err := client.ChatCompletionStream(ctx, *request)\nif err != nil {\n    log.Fatal(err)\n}\ndefer stream.Close()\n\nfmt.Print(\"Assistant: \")\nfor {\n    chunk, err := stream.Recv()\n    if err == io.EOF {\n        break\n    }\n    if err != nil {\n        log.Fatal(err)\n    }\n    \n    for _, choice := range chunk.Choices {\n        if choice.Delta.Content != nil {\n            fmt.Print(*choice.Delta.Content)\n        }\n    }\n}\nfmt.Println()\n```\n\n**📚 For comprehensive streaming documentation including:**\n- Complete API reference and response types\n- Advanced usage patterns and best practices  \n- Error handling and resource management\n- Performance considerations and limitations\n- Migration guide from non-streaming code\n\nSee the [**Streaming Documentation**](STREAMING.md) for complete details and examples.\n\n### Advanced Provider Routing\n\nOpenRouter allows you to customize how your requests are routed between different AI providers:\n\n```go\n// Create provider routing options\nproviderOptions := gopenrouter.NewProviderOptionsBuilder().\n    WithDataCollection(\"deny\").\n    WithSort(\"price\").\n    WithOrder([]string{\"Anthropic\", \"OpenAI\"}).\n    WithIgnore([]string{\"Mistral\"}).\n    Build()\n\n// Include provider options in your completion request\nrequest := gopenrouter.NewCompletionRequestBuilder(\n    \"anthropic/claude-3-opus-20240229\",\n    \"Write a short story about a robot learning to code.\",\n).WithProvider(providerOptions).\n  Build()\n```\n\n### Checking Credits and Usage\n\n```go\n// Get your account credit information\ncredits, err := client.GetCredits(ctx)\nif err != nil {\n    log.Fatalf(\"Error getting credits: %v\", err)\n}\n\nfmt.Printf(\"Total credits: %.2f\\n\", credits.TotalCredits)\nfmt.Printf(\"Total usage: %.2f\\n\", credits.TotalUsage)\n```\n\n### Listing Available Models\n\n```go\n// Get a list of all available models\nmodels, err := client.ListModels(ctx)\nif err != nil {\n    log.Fatalf(\"Error listing models: %v\", err)\n}\n\n// Display model information\nfor _, model := range models {\n    fmt.Printf(\"Model: %s\\n\", model.Name)\n    fmt.Printf(\"  Description: %s\\n\", model.Description)\n    fmt.Printf(\"  Context Length: %.0f tokens\\n\", model.ContextLength)\n}\n```\n\n### Getting Generation Details\n\n```go\n// Get details about a specific generation by its ID\ngenerationID := \"gen_abc123\"\ngeneration, err := client.GetGeneration(ctx, generationID)\nif err != nil {\n    log.Fatalf(\"Error getting generation: %v\", err)\n}\n\nfmt.Printf(\"Generation Cost: $%.6f\\n\", generation.TotalCost)\nfmt.Printf(\"Prompt Tokens: %d\\n\", generation.TokensPrompt)\nfmt.Printf(\"Completion Tokens: %d\\n\", generation.TokensCompletion)\n```\n\n## Examples\n\nThe library includes comprehensive examples to help you get started:\n\n\u003e **⚠️ Cost Warning**: Running these examples will make actual API calls to OpenRouter and will incur charges based on your usage. Please monitor your credits and usage to avoid unexpected costs.\n\n### Simple Completion Example\nLocated in `examples/simple_completion/`, this example demonstrates:\n- Basic text completion with usage reporting\n- Generation details retrieval using the generation endpoint\n- Credits status monitoring before and after requests\n- Cost calculation for individual requests\n- Advanced provider options with cost controls\n\nRun the example:\n```bash\nexport OPENROUTER_API_KEY=\"your-api-key-here\"\ngo run examples/simple_completion/simple_completion.go  # Note: This will incur API charges\n```\n\n### Chat Completion Example\nLocated in `examples/chat_completion/`, this example demonstrates:\n- Basic chat completion with system and user messages\n- Multi-turn conversations with context\n- Provider options for cost control and fallbacks\n- Different AI models (OpenAI, Anthropic, etc.)\n- Parameter tuning (temperature, penalties, etc.)\n\nRun the example:\n```bash\nexport OPENROUTER_API_KEY=\"your-api-key-here\"\ngo run examples/chat_completion/chat_completion.go  # Note: This will incur API charges\n```\n\n### Streaming Example\nLocated in `examples/streaming/`, this example demonstrates:\n- Real-time streaming for both completion and chat completion\n- Handling streaming responses and delta content\n- Model fallback with streaming support\n- Proper stream lifecycle management and error handling\n\nRun the example:\n```bash\nexport OPENROUTER_API_KEY=\"your-api-key-here\"\ngo run examples/streaming/streaming.go  # Note: This will incur API charges\n```\n\n## Error Handling\n\nThe library provides detailed error types for API errors and request errors:\n\n```go\nresp, err := client.Completion(ctx, *request)\nif err != nil {\n    var apiErr *gopenrouter.APIError\n    var reqErr *gopenrouter.RequestError\n    \n    if errors.As(err, \u0026apiErr) {\n        // Handle API-specific error\n        fmt.Printf(\"API Error: %s (Code: %d)\\n\", apiErr.Message, apiErr.Code)\n    } else if errors.As(err, \u0026reqErr) {\n        // Handle request error\n        fmt.Printf(\"Request Error: %s (Status: %d)\\n\", reqErr.Error(), reqErr.HTTPStatusCode)\n    } else {\n        // Handle other errors\n        fmt.Printf(\"Unexpected error: %v\\n\", err)\n    }\n    return\n}\n```\n\n## Development\n\n### Running Tests\n\n```bash\nmake test\n```\n\n### Linting\n\n```bash\nmake lint\n```\n\n### Coverage Report\n\n```bash\nmake cover\nmake cover-html  # Opens coverage report in browser\n```\n\n## Contributing\n\nContributions to GOpenRouter are welcome! Please feel free to submit a Pull Request.\n\n## Roadmap\n\n- [x] Chat completion API support\n- [x] Examples for common use cases\n- [x] Streaming support for completion and chat completion requests\n- [ ] Additional helper methods for advanced use cases\n\n## License\n\nThis library is distributed under the MIT license. See the LICENSE file for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbkovacki%2Fgopenrouter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbkovacki%2Fgopenrouter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbkovacki%2Fgopenrouter/lists"}