Skip to content
inference-gatewayPublic

About

An SDK written in Go for the Inference Gateway.

Topics

Resources

Contributing

Security policy

Stars

4 stars

Watchers

1 watching

Forks

Latest commit

 

History

411 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🚀 Inference Gateway Go SDK

A powerful and easy-to-use Go SDK for the Inference Gateway

Go Reference License: Apache 2.0 Release Go Version

Connect to multiple LLM providers through a unified interface • Stream responses • Function calling • Vision support • Audio support • MCP tools support • Middleware control

Installation • Quick Start • Examples • Documentation


Installation

To install the SDK, use go get:

go get github.com/inference-gateway/sdk

Usage

Creating a Client

To create a client, use the NewClient function:

package main

import (
    "context"
    "log"

    sdk "github.com/inference-gateway/sdk"
)

func main() {
    client := sdk.NewClient(&sdk.ClientOptions{
        BaseURL: "http://localhost:8080/v1",
    })

    if err := client.HealthCheck(context.Background()); err != nil {
        log.Fatalf("gateway is not healthy: %v", err)
    }
}

Using Custom Headers

The SDK supports custom HTTP headers that can be included with all requests. You can set headers in three ways:

  1. Initial headers via ClientOptions:
client := sdk.NewClient(&sdk.ClientOptions{
    BaseURL: "http://localhost:8080/v1",
    Headers: map[string]string{
        "X-Custom-Header": "my-value",
        "User-Agent":      "my-app/1.0",
    },
})
  1. Multiple headers using WithHeaders:
client = client.WithHeaders(map[string]string{
    "X-Request-ID": "abc123",
    "X-Source":     "sdk",
})
  1. Single header using WithHeader:
client = client.WithHeader("Authorization", "Bearer token123")

Headers can be combined and will override previous values if the same header name is used:

client := sdk.NewClient(&sdk.ClientOptions{
    BaseURL: "http://localhost:8080/v1",
    Headers: map[string]string{
        "X-App-Name": "my-app",
    },
})

// Add more headers
client = client.WithHeaders(map[string]string{
    "X-Request-ID": "req-123",
    "X-Version":    "1.0",
}).WithHeader("Authorization", "Bearer token")

// All subsequent requests will include all these headers
response, err := client.GenerateContent(ctx, provider, model, messages)

Retry Mechanism

The SDK includes a built-in retry mechanism for handling transient failures and network issues. By default, the client will automatically retry requests that fail with retryable status codes.

Default Retry Configuration:

client := sdk.NewClient(&sdk.ClientOptions{
    BaseURL: "http://localhost:8080/v1",
    // Default retry configuration is automatically applied
})

The default configuration includes:

  • Max Attempts: 3 in total (the first request plus 2 retries)
  • Backoff Strategy: exponential, starting at 2 seconds and multiplied by 2 per retry, capped at 30 seconds
  • Retryable Status Codes: 408 (Request Timeout), 429 (Too Many Requests), 500 (Internal Server Error), 502 (Bad Gateway), 503 (Service Unavailable), 504 (Gateway Timeout)
  • Retryable Network Errors: timeouts, connection refused, connection reset, DNS errors and unexpected EOF

There is no default request timeout. ClientOptions.Timeout is passed to the underlying http.Client unchanged, so leaving it unset means requests never time out on their own.

Custom Retry Configuration:

You can customize the retry behavior by providing your own retry configuration:

client := sdk.NewClient(&sdk.ClientOptions{
    BaseURL: "http://localhost:8080/v1",
    RetryConfig: &sdk.RetryConfig{
        Enabled:              true,
        MaxAttempts:          5,
        InitialBackoffSec:    1,
        MaxBackoffSec:        30,
        BackoffMultiplier:    2,
        RetryableStatusCodes: []int{408, 429, 500, 502, 503, 504},
    },
})

RetryConfig also accepts OnRetry func(attempt int, err error, delay time.Duration), called before each retry.

A custom RetryConfig replaces the defaults entirely - the defaults are only applied when RetryConfig is nil. Set Enabled: true and every backoff field yourself, otherwise the zero values apply. For example, &sdk.RetryConfig{MaxAttempts: 5} leaves Enabled false and the client silently makes a single attempt.

