turnmeld

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2026 License: MIT Imports: 16 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

English | 简体中文

Turnmeld

Turnmeld: A Multi-Provider LLM Library for Go

Use the Anthropic Messages API with OpenAI, Gemini, Kimi, DeepSeek and more. No proxy server required.

Turnmeld was formerly named Anthropify. New installations use github.com/pejash666/turnmeld from v0.3.0 onward. Existing users should follow the migration guide.

Go Reference Go version License

What is this?

Turnmeld is an open-source Go library for calling Anthropic, OpenAI, Gemini, Kimi, GLM, MiniMax, DeepSeek, AWS Bedrock and Azure OpenAI with the request and response types from the official anthropic-sdk-go. It translates provider protocols in-process and normalizes SSE streaming, tool use and thinking blocks into the Anthropic Messages API shape. Prompt-caching behavior remains provider-specific; see prompt caching. No proxy server or separate service is required.

Keep one []anthropic.MessageParam conversation history and select a configured provider through req.Model. Your application consumes the same anthropic.MessageStreamEventUnion events across providers.

API reference | Runnable examples | OpenAI and Gemini guide

When to use Turnmeld

  • Build a Go agent with one message format across multiple LLM providers.
  • Use OpenAI or Gemini behind an Anthropic-shaped API without deploying a proxy.
  • Switch between configured models while reusing a text conversation's message history.
  • Consume a consistent streaming format for text, tool calls and thinking, subject to each upstream model's capabilities.

Guides

Quick start

package main

import (
    "context"
    "fmt"
    "os"

    "github.com/anthropics/anthropic-sdk-go"
    tm "github.com/pejash666/turnmeld"
)

func main() {
    client, err := tm.New(
        tm.WithChatCompletion("kimi", tm.OpenAICompatConfig{
            BaseURL: "https://api.moonshot.cn/v1",
            APIKey:  os.Getenv("KIMI_API_KEY"),
        }),
        tm.WithModelRoute("kimi-", tm.Route{
            Provider: tm.ProviderChatCompletions,
            Backend:  "kimi",
        }),
    )
    if err != nil {
        panic(err)
    }

    stream, err := client.CreateMessageStream(context.Background(), anthropic.MessageNewParams{
        Model:     "kimi-k2.6",
        MaxTokens: 1024,
        Messages: []anthropic.MessageParam{
            anthropic.NewUserMessage(anthropic.NewTextBlock("Hello, who are you?")),
        },
    })
    if err != nil {
        panic(err)
    }
    defer stream.Close()

    for stream.Next() {
        fmt.Printf("%+v\n", stream.Current()) // anthropic.MessageStreamEventUnion
    }
    if err := stream.Err(); err != nil {
        panic(err)
    }
}

Non-streaming uses the same request type and returns *anthropic.Message:

msg, err := client.CreateMessage(ctx, req)

See it in action

Turnmeld keeps the application's conversation in Anthropic-canonical form while adapters translate it for each upstream. Example 03 runs a text chat across four turns and three providers: Claude plans, Kimi codes, GLM translates, then Claude summarises. It reuses the message history throughout; each turn selects req.Model and its token budget.

model hot-switching

var messages []anthropic.MessageParam
for _, t := range turns {
    messages = append(messages, anthropic.NewUserMessage(anthropic.NewTextBlock(t.question)))
    reply, _ := runTurn(client, t.model, t.maxTokens, messages) // only Model changes
    messages = append(messages, anthropic.NewAssistantMessage(anthropic.NewTextBlock(reply)))
}

See examples/03-model-hot-switching for the full runnable example.

For a walkthrough of provider registration, model routes and portability limits, read Switch LLM providers mid-conversation in Go.

Why Anthropic-canonical?

Streaming protocols differ widely across vendors, and the shape you pick as the canonical event format affects every downstream agent.

  • Anthropic's stream is a small, ordered set of events with explicit content block boundaries: message_start, content_block_start, content_block_delta, content_block_stop, message_delta, message_stop. Text, tool use and thinking each live in their own block.
  • OpenAI Chat Completions packs everything into choices[*].delta. Tool calls, reasoning, and refusals are tacked on as side fields with no structural separation between content kinds.
  • OpenAI Responses splits the same stream into a much larger event set (response.output_item.added, response.content_part.added, response.output_text.delta, and so on). The extra granularity adds bookkeeping without making the wire shape easier to consume.

For an agent framework that needs a stable internal event vocabulary, the Anthropic shape sits at a useful point on the granularity curve. Turnmeld adopts it as the canonical form and normalises every provider into it.

Supported providers

Provider Streaming Non-streaming Tool use Thinking cache_control
Anthropic yes native yes yes top-level + per-block
OpenAI Responses yes drain-and-assemble yes yes (reasoning) server auto
Azure OpenAI yes drain-and-assemble yes yes (reasoning) server auto
Gemini Native yes drain-and-assemble yes yes server auto
Kimi (Moonshot) yes drain-and-assemble yes yes server auto
GLM (Zhipu) yes drain-and-assemble yes model-dependent server auto
MiniMax yes native (anthropic) yes yes top-level + per-block
AWS Bedrock yes native (anthropic) yes yes top-level + per-block
DeepSeek yes drain-and-assemble yes yes (V3.2) server auto

MiniMax speaks the Anthropic protocol natively at https://api.minimax.io/anthropic/v1/messages, so it plugs into the same in-process anthropic adapter as real Claude. Two vendors, one protocol, one adapter — see example 07 for the registration pattern (WithAnthropicCompat("minimax", …) + WithModelRoute("MiniMax-", …)).

