openroutergo

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2025 License: MIT Imports: 14 Imported by: 0

README

OpenRouterGo

A powerful, developer-friendly Go SDK for OpenRouter.ai - the platform that gives you unified access to 100+ AI models from OpenAI, Anthropic, Google, and more through a single consistent API.

Go Reference Go Report Card Release Version License

[!WARNING] This client is not yet stable and the API signature may change in the future until it reaches version 1.0.0, so be careful when upgrading. However, the API signature should not change too much.

Features

  • 🚀 Simple & Intuitive API - Fluent builder pattern with method chaining for clean, readable code
  • 🔄 Smart Fallbacks - Automatically retry with alternative models if your first choice fails or is rate-limited
  • 🛠️ Function Calling - Let AI models access your tools and functions when needed
  • 📊 Structured Outputs - Force responses in valid JSON format with schema validation
  • 🧠 Complete Control - Fine-tune model behavior with temperature, top-p, frequency penalty and more
  • 🔍 Debug Mode - Instantly see the exact requests and responses for easier development

Installation

Go version 1.22 or higher is required.

go get github.com/eduardolat/openroutergo

Quick Start Example

package main

import (
	"fmt"
	"log"

	"github.com/eduardolat/openroutergo"
)

// Replace with your own API key and the model you want to use
const apiKey = "sk......."
const model = "deepseek/deepseek-r1:free"

func main() {
	// Create a client with your API key
	client, err := openroutergo.
		NewClient().
		WithAPIKey(apiKey).
		Create()
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	// Build and execute your request with a fluent API
	completion, resp, err := client.
		NewChatCompletion().
		WithModel(model).
		WithSystemMessage("You are a helpful assistant expert in geography.").
		WithUserMessage("What is the capital of France?").
		Execute()
	if err != nil {
		log.Fatalf("Failed to execute completion: %v", err)
	}

	// Print the model's first response
	fmt.Println("Response:", resp.Choices[0].Message.Content)

	// Continue the conversation seamlessly, the last response is
	// automatically added to the conversation history
	_, resp, err = completion.
		WithUserMessage("That's great! What about Japan?").
		Execute()
	if err != nil {
		log.Fatalf("Failed to execute completion: %v", err)
	}

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

More Examples

We've included several examples to help you get started quickly:

Get Started

  1. Get your API key from OpenRouter.ai
  2. Install the package: go get github.com/eduardolat/openroutergo
  3. Start building with the examples above

About me

I'm Eduardo, if you like my work please ⭐ star the repo and find me on the following platforms:

License

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

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// RoleSystem is the role of a system message in a chat completion.
	RoleSystem = chatCompletionRole{"system"}
	// RoleDeveloper is the role of a developer message in a chat completion.
	RoleDeveloper = chatCompletionRole{"developer"}
	// RoleUser is the role of a user message in a chat completion.
	RoleUser = chatCompletionRole{"user"}
	// RoleAssistant is the role of an assistant message in a chat completion.
	RoleAssistant = chatCompletionRole{"assistant"}
	// RoleTool is the role of a tool message in a chat completion.
	RoleTool = chatCompletionRole{"tool"}
)
View Source
var (
	// FinishReasonStop is when the model hit a natural stop point or a provided stop sequence.
	FinishReasonStop = chatCompletionFinishReason{"stop"}
	// FinishReasonLength is when the maximum number of tokens specified in the request was reached.
	FinishReasonLength = chatCompletionFinishReason{"length"}
	// FinishReasonContentFilter is when content was omitted due to a flag from our content filters.
	FinishReasonContentFilter = chatCompletionFinishReason{"content_filter"}
	// FinishReasonToolCalls is when the model called a tool.
	FinishReasonToolCalls = chatCompletionFinishReason{"tool_calls"}
	// FinishReasonError is when the model returned an error.
	FinishReasonError = chatCompletionFinishReason{"error"}
)
View Source
var (
	// ErrBaseURLRequired is returned when the base URL is needed but not provided.
	ErrBaseURLRequired = errors.New("the base URL is required")

	// ErrAPIKeyRequired is returned when the API key is needed but not provided.
	ErrAPIKeyRequired = errors.New("the API key is required")

	// ErrMessagesRequired is returned when no messages are found and they are needed.
	ErrMessagesRequired = errors.New("at least one message is required")

	// ErrAlreadyExecuting is returned when the user tries to execute an action while
	// there is already an action in progress.
	ErrAlreadyExecuting = errors.New("race condition: the client is currently executing an action")
)

Functions

func NewClient

func NewClient() *clientBuilder

NewClient starts the creation of a new OpenRouter client.

Types

type ChatCompletionMessage