Exponential Backoff:

The delay before retry n is InitialBackoffSec * BackoffMultiplier^(n-1) seconds, capped at MaxBackoffSec. There is no jitter.

Example delay sequence (with the defaults: 2s InitialBackoffSec, multiplier 2, 30s MaxBackoffSec):

  • 1st retry: 2s
  • 2nd retry: 4s
  • 3rd retry: 8s
  • 4th retry: 16s
  • 5th retry: 30s (capped)

Disabling Retries:

To disable automatic retries, set Enabled to false:

client := sdk.NewClient(&sdk.ClientOptions{
    BaseURL: "http://localhost:8080/v1",
    RetryConfig: &sdk.RetryConfig{
        Enabled: false, // Disables retries
    },
})

executeWithRetry sends exactly one request when Enabled is false or when MaxAttempts is below 1, so MaxAttempts: 0 also turns retries off.

Rate Limiting (429 Status):

When the server returns a 429 (Too Many Requests) status code, the SDK will:

  1. Check for a Retry-After header
  2. If present and at most MaxBackoffSec, wait for that duration before retrying. If it is longer than MaxBackoffSec (and MaxBackoffSec is greater than 0), the SDK treats it as a quota wall: it stops without retrying and returns a *sdk.RateLimitError
  3. If not present, use the standard exponential backoff strategy

Rate Limit Errors:

sdk.RateLimitError carries the gateway's status code, its error message (the {"error": ...} message or the raw body) and the requested wait, so callers can schedule their own retry:

response, err := client.GenerateContent(ctx, provider, model, messages)

var rateLimitErr *sdk.RateLimitError
if errors.As(err, &rateLimitErr) {
    log.Printf("rate limited by %s, retry in %s", provider, rateLimitErr.RetryAfter)
    return
}

Context and Cancellation:

Retries respect the context passed to API methods. If the context is cancelled or times out, retries will stop immediately:

ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()

// Retries will stop if the context times out
response, err := client.GenerateContent(ctx, provider, model, messages)

Middleware Options

The Inference Gateway supports various middleware layers (MCP tools) that can be bypassed. The SDK provides WithMiddlewareOptions to control middleware behavior:

package main

import (
    "context"
    "log"

    sdk "github.com/inference-gateway/sdk"
)

func main() {
    client := sdk.NewClient(&sdk.ClientOptions{
        BaseURL: "http://localhost:8080/v1",
        APIKey:  "your-api-key",
    })

    ctx := context.Background()
    messages := []sdk.Message{
        {Role: sdk.User, Content: sdk.NewMessageContent("Hello, world!")},
    }

    // 1. Skip MCP middleware only
    if _, err := client.WithMiddlewareOptions(&sdk.MiddlewareOptions{
        SkipMCP: true,
    }).GenerateContent(ctx, sdk.Openai, "gpt-4o", messages); err != nil {
        log.Fatalf("Error generating content: %v", err)
    }

    // 2. Direct provider access (no effect: the gateway ignores X-Direct-Provider)
    if _, err := client.WithMiddlewareOptions(&sdk.MiddlewareOptions{
        DirectProvider: true,
    }).GenerateContent(ctx, sdk.Openai, "gpt-4o", messages); err != nil {
        log.Fatalf("Error generating content: %v", err)
    }
}

Middleware Options:

  • SkipMCP - Bypasses MCP (Model Context Protocol) middleware processing
  • DirectProvider - Sets the X-Direct-Provider: true request header, but the gateway currently ignores it, so the option has no effect

Method Chaining:

Middleware options can be chained with other configuration methods:

response, err := client.
    WithHeader("X-Custom-Header", "value").
    WithMiddlewareOptions(&sdk.MiddlewareOptions{
        SkipMCP: true,
    }).
    GenerateContent(ctx, sdk.Openai, "gpt-4o", messages)

Alternative Header Approach:

You can also bypass MCP middleware using its header directly:

response, err := client.
    WithHeader("X-MCP-Bypass", "true").
    GenerateContent(ctx, sdk.Openai, "gpt-4o", messages)