AWS Bedrock is the third backend on the same Anthropic-protocol family. The Bedrock branch dispatches through anthropic-sdk-go's official bedrock subpackage, which transparently handles SigV4 signing, the /model/{id}/invoke[-with-response-stream] URL rewrite, the anthropic_version: bedrock-2023-05-31 body injection, the anthropic-beta header → anthropic_beta body translation, and AWS event-stream decoding back into canonical Anthropic SSE events. From the caller's perspective the request and response shapes are identical to Direct or MiniMax. Register with WithAnthropicBedrock and route Bedrock model IDs (or inference-profile ARNs) via WithModelRoute + Route.UpstreamModel. See the AWS Bedrock integration section below.

Azure OpenAI is the second backend on the OpenAI Responses protocol family. Internally rides on the same adapter/openai_responses code path as vanilla OpenAI; only URL composition (deployment-bound vs deployment-less, auto-picked) and auth headers (both api-key and Authorization: Bearer are sent for robustness against APIM gateways and Entra/AAD tokens) differ. Register with WithAzureOpenAI and pin a deployment via AzureOpenAIConfig.Deployment (or leave empty and let the body's model field carry the deployment name). See the Azure OpenAI integration section below.

Turnmeld recommends gemini-3.5-flash (or any Gemini 3.x flash variant). The adapter emits thinkingLevel in generationConfig.thinkingConfig, which the 2.5 series rejects with HTTP 400, so plan to use the 3.x family. Pro-series models (gemini-3-pro-preview, gemini-3.1-pro-preview) require explicit Google preview enrolment and are not assumed available out of the box.

Tested with thinking on gemini-3.5-flash, gemini-3.1-pro-preview, gemini-3-pro-preview, and gemini-pro-latest — all four return canonical thinking blocks with thoughtSignature round-trip on AI Studio billing-enabled projects.

Only the Anthropic adapter exposes a real non-streaming endpoint. For every other provider, CreateMessage opens the stream and assembles the final *anthropic.Message from content blocks.

Routing is prefix-based on req.Model:

Prefix Provider
claude- anthropic
gpt-, o1-, o3- openai_responses
gemini- gemini_native

Kimi / GLM / DeepSeek and other OpenAI-compatible upstreams are registered with WithChatCompletion(name, ...) and routed via WithModelRoute(prefix, Route{Provider: ProviderChatCompletions, Backend: name}).

Anthropic-compatible providers (e.g. MiniMax) plug onto the same anthropic adapter as real Claude via WithAnthropicCompat(name, AnthropicConfig{...}), then route by prefix:

tm.WithAnthropicCompat("minimax", tm.AnthropicConfig{
    BaseURL: "https://api.minimax.io/anthropic",
    APIKey:  os.Getenv("MINIMAX_API_KEY"),
})
tm.WithModelRoute("MiniMax-", tm.Route{
    Provider: tm.ProviderAnthropic, Backend: "minimax",
})

The two backends share one adapter and one routing table — see example 07 for the full demo.

AWS Bedrock integration

AWS Bedrock is the third backend on the Anthropic-protocol family. Turnmeld delegates every Bedrock-specific concern (SigV4 request signing, the /model/{id}/invoke[-with-response-stream] URL rewrite, the anthropic_version: bedrock-2023-05-31 body injection, the anthropic-beta header → anthropic_beta body translation, and the AWS event-stream binary frame decoding) to the official bedrock subpackage of anthropic-sdk-go. From your code's perspective, a Bedrock backend is byte-identical to Direct or MiniMax: same anthropic.MessageNewParams request, same MessageStreamEventUnion streaming, same *anthropic.Message non-streaming response.

Register Bedrock under any name and route specific model prefixes (or exact model names) at it via the standard WithModelRoute machinery. Bedrock requires per-account model identifiers — full names like anthropic.claude-opus-4-5-20250929-v1:0 or inference-profile ARNs like arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/abcdef — so the canonical pattern is to keep your req.Model short and let Route.UpstreamModel rewrite it on dispatch.

client, err := tm.New(
    tm.WithAnthropic(tm.AnthropicConfig{
        APIKey: os.Getenv("ANTHROPIC_API_KEY"),
    }),
    tm.WithAnthropicBedrock("bedrock", tm.BedrockConfig{
        AccessKeyID:     os.Getenv("AWS_ACCESS_KEY_ID"),
        SecretAccessKey: os.Getenv("AWS_SECRET_ACCESS_KEY"),
        // SessionToken is optional: only set for STS / SSO temporary keys.
        Region: "us-east-1",
    }),
    tm.WithModelRoute("claude-opus-4-5", tm.Route{
        Provider:      tm.ProviderAnthropic,
        Backend:       "bedrock",
        UpstreamModel: "anthropic.claude-opus-4-5-20250929-v1:0",
    }),
)
if err != nil {
    log.Fatal(err)
}

req := anthropic.MessageNewParams{
    Model:     "claude-opus-4-5", // canonical short name
    MaxTokens: 1024,
    Messages: []anthropic.MessageParam{
        anthropic.NewUserMessage(anthropic.NewTextBlock("Hello from Bedrock!")),
    },
}
msg, err := client.CreateMessage(ctx, req) // routed to Bedrock via the route table

A few notes:

  • No built-in model ID table. Inference-profile ARNs are account- and region-specific; published Bedrock model IDs change per release. Route.UpstreamModel is the single authoritative hook — keeping the mapping table inside your config is the only way to guarantee correctness for your account.
  • anthropic-beta flags work transparently. Set them via BedrockConfig.ExtraHeaders["anthropic-beta"] = []string{"…"}; the SDK's bedrock middleware lifts each value into the request body's anthropic_beta array because Bedrock rejects the HTTP header.
  • cache_control on Bedrock. The two forms behave differently:
    • Top-level (the v0.2.0 SetCacheControl automatic-caching helper) is forwarded verbatim, but Bedrock's schema hard-rejects it with 400 ValidationException: cache_control: Extra inputs are not permitted — this form does not work on Bedrock.
    • Per-block (cache_control set directly on a system / messages / tools content block) is accepted and does cache. Each cache checkpoint has a per-model minimum token count (e.g. Claude Haiku 4.5 requires ≥4096 tokens per breakpoint); below that threshold no cache_creation_input_tokens / cache_read_input_tokens are reported. Above the threshold, caching behaves identically to native Anthropic — verified live against us.anthropic.claude-haiku-4-5-20251001-v1:0 in us-east-1 via both a raw aws bedrock-runtime invoke-model call and the turnmeld Bedrock adapter.
  • SessionToken is optional. Set it only for STS-vended or AWS-SSO temporary credentials; long-lived IAM-user keys never have one. When set, turnmeld threads it through SigV4 as X-Amz-Security-Token.
  • Multiple AWS accounts. Register one WithAnthropicBedrock("aws-prod", …) per account and route different model prefixes at each. Turnmeld intentionally does not embed a load-balancer in the protocol shim.

See docs/design/v0.2.0-aws-bedrock.md for the full design rationale.

Azure OpenAI integration

Azure OpenAI is the second backend on the OpenAI Responses-protocol family. Turnmeld routes Azure traffic through the same adapter/openai_responses code path as vanilla OpenAI — the canonical BuildRequest and the SSE → Anthropic event converter are shared verbatim. Only two things differ at the network boundary:

  • URL composition. Azure exposes Responses under <resource>/openai/responses?api-version=… (deployment-less) or <resource>/openai/deployments/<deployment>/responses?api-version=… (deployment-bound). Turnmeld auto-picks based on whether AzureOpenAIConfig.Deployment is set.
  • Authentication. Azure historically uses an api-key header for resource keys; Entra/AAD access tokens use Authorization: Bearer; APIM gateways may strip one or the other. Turnmeld sends both on every request so a single APIKey value works regardless of whether you supplied a resource key or an AAD token.

Register Azure under any backend name and route specific model prefixes (or exact model names) at it via the standard WithModelRoute machinery. The typical pattern is one WithAzureOpenAI(...) per Azure deployment plus an explicit WithModelRoute so callers keep using canonical short model names:

client, err := tm.New(
    tm.WithAzureOpenAI("azure", tm.AzureOpenAIConfig{
        BaseURL:    "https://my-resource.openai.azure.com",
        APIKey:     os.Getenv("AZURE_OPENAI_API_KEY"),
        APIVersion: "2025-03-01-preview",
        Deployment: "gpt-5-deployment",
    }),
    tm.WithModelRoute("gpt-5", tm.Route{
        Provider: tm.ProviderOpenAIResponses,
        Backend:  "azure",
    }),
)
if err != nil {
    log.Fatal(err)
}

req := anthropic.MessageNewParams{
    Model:     "gpt-5", // canonical short name
    MaxTokens: 1024,
    Messages: []anthropic.MessageParam{
        anthropic.NewUserMessage(anthropic.NewTextBlock("Hello from Azure!")),
    },
}
msg, err := client.CreateMessage(ctx, req) // routed to the "azure" backend

A few notes:

  • APIVersion is required. Turnmeld deliberately does not pick a default ?api-version= value so upgrades stay visible in source control. Use the version your Azure resource is pinned to (e.g. 2025-03-01-preview).
  • Deployment-less URL form. Leave Deployment empty when you want the body's model field to drive the deployment selection — useful when one Azure resource hosts many deployments and you want to route via Route.UpstreamModel instead. The layered fallback is cfg.Deployment > Route.UpstreamModel > req.Model.
  • Backend-name namespace. WithOpenAIResponsesCompat("foo", ...) and WithAzureOpenAI("foo", ...) collide. The duplicate is rejected at New() with an explicit error. Pick distinct names (e.g. "openai" and "azure").
  • cache_control on Azure. Both per-block and v0.2.0 top-level forms are forwarded verbatim. Azure caches automatically server- side, identical to vanilla OpenAI Responses.
  • Multiple deployments. Register one WithAzureOpenAI("azure-gpt5", …) per deployment and route different model prefixes at each. Turnmeld intentionally does not embed routing logic in the adapter.

See docs/design/v0.2.0-azure-responses.md for the full design rationale.

Prompt caching

Turnmeld supports both Anthropic prompt-caching modes:

  • Top-level automatic (v0.2.0+). One toggle on the request, the upstream picks the optimal cache breakpoint and slides it forward as the conversation grows.

    req := anthropic.MessageNewParams{
        Model:     anthropic.Model("claude-opus-4-7"),
        MaxTokens: 1024,
        System:    longSystemPrompt, // big shared context
        Messages:  conversation,
    }
    tm.SetCacheControl(&req, tm.CacheControl{Type: tm.CacheControlEphemeral})
    msg, err := client.CreateMessage(ctx, req)
    
  • Per-block manual 4-tag. Continues to work via the SDK's per-block SetExtraFields(map[string]any{"cache_control": ...}) on system / messages / tools content blocks. Use this when you need to pin the cache breakpoint to a specific block.

The two modes can be combined; if both are set Anthropic resolves them per the official docs.

Provider behaviour matrix

SetCacheControl is only translated to a wire field on the anthropic adapter (real Claude and MiniMax via WithAnthropicCompat). On every other backend it is a documented, silent no-op — those upstreams cache automatically server-side and have no analogous request field:

Provider Top-level SetCacheControl effect
Anthropic emits {"cache_control":{"type":"ephemeral"}}
MiniMax same wire body via the anthropic adapter
AWS Bedrock forwarded verbatim, but Bedrock rejects it with 400 ValidationException — use per-block cache_control instead (see AWS Bedrock integration)
OpenAI Responses no-op (auto-cached server-side, prompts >1024 t)
Azure OpenAI no-op (auto-cached server-side, prompts >1024 t)
Gemini Native no-op (Gemini 2.5+ implicit caching server-side)
Kimi (Moonshot) no-op (auto prefix cache server-side)
GLM (Zhipu) no-op (auto cache server-side)

This means you can call SetCacheControl(&req, ...) unconditionally in a multi-provider routing layer — it will activate on Claude and be quietly ignored everywhere else.

v0.2.0 ships only the default 5-minute TTL ({"type":"ephemeral"}). The 1-hour extended-cache form is gated behind an Anthropic beta header upstream and will be exposed in a later release.

Gemini provider configuration

The Gemini adapter speaks three auth flavours against two upstream hosts. The mode is selected explicitly via GeminiMode; GeminiModeAuto keeps the original heuristic (project+location implies Vertex, otherwise Studio).

Mode When to use Endpoint Auth
Studio Free tier, prototyping generativelanguage.googleapis.com/v1beta API key (AIza...) via ?key=
Express Vertex with simplified auth aiplatform.googleapis.com/v1/publishers/google API key (AQ.*) via ?key=
Vertex Production, GCP-native aiplatform.googleapis.com/v1/projects/<p>/locations/<l> OAuth2 Bearer token
// Studio
tm.WithGemini(tm.GeminiConfig{
    Mode:   tm.GeminiModeStudio,
    APIKey: os.Getenv("GEMINI_API_KEY"),
})
// Express (Vertex with API key)
tm.WithGemini(tm.GeminiConfig{
    Mode:   tm.GeminiModeExpress,
    APIKey: os.Getenv("VERTEX_EXPRESS_KEY"), // AQ.*
})
// Vertex (OAuth2)
tm.WithGemini(tm.GeminiConfig{
    Mode:     tm.GeminiModeVertex,
    Project:  os.Getenv("VERTEX_PROJECT"),
    Location: os.Getenv("VERTEX_LOCATION"),
    APIKey:   bearerToken, // gcloud auth print-access-token
})

Installation

go get github.com/pejash666/turnmeld@v0.3.0

Requires Go 1.24 or later.

How Turnmeld compares

Turnmeld is intentionally narrow: a Go library that converts between Anthropic-canonical events and provider-native protocols. It is not a proxy server, not a routing layer, not a multi-tenant gateway, and ships no cmd/, no YAML, and no daemon.

If you need a hosted proxy with auth, rate-limiting, billing, and multi-tenancy out of the box, LiteLLM is a more complete solution and is Python-first. If you need a Go-native library to embed inside an agent — with first-party streaming, tool use, and the Anthropic canonical event shape — Turnmeld is built for that.

Status

alpha. APIs may change. All four adapter paths are real-API tested (25 E2E tests, 0 failures across Anthropic / OpenAI / Gemini / Kimi / GLM / DeepSeek). Production users should pin to a specific commit.

Testing

Unit tests are fixture-driven and never touch the network:

go test ./...

Real-network smoke tests live under e2e/ and are gated behind a build tag:

cp .env.e2e.example .env.e2e   # fill in only the providers you have keys for
make test-e2e                  # loads .env.e2e and runs `go test -tags=e2e ./e2e/...`

Providers whose API key is unset are skipped automatically. See e2e/README.md for the per-provider matrix. .env.e2e is git-ignored; only .env.e2e.example is tracked.

Contributing

Issues and pull requests are welcome. Before sending a PR:

  • go test ./... must pass.
  • If you change adapter behaviour, add a corresponding E2E test under e2e/ and verify with make test-e2e against a real key.
  • Keep the public API aliased to github.com/anthropics/anthropic-sdk-go types where possible; do not introduce parallel request/response shapes.

License

MIT. See LICENSE.

Documentation

Overview

Package turnmeld is a Go library for using the Anthropic Messages API with Anthropic, OpenAI, Gemini and OpenAI-compatible LLM providers.

Message request and response types are aliases to github.com/anthropics/anthropic-sdk-go. Provider adapters translate requests in-process and normalize streaming text, tool use and thinking events into Anthropic-shaped content blocks, without requiring a proxy server.

Construct a Client with New and provider options such as WithAnthropic, WithOpenAI, WithGemini or WithChatCompletion. Use WithModelRoute to route model names to configured backends. CreateMessageStream returns canonical streaming events; CreateMessage returns an assembled Message.

Index

Constants

View Source
const (
	SchemaPolicyStrict     = schema.PolicyStrict
	SchemaPolicyLossy      = schema.PolicyLossy
	SchemaPolicyBestEffort = schema.PolicyBestEffort
)

Re-exports of the underlying enum constants. See SchemaPolicy.

View Source
const (
	GeminiModeAuto    = geminiadapter.GeminiModeAuto
	GeminiModeStudio  = geminiadapter.GeminiModeStudio
	GeminiModeExpress = geminiadapter.GeminiModeExpress
	GeminiModeVertex  = geminiadapter.GeminiModeVertex
)

Re-exported Gemini mode constants. See adapter/gemini_native for the authoritative documentation of each variant.

View Source
const (
	AnthropicModeDirect  = anthropicadapter.AnthropicModeDirect
	AnthropicModeBedrock = anthropicadapter.AnthropicModeBedrock
)

Re-exported Anthropic mode constants.

Variables

View Source
var (
	// ErrProviderNotConfigured is returned when routing selects a provider
	// that was never registered via the functional options.
	ErrProviderNotConfigured = errors.New("turnmeld: provider not configured")
	// ErrUnknownModel is returned when no route rule matches the request
	// model and no override is installed.
	ErrUnknownModel = errors.New("turnmeld: unable to route model")
	// ErrStreamClosed is returned by StreamReader when the upstream stream
	// has been fully consumed.
	ErrStreamClosed = errors.New("turnmeld: stream closed")
	// ErrUnsupported is returned by adapters that lack a native
	// non-streaming endpoint. The top-level Client uses errors.Is to
	// detect this sentinel and falls back to draining Stream. It is an
	// alias of adapter.ErrUnsupported so every adapter and the parent
	// package share one comparable value.
	ErrUnsupported = adapter.ErrUnsupported
)

Sentinel errors exposed to callers. Wrap using fmt.Errorf("%w: ...", err).

View Source
var ErrSchemaIncompatible = schema.ErrSchemaIncompatible

ErrSchemaIncompatible is returned (wrapped) by adapters when a tool's input_schema cannot be losslessly converted to the upstream dialect under the active SchemaPolicy. Detect with errors.Is.

Functions

func SetCacheControl

func SetCacheControl(req *MessageNewParams, cc CacheControl)

SetCacheControl installs (or, when cc.Type == "", clears) a top-level cache_control directive on req. It writes via the SDK's param.metadata.SetExtraFields, so the canonical struct stays dependency-free of turnmeld-private state and any other extra fields the caller has installed are preserved.

Calling SetCacheControl is idempotent and safe to call repeatedly.

v0.2.0 only ships {Type: CacheControlEphemeral} (the default 5-minute TTL). The 1-hour TTL form is gated behind a beta header upstream and will be added in a later release.

Types

type AnthropicConfig

type AnthropicConfig struct {
	APIKey       string
	BaseURL      string
	Version      string // defaults to "2023-06-01"
	ExtraHeaders http.Header
}

AnthropicConfig configures the Anthropic passthrough adapter.

type AnthropicMode

type AnthropicMode = anthropicadapter.AnthropicMode

AnthropicMode re-exports the adapter-level mode enum. The zero value (AnthropicModeDirect) preserves v0.1.x behaviour; users do not normally interact with this type — WithAnthropic / WithAnthropicCompat default to Direct, and WithAnthropicBedrock selects Bedrock internally.

type AzureOpenAIConfig

type AzureOpenAIConfig struct {
	// BaseURL is the Azure resource endpoint, e.g.
	// "https://my-resource.openai.azure.com" (no path). Required.
	BaseURL string
	// APIKey is either an Azure resource key or an Entra (AAD)
	// access token. Required.
	APIKey string
	// APIVersion is the ?api-version=... query value, e.g.
	// "2025-03-01-preview". Required — turnmeld deliberately does
	// not pick a default so api-version upgrades stay visible in
	// source control.
	APIVersion string
	// Deployment, when non-empty, pins this backend to a single Azure
	// deployment and selects the deployment-bound URL form. Empty
	// falls back to the deployment-less URL form, in which case the
	// deployment name is read from the request body's model field
	// (the caller's req.Model, optionally rewritten by
	// Route.UpstreamModel).
	Deployment string
	// ExtraHeaders is merged into every request.
	ExtraHeaders http.Header
}

AzureOpenAIConfig configures an Azure OpenAI Responses backend. Registered via WithAzureOpenAI; multiple backends may be registered under distinct names. Internally this rides on the same adapter/openai_responses code path as vanilla OpenAI — only URL composition and authentication headers differ.

Two URL forms are supported, auto-picked by whether Deployment is set:

  • Deployment != "" => deployment-bound URL <BaseURL>/openai/deployments/<Deployment>/responses?api-version=<APIVersion>
  • Deployment == "" => deployment-less URL <BaseURL>/openai/responses?api-version=<APIVersion> The body's model field then carries the deployment name verbatim (the caller's req.Model after Route.UpstreamModel rewrite).

