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
- Variables
- func SetCacheControl(req *MessageNewParams, cc CacheControl)
- type AnthropicConfig
- type AnthropicMode
- type AzureOpenAIConfig
- type BedrockConfig
- type CacheControl
- type CacheControlType
- type Client
- type GeminiConfig
- type GeminiMode
- type Message
- type MessageNewParams
- type MessageStreamEventUnion
- type OpenAICompatConfig
- type OpenAIConfig
- type OpenAIResponsesConfig
- type Option
- func WithAnthropic(cfg AnthropicConfig) Option
- func WithAnthropicBedrock(name string, cfg BedrockConfig) Option
- func WithAnthropicCompat(name string, cfg AnthropicConfig) Option
- func WithAzureOpenAI(name string, cfg AzureOpenAIConfig) Option
- func WithChatCompletion(name string, cfg OpenAICompatConfig) Option
- func WithGemini(cfg GeminiConfig) Option
- func WithHTTPClient(h *http.Client) Option
- func WithLogger(l *slog.Logger) Option
- func WithModelOverride(fn func(model string) (Route, bool)) Option
- func WithModelRoute(prefix string, route Route) Option
- func WithOpenAI(cfg OpenAIResponsesConfig) Option
- func WithOpenAIResponsesCompat(name string, cfg OpenAIResponsesConfig) Option
- func WithSchemaPolicy(p SchemaPolicy) Option
- type ProviderKind
- type Route
- type SchemaPolicy
- type StreamReader
Constants ¶
const ( SchemaPolicyStrict = schema.PolicyStrict SchemaPolicyLossy = schema.PolicyLossy SchemaPolicyBestEffort = schema.PolicyBestEffort )
Re-exports of the underlying enum constants. See SchemaPolicy.
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.
const ( AnthropicModeDirect = anthropicadapter.AnthropicModeDirect AnthropicModeBedrock = anthropicadapter.AnthropicModeBedrock )
Re-exported Anthropic mode constants.
Variables ¶
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).
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 ¶
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 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 ¶
WithHTTPClient injects a shared http.Client. Passing nil restores the default (http.DefaultClient).
func WithLogger ¶
WithLogger installs an slog.Logger. When nil (the default) the library emits no log output.
func WithModelOverride ¶
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 ¶
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 ¶
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 ¶
func (s *StreamReader) Current() MessageStreamEventUnion
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
|
|
|
02-multi-provider
command
|
|
|
03-model-hot-switching
command
|
|
|
04-tool-use-portable
command
|
|
|
05-thinking-blocks
command
|
|
|
06-streaming-events
command
|
|
|
07-anthropic-compat
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. |