Note: Middleware options apply to all subsequent API calls until overridden with a new WithMiddlewareOptions call. The gateway currently honors only the X-MCP-Bypass header.

Listing Models

To list available models, use the ListModels method:

client := sdk.NewClient(&sdk.ClientOptions{
    BaseURL: "http://localhost:8080/v1",
})

ctx := context.Background()

// List all models from all providers
resp, err := client.ListModels(ctx)
if err != nil {
    log.Fatalf("Error listing models: %v", err)
}
fmt.Printf("All available models: %+v\n", resp.Data)

// List models for a specific provider
groqResp, err := client.ListProviderModels(ctx, sdk.Groq)
if err != nil {
    log.Fatalf("Error listing provider models: %v", err)
}
fmt.Printf("Provider: %s\n", *groqResp.Provider)
fmt.Printf("Available Groq models: %+v\n", groqResp.Data)

// Request additional per-model metadata (?include=context_window)
withCtx, err := client.ListModels(ctx, sdk.ListModelsParamsIncludeContextWindow)
if err != nil {
    log.Fatalf("Error listing models: %v", err)
}
for _, model := range withCtx.Data {
    if model.ContextWindow != nil {
        fmt.Printf("%s context window: %d tokens\n", model.ID, model.ContextWindow.Tokens)
    }
}

MCP JSON-RPC Endpoint

The gateway also exposes itself as an MCP server over JSON-RPC 2.0 at POST /mcp, aggregating every server in MCP_SERVERS behind one URL. Use MCPJSONRPC; the required MCP-Protocol-Version, Mcp-Method and Mcp-Name headers and the params._meta object are filled in for you:

client := sdk.NewClient(&sdk.ClientOptions{
    BaseURL: "http://localhost:8080/v1", // the /v1 suffix is stripped, /mcp lives at the root
    APIKey:  "your-api-key",
})

ctx := context.Background()

request, err := sdk.NewMCPJSONRPCRequest(1, sdk.ToolsList, nil)
if err != nil {
    log.Fatalf("Error building request: %v", err)
}

response, err := client.MCPJSONRPC(ctx, request)
if err != nil {
    log.Fatalf("Error calling MCP endpoint: %v", err)
}

if response.Error != nil {
    log.Fatalf("JSON-RPC error %d: %s", response.Error.Code, response.Error.Message)
}

fmt.Printf("Result: %+v\n", *response.Result)

Calling a tool works the same way - tool names are namespaced mcp_<server alias>_<tool name>:

request, _ := sdk.NewMCPJSONRPCRequest(2, sdk.ToolsCall, map[string]any{
    "name": "mcp_deepwiki_ask_question",
    "arguments": map[string]any{
        "repoName": "inference-gateway/inference-gateway",
        "question": "How is MCP wired up?",
    },
})

response, err := client.MCPJSONRPC(ctx, request)