Both api-key and Authorization: Bearer headers are sent on every request — the former is Azure's canonical key header, the latter is required for Entra/AAD access tokens and works with resource keys too. This belt-and-suspenders approach is robust against APIM gateways that strip one or the other.

Backend names share the same namespace as WithOpenAIResponsesCompat; registering both helpers under the same name is rejected at New() time. See docs/design/v0.2.0-azure-responses.md for the authoritative design and rationale.

type BedrockConfig

type BedrockConfig struct {
	// AccessKeyID is the AWS access key ID. Required.
	AccessKeyID string
	// SecretAccessKey is the AWS secret access key. Required.
	SecretAccessKey string
	// SessionToken is optional and only used for STS-vended / SSO
	// temporary credentials. Leave empty for long-lived IAM-user keys.
	SessionToken string
	// Region is the AWS region of the Bedrock runtime endpoint, e.g.
	// "us-east-1". Required.
	Region string
	// BaseURL overrides the default
	// https://bedrock-runtime.<region>.amazonaws.com host. Intended
	// for tests pointing at httptest.NewServer; production callers
	// should leave it empty.
	BaseURL string
	// ExtraHeaders is merged onto every request before the SDK's
	// bedrock middleware runs. Set "anthropic-beta" here to get the
	// SDK's automatic header-to-body translation.
	ExtraHeaders http.Header
}

