> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://developers.meshapi.ai/docs/sd-ks/llms.txt.
> For full documentation content, see https://developers.meshapi.ai/docs/sd-ks/llms-full.txt.

# Go SDK

> Getting started with the MeshAPI Go SDK.

# Go SDK

A fast, zero-dependency Go client for the MeshAPI AI model gateway.

## Requirements

* Go ≥ 1.21

## Installation

```bash
go get github.com/yourorg/meshapi-go-sdk@v0.1.0
```

## Quick Start

### Basic Chat Completion

```go
import "meshapi-go-sdk"

client := meshapi.New(meshapi.Config{
    BaseURL: "https://api.meshapi.ai",
    Token:   "rsk_...",
})

model := "openai/gpt-4o-mini"
resp, err := client.Chat.Completions.Create(ctx, meshapi.ChatCompletionParams{
    Model:    &model,
    Messages: []meshapi.ChatMessage{{Role: "user", Content: "What is 2+2?"}},
})
```

### Streaming Chat Completion

Streaming is handled elegantly using Go channels. The client returns both a data channel and an error channel to process chunks asynchronously.

```go
chunkCh, errCh := client.Chat.Completions.Stream(ctx, params)

for chunk := range chunkCh {
    if len(chunk.Choices) > 0 && chunk.Choices[0].Delta != nil {
        fmt.Print(*chunk.Choices[0].Delta.Content)
    }
}

// Check for errors once the stream closes
if err := <-errCh; err != nil {
    log.Fatal(err)
}
```

## Error Handling & Resiliency

Retries occur automatically on `429`, `502`, `503`, and `504` errors using exponential backoff (defaulting to 3 retries, maximum 30 seconds wait, adhering to the `Retry-After` header).

You can catch structured `MeshAPIError` wrappers:

```go
resp, err := client.Chat.Completions.Create(ctx, params)
if err != nil {
    var svcErr *meshapi.MeshAPIError
    if errors.As(err, &svcErr) {
        fmt.Println(svcErr.Status)     // HTTP status
        fmt.Println(svcErr.Code)       // "rate_limit_exceeded", "spend_limit_exceeded", etc.
        fmt.Println(svcErr.RequestID)  // Trackable request ID
    }
}
```

> \[!WARNING]
> **Streams do not automatically retry!** On a network connection failure mid-stream, the error channel receives a `MeshAPIError` with `Code="stream_interrupted"`. Restarting the `Stream` call is required to resume.