Methods are sdk.ServerDiscover, sdk.ToolsList and sdk.ToolsCall. Pass nil as the id to send a notification, which the gateway acknowledges with 202 and no body (MCPJSONRPC then returns nil, nil). JSON-RPC level failures come back in response.Error rather than as a Go error; transport and gateway errors (such as a 403 when the endpoint isn't exposed) are returned as errors.

When the gateway has authentication enabled, clients can discover the authorization server through the OAuth 2.0 Protected Resource Metadata document (RFC 9728):

metadata, err := client.GetMCPProtectedResourceMetadata(ctx)
if err != nil {
    log.Fatalf("Error fetching metadata: %v", err)
}

fmt.Printf("Resource: %s\n", metadata.Resource)
fmt.Printf("Authorization servers: %v\n", metadata.AuthorizationServers)

Generating Content

To generate content using a model, use the GenerateContent method:

Note: Some models support reasoning capabilities. You can use the ReasoningFormat parameter to control how reasoning is provided in the response. The model's reasoning will be available in the Reasoning or ReasoningContent fields of the response message.

client := sdk.NewClient(&sdk.ClientOptions{
    BaseURL: "http://localhost:8080/v1",
})

ctx := context.Background()
response, err := client.GenerateContent(
    ctx,
    sdk.Ollama,
    "ollama/llama2",
    []sdk.Message{
        {
            Role:    sdk.System,
            Content: sdk.NewMessageContent("You are a helpful assistant."),
        },
        {
            Role:    sdk.User,
            Content: sdk.NewMessageContent("What is Go?"),
        },
    },
)
if err != nil {
    log.Printf("Error generating content: %v", err)
    return
}

// GenerateContent already returns a decoded *sdk.CreateChatCompletionResponse
message := response.Choices[0].Message

content, err := message.Content.AsMessageContent0()
if err != nil {
    log.Printf("Error reading content: %v", err)
    return
}
fmt.Printf("Generated content: %s\n", content)

// If reasoning was requested and the model supports it
if message.Reasoning != nil {
    fmt.Printf("Reasoning: %s\n", *message.Reasoning)
}

Vision Support

The SDK supports multimodal messages with images for vision-capable models like GPT-4 Vision. You can include images via URLs or base64-encoded data.

Simple Text Message (Backward Compatible)

// Create a simple text message
textMessage, err := sdk.NewTextMessage(sdk.User, "What is Go programming language?")
if err != nil {
    log.Fatal(err)
}

response, err := client.GenerateContent(
    context.Background(),
    sdk.Openai,
    "gpt-4o",
    []sdk.Message{textMessage},
)

Vision Message with Image URL

// Create content parts with text and image
var contentParts []sdk.ContentPart

// Add text part
textPart, err := sdk.NewTextContentPart("What is in this image?")
if err != nil {
    log.Fatal(err)
}
contentParts = append(contentParts, textPart)

// Add image part (auto detail level by default)
imagePart, err := sdk.NewImageContentPart(
    "https://example.com/image.jpg",
    nil, // detail level: nil for auto, or a *sdk.ImageURLDetail
)
if err != nil {
    log.Fatal(err)
}
contentParts = append(contentParts, imagePart)

// Create vision message
visionMessage, err := sdk.NewImageMessage(sdk.User, contentParts)
if err != nil {
    log.Fatal(err)
}

response, err := client.GenerateContent(
    context.Background(),
    sdk.Openai,
    "gpt-4o",
    []sdk.Message{visionMessage},
)

Vision Message with Base64 Encoded Image

// Use high detail level for better image analysis
highDetail := sdk.ImageURLDetailHigh
imagePart, err := sdk.NewImageContentPart(
    "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD...",
    &highDetail,
)
if err != nil {
    log.Fatal(err)
}

Multiple Images in One Message

var contentParts []sdk.ContentPart

// Add text
textPart, _ := sdk.NewTextContentPart("Compare these images:")
contentParts = append(contentParts, textPart)

// Add first image
image1, _ := sdk.NewImageContentPart("https://example.com/image1.jpg", nil)
contentParts = append(contentParts, image1)

// Add second image
image2, _ := sdk.NewImageContentPart("https://example.com/image2.jpg", nil)
contentParts = append(contentParts, image2)

visionMessage, _ := sdk.NewImageMessage(sdk.User, contentParts)

Image Detail Levels: pass a *sdk.ImageURLDetail (the constants are not addressable, so assign one to a variable first, as above)

  • nil or sdk.ImageURLDetailAuto: Automatic detail level (default)
  • sdk.ImageURLDetailLow: Lower resolution, faster and cheaper
  • sdk.ImageURLDetailHigh: Higher resolution, better quality but more expensive

For a complete example, see examples/vision/main.go.

Video Generation

The Videos API is asynchronous: CreateVideo posts a multipart request and returns a VideoJob. Poll RetrieveVideo with the returned job id until its Status is completed, then fetch the rendered bytes with DownloadVideoContent. The gateway must run with VIDEOS_ENABLED=true and a provider that serves the Videos API (currently elevenlabs and mirelo).

client := sdk.NewClient(&sdk.ClientOptions{
    BaseURL: os.Getenv("INFERENCE_GATEWAY_URL"),
})
ctx := context.Background()

job, err := client.CreateVideo(ctx, sdk.Elevenlabs, sdk.CreateVideoRequest{
    Model:   "elevenlabs/creatify-aurora",
    Prompt:  new("A cat surfing a wave"),
    Seconds: new("4"),
    Size:    new("720x1280"),
})
if err != nil {
    log.Fatalf("Error creating video job: %v", err)
}

// Poll the job until it completes
for {
    job, err = client.RetrieveVideo(ctx, sdk.Elevenlabs, job.ID)
    if err != nil {
        log.Fatalf("Error polling video job: %v", err)
    }
    if job.Status == sdk.VideoJobStatusCompleted {
        break
    }
    if job.Status == sdk.VideoJobStatusFailed {
        log.Fatalf("Video job failed: %s", *job.Error.Message)
    }
    time.Sleep(20 * time.Second)
}

video, err := client.DownloadVideoContent(ctx, sdk.Elevenlabs, job.ID)
if err != nil {
    log.Fatalf("Error downloading video: %v", err)
}
os.WriteFile("output.mp4", video, 0644)

Optional file fields such as the first-frame InputReference image are built with openapi_types.File and InitFromBytes, the same way as CreateImageEdit's Image field.

For a complete example, see examples/video/main.go.

Audio Support

The gateway exposes an OpenAI-compatible Audio API for speech, sound effects and music. Run the gateway with AUDIO_ENABLED=true plus the API key of the provider you call - openai, elevenlabs and mirelo serve the Audio API. All three methods return the raw audio bytes, which you can write straight to a file.

Speech

audio, err := client.CreateSpeech(ctx, sdk.Openai, sdk.CreateSpeechRequest{
    Model:          "gpt-4o-mini-tts",
    Input:          "What is Go?",
    Voice:          "alloy",
    ResponseFormat: new(sdk.CreateSpeechRequestResponseFormatMp3),
})
if err != nil {
    log.Fatalf("Error: %v", err)
}
_ = os.WriteFile("output.mp3", audio, 0644)

Sound Effects

Without a video, CreateSFX generates a sound from a text prompt:

audio, err := client.CreateSFX(ctx, sdk.Elevenlabs, sdk.CreateSFXRequest{
    Model:           "elevenlabs/eleven_text_to_sound_v2",
    Prompt:          "distant thunder rolling over a valley",
    DurationSeconds: new(float32(2)),
})

With a video you score the clip instead: set Video to an https URL or a base64 data URI and Output to the track to return (mix, sfx or speech):

videoURL := "https://example.com/clip.mp4"
audio, err := client.CreateSFX(ctx, sdk.Elevenlabs, sdk.CreateSFXRequest{
    Model:  "elevenlabs/music_v2_5",
    Video:  &videoURL,
    Output: new(sdk.CreateSFXRequestOutputMix),
})

Music

audio, err := client.CreateMusic(ctx, sdk.Elevenlabs, sdk.CreateMusicRequest{
    Model:           "elevenlabs/music_v2_5",
    Prompt:          "Upbeat jazz trio with brushed drums and piano",
    DurationSeconds: new(float32(10)),
    Instrumental:    new(true),
})

For complete examples, see examples/speech/main.go, examples/sfx/main.go and examples/music/main.go.

Using ReasoningFormat

You can enable reasoning capabilities by setting the ReasoningFormat parameter in your request:

client := sdk.NewClient(&sdk.ClientOptions{
    BaseURL: "http://localhost:8080/v1",
})

ctx := context.Background()

// Set up your messages
messages := []sdk.Message{
    {
        Role:    sdk.System,
        Content: sdk.NewMessageContent("You are a helpful assistant. Please include your reasoning for complex questions."),
    },
    {
        Role:    sdk.User,
        Content: sdk.NewMessageContent("What is the square root of 144 and why?"),
    },
}

// Create a request with reasoning format
reasoningFormat := "parsed"  // Use "raw" or "parsed" - default to "parsed" if not specified
options := &sdk.CreateChatCompletionRequest{
    ReasoningFormat: &reasoningFormat,
}

// Set options and make the request
response, err := client.WithOptions(options).GenerateContent(
    ctx,
    sdk.Anthropic,
    "anthropic/claude-3-opus-20240229",
    messages,
)

if err != nil {
    log.Fatalf("Error generating content: %v", err)
}

content, err := response.Choices[0].Message.Content.AsMessageContent0()
if err != nil {
    log.Fatalf("Error reading content: %v", err)
}

fmt.Printf("Content: %s\n", content)
if response.Choices[0].Message.Reasoning != nil {
    fmt.Printf("Reasoning: %s\n", *response.Choices[0].Message.Reasoning)
}

Streaming Content

To generate content using streaming mode, use the GenerateContentStream method:

client := sdk.NewClient(&sdk.ClientOptions{
    BaseURL: "http://localhost:8080/v1",
})
ctx := context.Background()
events, err := client.GenerateContentStream(
    ctx,
    sdk.Ollama,
    "ollama/llama2",
    []sdk.Message{
        {
            Role:    sdk.System,
            Content: sdk.NewMessageContent("You are a helpful assistant."),
        },
        {
            Role:    sdk.User,
            Content: sdk.NewMessageContent("What is Go?"),
        },
    },
)
if err != nil {
    log.Fatalf("Error generating content stream: %v", err)
}

// Read events from the stream / channel
for event := range events {
    if event.Event == nil {
        // A read error on the stream: Data holds {"error": "..."}
        if event.Data != nil {
            var errResp struct {
                Error string `json:"error"`
            }
            if err := json.Unmarshal(*event.Data, &errResp); err != nil {
                log.Printf("Error parsing error: %v", err)
                continue
            }
            log.Printf("Error: %s", errResp.Error)
        }
        continue
    }

    switch *event.Event {
    case sdk.ContentDelta:
        if event.Data != nil {
            // Parse the streaming response
            var streamResponse sdk.CreateChatCompletionStreamResponse
            if err := json.Unmarshal(*event.Data, &streamResponse); err != nil {
                log.Printf("Error parsing stream response: %v", err)
                continue
            }

            // Process each choice in the response
            for _, choice := range streamResponse.Choices {
                // Handle reasoning content (both reasoning and reasoning_content fields)
                if choice.Delta.Reasoning != nil && *choice.Delta.Reasoning != "" {
                    fmt.Printf("💭 Reasoning: %s\n", *choice.Delta.Reasoning)
                }
                if choice.Delta.ReasoningContent != nil && *choice.Delta.ReasoningContent != "" {
                    fmt.Printf("💭 Reasoning: %s\n", *choice.Delta.ReasoningContent)
                }

                if choice.Delta.Content != nil {
                    // Just print the content as it comes in
                    fmt.Print(*choice.Delta.Content)
                }
            }
        }

    case sdk.StreamEnd:
        // Stream has ended
        fmt.Println("\nStream ended")
    }
}

Messages API (Anthropic-compatible)

The gateway also exposes an Anthropic-compatible Messages API (POST /messages). Not every provider implements it - unsupported providers return an error, so use GenerateContent for those.

client := sdk.NewClient(&sdk.ClientOptions{
    BaseURL: "http://localhost:8080/v1",
})
ctx := context.Background()

var content sdk.MessagesMessage_Content
if err := content.FromMessagesMessageContent0("What is Go?"); err != nil {
    log.Fatalf("Failed to build content: %v", err)
}

response, err := client.CreateMessage(ctx, sdk.Anthropic, sdk.CreateMessagesRequest{
    Model:     "claude-sonnet-5",
    MaxTokens: 1024,
    Messages: []sdk.MessagesMessage{
        {Role: sdk.MessagesMessageRoleUser, Content: content},
    },
})
if err != nil {
    log.Fatalf("Failed to create message: %v", err)
}

for _, block := range response.Content {
    if text, err := block.AsMessagesTextBlock(); err == nil {
        fmt.Println(text.Text)
    }
}

For streaming, use CreateMessageStream. Each ContentDelta event's Data is a JSON-serialized sdk.MessagesStreamEvent - switch on its Type field (message_start, content_block_delta, message_stop, ...) or just read Delta.Text:

events, err := client.CreateMessageStream(ctx, sdk.Anthropic, request)
if err != nil {
    log.Fatalf("Failed to create message stream: %v", err)
}

for event := range events {
    if event.Event == nil {
        continue
    }
    switch *event.Event {
    case sdk.ContentDelta:
        var streamEvent sdk.MessagesStreamEvent
        if err := json.Unmarshal(*event.Data, &streamEvent); err != nil {
            continue
        }
        if streamEvent.Delta != nil && streamEvent.Delta.Text != nil {
            fmt.Print(*streamEvent.Delta.Text)
        }
    case sdk.StreamEnd:
        fmt.Println("\nStream ended")
    }
}

For a complete example, see examples/messages/main.go.

Tool-Use

To use tools with the SDK, you can define a tool and provide it to the client:

client := sdk.NewClient(&sdk.ClientOptions{
    BaseURL: "http://localhost:8080/v1",
})

// Create tools array with our function
tools := []sdk.ChatCompletionTool{
    {
        Type:     sdk.Function,
        Function: sdk.FunctionObject{
            Name:        "get_current_weather",
            Description: new("Get the current weather in a given location"),
            Parameters: &sdk.FunctionParameters{
                "type": "object",
                "properties": map[string]any{
                    "location": map[string]any{
                        "type":        "string",
                        "enum":        []string{"san francisco", "new york", "london", "tokyo", "sydney"},
                        "description": "The city and state, e.g. San Francisco, CA",
                    },
                    "unit": map[string]any{
                        "type":        "string",
                        "enum":        []string{"celsius", "fahrenheit"},
                        "description": "The temperature unit to use",
                    },
                },
                "required": []string{"location"},
            },
        },
    },
    {
        Type:     sdk.Function,
        Function: sdk.FunctionObject{
            Name:        "get_current_time",
            Description: new("Get the current time in a given location"),
            Parameters: &sdk.FunctionParameters{
                "type": "object",
                "properties": map[string]any{
                    "location": map[string]any{
                        "type":        "string",
                        "enum":        []string{"san francisco", "new york", "london", "tokyo", "sydney"},
                        "description": "The city and state, e.g. San Francisco, CA",
                    },
                },
                "required": []string{"location"},
            },
        },
    },
}

// Provide the tool to the client
client.WithTools(&tools).GenerateContent(ctx, provider, modelName, messages)

Health Check

To check if the API is healthy:

client := sdk.NewClient(&sdk.ClientOptions{
    BaseURL: "http://localhost:8080/v1",
})

ctx := context.Background()
err := client.HealthCheck(ctx)
if err != nil {
    log.Fatalf("Health check failed: %v", err)
}

Examples

For more detailed examples and use cases, check out the examples directory. The examples include:

Most examples include their own README with specific instructions and explanations; the rest are documented inline in main.go.

Supported Providers

The SDK supports the following LLM providers:

  • Ollama (sdk.Ollama)
  • Ollama Cloud (sdk.OllamaCloud)
  • Groq (sdk.Groq)
  • OpenAI (sdk.Openai)
  • DeepSeek (sdk.Deepseek)
  • Cloudflare (sdk.Cloudflare)
  • Cohere (sdk.Cohere)
  • Anthropic (sdk.Anthropic)
  • Google (sdk.Google)
  • Mistral AI (sdk.Mistral)
  • MiniMax (sdk.Minimax)
  • Moonshot (sdk.Moonshot)
  • ElevenLabs (sdk.Elevenlabs)
  • Mirelo (sdk.Mirelo)
  • llama.cpp (sdk.Llamacpp)
  • NVIDIA (sdk.Nvidia)
  • Z.ai (sdk.Zai)
  • Webwright (sdk.Webwright)

Documentation

  1. Install godoc (not part of the Go distribution): go install golang.org/x/tools/cmd/godoc@latest
  2. Run: task docs
  3. Open: http://localhost:6060/pkg/github.com/inference-gateway/sdk

Contributing

Please refer to the CONTRIBUTING.md file for information about how to get involved. We welcome issues, questions, and pull requests.

License

This SDK is distributed under the Apache 2.0 License, see LICENSE for more information.

About

An SDK written in Go for the Inference Gateway.

Topics

Resources

Contributing

Security policy

Stars

4 stars

Watchers

1 watching

Forks

Releases

Used by

Contributors

Languages