BedrockConfig configures an AWS Bedrock backend that speaks the Anthropic protocol. Registered via WithAnthropicBedrock; multiple backends may be registered under distinct names. Behind the scenes requests dispatch through anthropic-sdk-go's bedrock subpackage, which handles SigV4 signing, URL rewriting, anthropic_version body injection, "anthropic-beta" header to body translation, and AWS event-stream decoding. See docs/design/v0.2.0-aws-bedrock.md for the full division of responsibilities.

type CacheControl

type CacheControl struct {
	Type CacheControlType `json:"type"`
}

CacheControl is the canonical top-level prompt-caching toggle.

Effects per backend:

  • anthropic / anthropic-compat (incl. MiniMax): emitted as {"cache_control":{"type":"ephemeral"}} at the request top level.
  • openai_responses, gemini_native, chat_completions: documented no-op; those backends auto-cache server-side.

Per-block manual cache_control breakpoints set on individual content blocks are unaffected and continue to work in both modes.

func GetCacheControl

func GetCacheControl(req MessageNewParams) (CacheControl, bool)

GetCacheControl returns the currently-installed top-level cache_control directive on req, if any. Useful for tests and for adapters that want to peek (only the anthropic adapter does today).

The second return is false when no top-level cache_control has been installed via SetCacheControl, or when the installed value has an unrecognised shape.