type ChatCompletionMessage struct {
	// The ID of the tool call, if the message is a tool call.
	ToolCallID string `json:"tool_call_id,omitempty,omitzero"`
	// The name of the entity that sent the message or the name of the tool, if the message is a tool call.
	Name string `json:"name,omitempty,omitzero"`
	// Who the message is from. Must be one of openroutergo.RoleSystem, openroutergo.RoleUser, or openroutergo.RoleAssistant.
	Role chatCompletionRole `json:"role"`
	// The content of the message
	Content string `json:"content"`
	// When the model decided to call a tool
	ToolCalls []ChatCompletionMessageToolCall `json:"tool_calls,omitempty,omitzero"`
}

func (ChatCompletionMessage) HasToolCalls

func (c ChatCompletionMessage) HasToolCalls() bool

HasToolCalls returns true if the message has tool calls.

type ChatCompletionMessageToolCall

type ChatCompletionMessageToolCall struct {
	// The ID of the tool call.
	ID string `json:"id"`
	// The type of tool call. Always "function".
	Type string `json:"type"`
	// Function is the function that the model wants to call.
	Function ChatCompletionMessageToolCallFunction `json:"function,omitempty,omitzero"`
}

type ChatCompletionMessageToolCallFunction

type ChatCompletionMessageToolCallFunction struct {
	// The name of the function to call.
	Name string `json:"name"`
	// The arguments to call the function with, as generated by the model in JSON
	// format. Note that the model does not always generate valid JSON, and may
	// hallucinate parameters not defined by your function schema. Validate the
	// arguments in your code before calling your function.
	//
	// You have to unmarshal the arguments to the correct type yourself.
	Arguments string `json:"arguments"`
}

type ChatCompletionResponse

type ChatCompletionResponse struct {
	// A unique identifier for the chat completion.
	ID string `json:"id"`
	// A list of chat completion choices (the responses from the model).
	Choices []ChatCompletionResponseChoice `json:"choices"`
	// Usage statistics for the completion request.
	Usage ChatCompletionResponseUsage `json:"usage"`
	// The Unix timestamp (in seconds) of when the chat completion was created.
	Created int `json:"created"`
	// The model used for the chat completion.
	Model string `json:"model"`
	// The provider used for the chat completion.
	Provider string `json:"provider"`
	// The object type, which is always "chat.completion"
	Object string `json:"object"`
}

ChatCompletionResponse is the response from the OpenRouter API for a chat completion request.

func (ChatCompletionResponse) HasChoices

func (c ChatCompletionResponse) HasChoices() bool

HasChoices returns true if the chat completion has choices.

type ChatCompletionResponseChoice

type ChatCompletionResponseChoice struct {
	// The reason the model stopped generating tokens. This will be `stop` if the model hit a
	// natural stop point or a provided stop sequence, `length` if the maximum number of
	// tokens specified in the request was reached, `content_filter` if content was omitted
	// due to a flag from our content filters, `tool_calls` if the model called a tool, or
	// `error` if the model returned an error.
	FinishReason chatCompletionFinishReason `json:"finish_reason"`
	// A chat completion message generated by the model.
	Message ChatCompletionMessage `json:"message"`
}

type ChatCompletionResponseUsage

type ChatCompletionResponseUsage struct {
	// The number of tokens in the prompt.
	PromptTokens int `json:"prompt_tokens"`
	// The number of tokens in the generated completion.
	CompletionTokens int `json:"completion_tokens"`
	// The total number of tokens used in the request (prompt + completion).
	TotalTokens int `json:"total_tokens"`
}

type ChatCompletionTool

type ChatCompletionTool struct {
	// The name of the tool, when the model calls this tool, it will return this name so
	// you can identify it.
	Name string `json:"name"`
	// The description of the tool, make sure to give a good description so the model knows
	// when to use it.
	Description string `json:"description,omitempty,omitzero"`
	// Make sure to define your tool's parameters using map[string]any and following the
	// JSON Schema format.
	//
	//   - Format example: https://platform.openai.com/docs/guides/function-calling
	//   - JSON Schema reference: https://json-schema.org/understanding-json-schema/reference
	Parameters map[string]any `json:"parameters"`
}

ChatCompletionTool is a tool that can be used in a chat completion request.

type Client

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

Client represents a client for the OpenRouter API.

func (*Client) NewChatCompletion

func (c *Client) NewChatCompletion() *chatCompletionBuilder

NewChatCompletion creates a new chat completion request builder for the OpenRouter API.

Docs:

Directories

Path Synopsis
examples
internal
assert
Package assert provides a set of functions for asserting the results of tests.
Package assert provides a set of functions for asserting the results of tests.

Jump to

Keyboard shortcuts

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