type CacheControlType

type CacheControlType string

CacheControlType discriminates a cache_control entry. Currently the only legal value is CacheControlEphemeral.

const (
	// CacheControlEphemeral asks the upstream to cache the longest
	// cacheable prefix for ~5 minutes. Equivalent to the JSON value
	// {"type":"ephemeral"} placed at the top level of the request.
	CacheControlEphemeral CacheControlType = "ephemeral"
)

type Client

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

Client is the top-level entry point. Construct one with New.

func New

func New(opts ...Option) (*Client, error)

New constructs a Client and pre-creates each enabled adapter so that subsequent requests share connections/SDK state.

func (*Client) CreateMessage

func (c *Client) CreateMessage(ctx context.Context, req anthropic.MessageNewParams) (*anthropic.Message, error)

CreateMessage performs a non-streaming request. When the adapter exposes a native non-streaming endpoint it is used; otherwise the stream is drained and the final message assembled from content blocks.

func (*Client) CreateMessageStream

func (c *Client) CreateMessageStream(ctx context.Context, req anthropic.MessageNewParams) (*StreamReader, error)

CreateMessageStream dispatches req to the routed provider and returns a StreamReader emitting Anthropic-shaped events.

type GeminiConfig

type GeminiConfig struct {
	// Mode selects between Auto (heuristic), Studio, Express, and
	// Vertex. The zero value (Auto) preserves the legacy behaviour:
	// project+location => Vertex, otherwise APIKey => Studio.
	Mode GeminiMode
	// Project is the GCP project ID. Required for Vertex mode.
	Project string
	// Location is the GCP region (e.g. "us-central1"). Required for Vertex mode.
	Location string
	// Publisher defaults to "google".
	Publisher string
	// APIKey carries either an AI Studio key (Studio mode), a Vertex
	// Express key such as AQ.* (Express mode), or a Bearer access
	// token (Vertex mode).
	APIKey string
	// BaseURL overrides the default upstream host for the resolved mode.
	BaseURL string
	// ExtraHeaders is merged into every request.
	ExtraHeaders http.Header
}

GeminiConfig configures the Gemini Vertex streamGenerateContent adapter.

type GeminiMode

type GeminiMode = geminiadapter.GeminiMode

GeminiMode re-exports the adapter-level mode enum so callers do not need to import the adapter package directly.

type Message

type Message = anthropic.Message

Message is the canonical non-streaming response.

type MessageNewParams

type MessageNewParams = anthropic.MessageNewParams

MessageNewParams is the canonical request type (Anthropic Messages API). Re-exported so callers only need to depend on this package.

type MessageStreamEventUnion

type MessageStreamEventUnion = anthropic.MessageStreamEventUnion

MessageStreamEventUnion is the canonical streaming event emitted by the StreamReader. All adapters normalise their upstream protocol into this shape.

func DecodeEvent

func DecodeEvent(data []byte) (MessageStreamEventUnion, error)

DecodeEvent parses a raw Anthropic-JSON event payload into a typed event. Exposed for callers that consume SSE themselves (e.g. testing).

type OpenAICompatConfig

type OpenAICompatConfig struct {
	// BaseURL must not end with "/chat/completions"; the adapter appends it.
	BaseURL string
	// APIKey is forwarded as Authorization: Bearer <APIKey>.
	APIKey string
	// ExtraHeaders is merged into every request.
	ExtraHeaders http.Header
	// DefaultModel, when non-empty, is substituted into the outgoing
	// request if the user did not provide an explicit model.
	DefaultModel string
}

OpenAICompatConfig configures a single OpenAI-compatible ChatCompletion backend. Multiple backends may be registered under distinct names.

type OpenAIConfig

type OpenAIConfig = OpenAIResponsesConfig

OpenAIConfig is the legacy alias for OpenAIResponsesConfig retained for source compatibility with v0.1.x callers.

type OpenAIResponsesConfig

type OpenAIResponsesConfig struct {
	// APIKey is the Bearer token used when calling the upstream.
	APIKey string
	// BaseURL overrides the default https://api.openai.com endpoint.
	// Useful for Azure OpenAI or OpenRouter.
	BaseURL string
	// Organization, if set, is forwarded as the OpenAI-Organization header.
	Organization string
	// Project, if set, is forwarded as the OpenAI-Project header.
	Project string
	// ExtraHeaders is merged into every request.
	ExtraHeaders http.Header
}

OpenAIResponsesConfig configures the OpenAI Responses adapter (GPT-5 family). Multiple backends may be registered under distinct names via WithOpenAIResponsesCompat; the legacy WithOpenAI is sugar for the default-named "openai" slot.

type Option

type Option func(*config)

Option mutates an internal config struct during Client construction.

func WithAnthropic

func WithAnthropic(cfg AnthropicConfig) Option

WithAnthropic enables the Anthropic passthrough adapter under the default "anthropic" backend slot. Equivalent to WithAnthropicCompat("anthropic", cfg).

func WithAnthropicBedrock

func WithAnthropicBedrock(name string, cfg BedrockConfig) Option

WithAnthropicBedrock registers an AWS Bedrock backend under the given name. Multiple calls accumulate; the name is used as the Route.Backend value, exactly like WithAnthropicCompat. Bedrock requires per-account model identifiers (e.g. "anthropic.claude-opus-4-5-20250929-v1:0" or an inference-profile ARN), so the typical usage pairs this option with WithModelRoute:

tm.WithAnthropicBedrock("bedrock", tm.BedrockConfig{
    AccessKeyID:     os.Getenv("AWS_ACCESS_KEY_ID"),
    SecretAccessKey: os.Getenv("AWS_SECRET_ACCESS_KEY"),
    Region:          "us-east-1",
}),
tm.WithModelRoute("claude-opus-4-5", tm.Route{
    Provider:      tm.ProviderAnthropic,
    Backend:       "bedrock",
    UpstreamModel: "anthropic.claude-opus-4-5-20250929-v1:0",
}),

Turnmeld intentionally ships no built-in model-ID mapping table — inference-profile ARNs are account-scoped, so Route.UpstreamModel remains the single authoritative hook.

All Bedrock-specific concerns (SigV4 signing, URL path rewrite, anthropic_version body injection, anthropic-beta header to body translation, AWS event-stream decoding) are delegated to anthropic-sdk-go's bedrock subpackage. See docs/design/v0.2.0-aws-bedrock.md for the full design.

func WithAnthropicCompat

func WithAnthropicCompat(name string, cfg AnthropicConfig) Option

WithAnthropicCompat registers an Anthropic-protocol backend under the given name. Multiple calls accumulate; the name is used as the Route.Backend value. To address this backend, add a prefix rule via WithModelRoute, e.g.

tm.WithModelRoute("MiniMax-",
    tm.Route{Provider: tm.ProviderAnthropic, Backend: "minimax"})

The reserved name "anthropic" is the default-named slot used by the built-in claude-* prefix routes; WithAnthropic is sugar for WithAnthropicCompat("anthropic", cfg).

func WithAzureOpenAI

func WithAzureOpenAI(name string, cfg AzureOpenAIConfig) Option

WithAzureOpenAI registers an Azure OpenAI Responses backend under the given name. Multiple calls accumulate; the name is used as the Route.Backend value. Backend names share the same namespace as WithOpenAIResponsesCompat — registering both helpers under the same name is rejected at New() time.

Typical usage pairs this option with WithModelRoute, since Azure deployment names are usually distinct from canonical OpenAI model names:

tm.WithAzureOpenAI("azure", tm.AzureOpenAIConfig{
    BaseURL:    "https://my-resource.openai.azure.com",
    APIKey:     os.Getenv("AZURE_OPENAI_API_KEY"),
    APIVersion: "2025-03-01-preview",
    Deployment: "gpt-5-deployment",
}),
tm.WithModelRoute("gpt-5", tm.Route{
    Provider: tm.ProviderOpenAIResponses,
    Backend:  "azure",
}),

See docs/design/v0.2.0-azure-responses.md for the authoritative design covering URL forms, dual-auth headers, and the layered model fallback (cfg.Deployment > Route.UpstreamModel > req.Model).

func WithChatCompletion

func WithChatCompletion(name string, cfg OpenAICompatConfig) Option

WithChatCompletion registers an OpenAI-compatible ChatCompletion backend under the given name. Multiple calls accumulate; the name is used as the Route.Backend value.

func WithGemini

func WithGemini(cfg GeminiConfig) Option

WithGemini enables the Gemini native adapter.

func WithHTTPClient

func WithHTTPClient(h *http.Client) Option

WithHTTPClient injects a shared http.Client. Passing nil restores the default (http.DefaultClient).

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger installs an slog.Logger. When nil (the default) the library emits no log output.

func WithModelOverride

func WithModelOverride(fn func(model string) (Route, bool)) Option

WithModelOverride installs a function that, when it returns ok, wins over all prefix rules. Intended for dynamic routing (A/B tests, config reloads).

func WithModelRoute

func WithModelRoute(prefix string, route Route) Option

WithModelRoute adds an explicit prefix-based routing rule. Longer prefixes match first. Rules added via this option take precedence over the built-in defaults.

func WithOpenAI

func WithOpenAI(cfg OpenAIResponsesConfig) Option

WithOpenAI enables the OpenAI Responses adapter under the default "openai" backend slot. Equivalent to WithOpenAIResponsesCompat("openai", cfg).

func WithOpenAIResponsesCompat

func WithOpenAIResponsesCompat(name string, cfg OpenAIResponsesConfig) Option

WithOpenAIResponsesCompat registers an OpenAI Responses-protocol backend under the given name. Multiple calls accumulate; the name is used as the Route.Backend value. The reserved name "openai" is the default-named slot used by the built-in gpt-/o1-/o3- prefix routes; WithOpenAI is sugar for WithOpenAIResponsesCompat("openai", cfg).

func WithSchemaPolicy

func WithSchemaPolicy(p SchemaPolicy) Option

WithSchemaPolicy selects the client-global tool-schema normalisation policy. The default (when this option is not supplied) is SchemaPolicyStrict: any non-cosmetic lossy transform returns ErrSchemaIncompatible from Invoke/Stream. SchemaPolicyLossy performs the documented rewrites/drops and logs each via slog.Warn; SchemaPolicyBestEffort additionally tolerates the documented best-effort downgrades (see schema package docs).

type ProviderKind

type ProviderKind string

ProviderKind identifies one of the supported backends.

const (
	// ProviderAnthropic is the native Anthropic Messages API (passthrough).
	ProviderAnthropic ProviderKind = "anthropic"
	// ProviderOpenAIResponses is the OpenAI GPT-5 Response API.
	ProviderOpenAIResponses ProviderKind = "openai_responses"
	// ProviderGeminiNative is the Google Vertex/AI Studio streamGenerateContent API.
	ProviderGeminiNative ProviderKind = "gemini_native"
	// ProviderChatCompletions is the OpenAI-compatible ChatCompletion API
	// (Kimi/GLM/DeepSeek/OpenAI ChatGPT etc.).
	ProviderChatCompletions ProviderKind = "chat_completions"
)

type Route

type Route struct {
	Provider ProviderKind
	// Backend selects which named backend handles the request.
	// Meaningful for ProviderAnthropic, ProviderOpenAIResponses, and
	// ProviderChatCompletions. An empty value defaults to "anthropic"
	// for ProviderAnthropic and "openai" for ProviderOpenAIResponses;
	// ignored for ProviderGeminiNative.
	Backend string
	// UpstreamModel, if non-empty, replaces req.Model before dispatch.
	UpstreamModel string
}

Route resolves a model name to a concrete provider plus an optional remapped model string forwarded upstream.

type SchemaPolicy

type SchemaPolicy = schema.Policy

SchemaPolicy is the v0.2.0 client-global tool-schema normalisation policy. The default (PolicyStrict) makes every lossy transform a hard error so callers learn about silent field drops; PolicyLossy performs the documented rewrites and logs them at slog.Warn; PolicyBestEffort additionally tolerates the documented best-effort downgrades (e.g. OpenAI Strict additionalProperties:true -> false).

See docs/design/v0.2.0-protocol-driven-adapters.md §4.3 for the authoritative behaviour table.

type StreamReader

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

StreamReader is a pull-style iterator over Anthropic-shaped streaming events. Zero-value readers are unusable; construct one via Client.CreateMessageStream.

func (*StreamReader) Close

func (s *StreamReader) Close() error

Close drains the underlying channel. It is safe to call multiple times.

func (*StreamReader) Current

Current returns the last event produced by Next.

func (*StreamReader) CurrentRaw

func (s *StreamReader) CurrentRaw() []byte

CurrentRaw returns the raw JSON bytes for the last event. Useful when the caller wants to forward the payload verbatim (e.g. over their own HTTP SSE connection).

func (*StreamReader) Err

func (s *StreamReader) Err() error

Err returns the first error encountered, if any.

func (*StreamReader) Next

func (s *StreamReader) Next() bool

Next pulls the next event from the underlying channel. It returns false when the stream has ended; the caller should consult Err to check for an error termination.

Directories

Path Synopsis
Package adapter defines the interface every provider backend must implement.
Package adapter defines the interface every provider backend must implement.
anthropic
Package anthropic implements the Anthropic passthrough adapter.
Package anthropic implements the Anthropic passthrough adapter.
chat_completions
Package chat_completions implements the turnmeld adapter for any OpenAI Chat Completions compatible upstream (Kimi / DeepSeek / Qwen / GLM / OpenRouter / etc.), translating its SSE stream into the Anthropic Messages event stream.
Package chat_completions implements the turnmeld adapter for any OpenAI Chat Completions compatible upstream (Kimi / DeepSeek / Qwen / GLM / OpenRouter / etc.), translating its SSE stream into the Anthropic Messages event stream.
gemini_native
Package gemini_native implements the turnmeld adapter for Google's Vertex AI / AI Studio streamGenerateContent JSON+SSE API, translating its events into the Anthropic Messages event stream.
Package gemini_native implements the turnmeld adapter for Google's Vertex AI / AI Studio streamGenerateContent JSON+SSE API, translating its events into the Anthropic Messages event stream.
openai_responses
Package openai_responses converts between the Anthropic Messages protocol and OpenAI's GPT-5 Response API.
Package openai_responses converts between the Anthropic Messages protocol and OpenAI's GPT-5 Response API.
examples
01-hello command
internal
schema
Package schema centralises tool input_schema dialect handling for every protocol adapter shipped by turnmeld.
Package schema centralises tool input_schema dialect handling for every protocol adapter shipped by turnmeld.
ssehelper
Package ssehelper provides a minimal Server-Sent Events line decoder suitable for parsing Anthropic, OpenAI, and Gemini streams.
Package ssehelper provides a minimal Server-Sent Events line decoder suitable for parsing Anthropic, OpenAI, and Gemini streams.

Jump to

Keyboard shortcuts

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