graycoderouter

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2026 License: MIT Imports: 3 Imported by: 0

README

graycode-router

Universal LLM Provider Runtime

One interface for every model. Authentication, routing, streaming, retries, caching — handled.

Go License CI Release GoDoc

Quick Start · Features · Docs · Examples · Providers · Architecture · Contributing


What is graycode-router

graycode-router is the LLM provider runtime that powers the hawk coding agent. It handles everything between your application and LLM APIs — authentication, model resolution, streaming, retries, rate limiting, and caching.

When your app calls a model, graycode-router figures out which provider to use, how to talk to it, and how to stream the response back. Switch from Anthropic to Ollama? graycode-router handles the translation. API returns 529? graycode-router retries with backoff. Response hits max_tokens? graycode-router continues automatically.

Your app never talks to an LLM API directly. graycode-router does.

Hawk is the product face: it owns UX, agent orchestration, tools, permissions, sessions, and product semantics. GraycodeRouter is the provider engine: it owns credentials, catalog and route resolution, provider transports, normalized streams, retry/fallback, usage, and provider telemetry. Hawk integrates through the stable engine facade rather than assembling GraycodeRouter's internal provider packages.

Ecosystem Boundaries

graycode-router is a Hawk support engine. Keep the dependency edge one-way:

  • host-facing DTOs and the Provider port live in eagle/llm; engine/ re-exports them as aliases (*Engine implements llm.Provider)
  • internal provider/transport types stay graycode-router-scoped (not shared contracts)
  • do not import hawk/internal/*
  • do not import removed legacy path hawk/shared/types
  • do not import other engines (harrier, shrike, swift, kestrel, merlin) — engines are peers, not dependencies

Quick Start

go get github.com/GrayCodeAI/graycode-router

Requires Go 1.26+. Minimal dependencies (UUID, OpenTelemetry, SQLite, keyring).

import "github.com/GrayCodeAI/graycode-router/client"

// Create a client — provider auto-detected from environment
c := client.NewGraycodeRouterClient(&client.GraycodeRouterConfig{
    Provider: client.DetectProvider(),
})

// Stream a response
sr, err := c.StreamChat(ctx, messages, client.ChatOptions{
    Model: "claude-sonnet-4-6",
})
defer sr.Close()

for evt := range sr.Events {
    switch evt.Type {
    case "content":   // stream text
    case "tool_call": // execute tool
    case "done":      // response complete
    }
}

Features

Provider Routing

Automatically detects and routes to the right provider based on environment variables, config files, or explicit selection.

Model Resolution

Maps abstract tiers (opus/sonnet/haiku) to concrete model IDs per provider. Ships with an embedded catalog of pricing, context windows, and capabilities.

Streaming

Parses SSE for Anthropic and OpenAI formats — text, tool calls, and thinking blocks.

Reliability

  • Retries on 429/500/529 with exponential backoff and Retry-After support
  • Auto-continuation when stop_reason == max_tokens
  • Provider fallback chains for high availability

Rate Limiting

Token bucket rate limiter per provider — prevents hitting API limits before they happen.

Caching

  • Response caching with configurable TTL
  • Semantic similarity caching for repeated prompts
  • Anthropic prompt caching breakpoints on system prompt and conversation prefix

Cost Tracking

Built-in cost estimation per call, with per-provider pricing from the embedded model catalog.

Reasoning Controls

Passes reasoning_effort and Anthropic extended-thinking thinking_budget_tokens through to capable models — omitted when unset.

Keyless CI Auth

GitHub OIDC keyless authentication for cloud deployments — mints a short-lived token in GitHub Actions and exchanges it for AWS Bedrock (STS AssumeRoleWithWebIdentity) or GCP Vertex (Workload Identity Federation) credentials, no stored secrets.

OpenAI-Compatible Proxy

Serves POST /v1/chat/completions so existing OpenAI SDK clients can talk to graycode-router unchanged.

Load-Balancing Strategies

Named routing strategies beyond weighted random: simple-shuffle, least-busy, latency-based, cost-based, and usage-based.

Pluggable Cache & Audit Sinks

Distributed CacheBackend interface (in-memory default, RESP/Redis-capable) and an AuditSink interface (no-op default, JSONL file sink) for privacy-preserving call metadata.

Model Role Slots

Named primary / weak / editor model slots with fallback to primary, plus an LLM summarizing condenser that shrinks long conversation histories using the weak model.

Rerank & Readiness

POST /rerank endpoint (provider-backed with lexical fallback) and a GET /ready readiness probe alongside the existing health check.

gRPC Skeleton

Dependency-free gRPC API skeleton behind the grpc build tag — wired when generated stubs are available.

Documentation

Detailed documentation is available in the docs/ directory:

Examples

Runnable examples are in the examples/ directory:

Run any example with:

ANTHROPIC_API_KEY=sk-... go run ./examples/basic/

Supported Providers

22 provider gateways in catalog/registry/providers.go (hawk /config uses the same list), listed in registry SortOrder:

Provider ID Env variable
Anthropic anthropic ANTHROPIC_API_KEY
OpenAI openai OPENAI_API_KEY
Google Gemini gemini GEMINI_API_KEY
DeepSeek deepseek DEEPSEEK_API_KEY
xAI (Grok) grok XAI_API_KEY
Kimi (Moonshot) kimi MOONSHOT_API_KEY
Z.AI — Coding Plan zai_coding ZAI_CODING_API_KEY
Z.AI — Pay-as-you-go zai_payg ZAI_API_KEY
Xiaomi (MiMo) Token Plan xiaomi_mimo_token_plan XIAOMI_MIMO_TOKEN_PLAN_API_KEY (+ region cn / sgp / ams)
Xiaomi (MiMo) Pay-as-you-go xiaomi_mimo_payg XIAOMI_MIMO_PAYG_API_KEY
MiniMax — Token Plan minimax_token_plan MINIMAX_TOKEN_PLAN_API_KEY
MiniMax — Pay-as-you-go minimax_payg MINIMAX_PAYG_API_KEY
Azure OpenAI azure AZURE_OPENAI_API_KEY (+ AZURE_OPENAI_ENDPOINT)
Amazon Bedrock bedrock AWS_SECRET_ACCESS_KEY (+ AWS_ACCESS_KEY_ID, AWS_SESSION_TOKEN)
Vertex AI vertex VERTEX_ACCESS_TOKEN (or GOOGLE_OAUTH_ACCESS_TOKEN)
OpenRouter openrouter OPENROUTER_API_KEY
CanopyWave canopywave CANOPYWAVE_API_KEY
Poolside poolside POOLSIDE_API_KEY
Groq groq GROQ_API_KEY
ClinePass clinepass CLINE_API_KEY
OpenCode Go opencodego OPENCODEGO_API_KEY
Ollama ollama OLLAMA_BASE_URL (local; no API key)

Runtime auto-detection uses a separate priority order for chat when no deployment is pinned; see config profiles.

Usage

Basic Chat

resp, err := c.Chat(ctx, messages, client.ChatOptions{
    Model: "gpt-4o",
})

Streaming with Continuation

// Auto-continues when max_tokens is hit
resp, err := client.ChatWithContinuation(ctx, provider, messages,
    client.ChatOptions{Model: model},
    client.DefaultContinuationConfig(),
)

Mock Provider for Testing

mock := client.NewMockProvider(client.MockModeFixed)
mock.Response = "Here is the code you asked for..."

resp, _ := mock.Chat(ctx, messages, opts)
// No real API calls — perfect for tests

Model Catalog

cat := catalog.DefaultModelCatalog()

// Get the best model for a tier
model := catalog.GetPreferredProviderModel("anthropic", catalog.TierSonnet, &cat)
// → "claude-sonnet-4-6"

// Check deprecation warnings
warn := catalog.GetModelDeprecationWarning("claude-3-7-sonnet", "anthropic")

Provider Configuration

cfg := config.LoadProviderConfig("")             // load from disk
config.ApplyProviderConfigToEnv(cfg, false, nil) // apply to environment
config.SaveProviderConfig(cfg, "")               // save changes

Architecture

graycode-router/
├── engine/                 # Stable host-facing facade and provider-neutral DTOs
├── client/                 # Backwards-compatible public client facade
│   ├── core/               # Provider-neutral wire, stream, retry, and transport primitives
│   ├── adapters/           # Provider protocol adapters and construction registry
│   └── embeddings/         # Embedding clients, cache, and defaults
├── config/                 # Provider configuration & routing
│   └── credential/         # Credential file management
├── catalog/                # Model catalog & tier system
│   ├── discover/           # Model discovery
│   ├── legacy/             # Legacy model support
│   ├── live/               # Live model data
│   └── registry/           # Model registry
├── codeagent/              # Code agent retry & fallback strategies
├── conversation/           # Conversation engine with branching
├── credentials/            # Credential management
├── docs/                   # Documentation & guides
├── examples/               # Runnable code examples
├── router/                 # Provider routing strategies
├── operationsgraph/        # Privacy-safe route and generation telemetry projection
├── runtime/                # Runtime manifest & routing policies
├── storage/                # SQLite conversation DAG store
├── types/                  # Branded types & API errors
├── errors/                 # Error message constants
├── constants/              # API limits
├── utils/                  # Error utilities
├── internal/
│   ├── api/                # HTTP API handlers
│   ├── cache/              # Response cache warmer
│   ├── health/             # Provider health checker
│   ├── observability/      # OpenTelemetry spans & metrics
│   ├── sdk/                # Go, Python, TypeScript client SDKs
│   └── version/            # Version information
└── assets/                 # Logo and branding

See docs/ARCHITECTURE.md for detailed system design and data flows.

operationsgraph.Build projects resolved routes and normalized usage into graycode-router.graph/v1 operations nodes. Provider, model, request ID, and generated content are represented only by SHA-256 digests; token counts, finish reason, tool-call count, and deployment-routing state remain queryable.

Ecosystem

graycode-router is part of the hawk-eco:

Component Repository Purpose
hawk GrayCodeAI/hawk AI coding agent
graycode-router This repo LLM provider runtime
shrike GrayCodeAI/shrike Tokenizer & compression
harrier GrayCodeAI/harrier Graph-based memory
swift GrayCodeAI/swift Session capture

Development

Prerequisites

  • Go 1.26+

Build & Test

go build ./...               # Verify the library compiles
go test -race ./...           # Run all tests with race detector
make ci                       # Run full CI suite (lint, test, security)
make cover                    # Generate coverage report

Contributing

We welcome contributions! Please see CONTRIBUTING.md for development setup, commit conventions, and the PR process.

Quick start:

  1. Fork and create a branch: git checkout -b feat/short-description
  2. Make changes in small, focused commits
  3. Run make ci locally
  4. Open a pull request

Use Conventional Commits for commit messages — release-please uses them for versioning.

License

MIT — see LICENSE for details.

© 2026 GrayCode AI

Documentation

Overview

Package graycode-router provides LLM provider clients and configuration.

The Version variable is sourced from the VERSION file at the repo root and propagated to sub-packages at init time.

Index

Constants

This section is empty.

Variables

View Source
var Version = strings.TrimSpace(versionFile)

Version of the graycode-router library. Single source of truth: VERSION file.

Functions

This section is empty.

Types

This section is empty.

Directories

Path Synopsis
Package catalog defines graycode-router's model catalog: the versioned set of known providers and their model entries, the bootstrap (built-in) catalog, and helpers to compile and query catalog data (e.g.
Package catalog defines graycode-router's model catalog: the versioned set of known providers and their model entries, the bootstrap (built-in) catalog, and helpers to compile and query catalog data (e.g.
concentrate
Package concentrate holds shared constants and pricing-cache helpers for the Concentrate AI Responses API gateway (https://concentrate.ai).
Package concentrate holds shared constants and pricing-cache helpers for the Concentrate AI Responses API gateway (https://concentrate.ai).
opencodego
Package opencodego holds shared constants and helpers for the OpenCode Go gateway (https://opencode.ai/docs/go/).
Package opencodego holds shared constants and helpers for the OpenCode Go gateway (https://opencode.ai/docs/go/).
opengateway
Package opengateway holds shared constants for the OpenGateway inference gateway (https://gitlawb.com/opengateway), an OpenAI-compatible endpoint that routes requests across providers (MiMo, Gemini, MiniMax, Qwen, Kimi, GLM, etc.) and returns the live model catalog with inline pricing from GET /v1/models.
Package opengateway holds shared constants for the OpenGateway inference gateway (https://gitlawb.com/opengateway), an OpenAI-compatible endpoint that routes requests across providers (MiMo, Gemini, MiniMax, Qwen, Kimi, GLM, etc.) and returns the live model catalog with inline pricing from GET /v1/models.
xiaomi
Package xiaomi resolves Xiaomi MiMo API base URLs for pay-as-you-go and Token Plan.
Package xiaomi resolves Xiaomi MiMo API base URLs for pay-as-you-go and Token Plan.
zai
Package zai resolves Z.AI (Zhipu GLM) API base URLs for General (pay-as-you-go) and Coding Plan subscriptions across International vs China regions.
Package zai resolves Z.AI (Zhipu GLM) API base URLs for General (pay-as-you-go) and Coding Plan subscriptions across International vs China regions.
Package client provides LLM provider clients for Anthropic, OpenAI, and OpenAI-compatible APIs with streaming, retry, and provider detection.
Package client provides LLM provider clients for Anthropic, OpenAI, and OpenAI-compatible APIs with streaming, retry, and provider detection.
core
Package core holds the provider contract and the data types shared by every layer of the graycode-router client: adapters, middleware, caching, embeddings, and the client facade itself.
Package core holds the provider contract and the data types shared by every layer of the graycode-router client: adapters, middleware, caching, embeddings, and the client facade itself.
Package codeagent provides intelligent retry and fallback strategies tailored to code agent workloads.
Package codeagent provides intelligent retry and fallback strategies tailored to code agent workloads.
Package config holds graycode-router's provider configuration model and accessors for the active provider/model selection (ActiveProvider, ActiveModel, SetActiveProvider, SetProviderModel) used to route requests.
Package config holds graycode-router's provider configuration model and accessors for the active provider/model selection (ActiveProvider, ActiveModel, SetActiveProvider, SetProviderModel) used to route requests.
Package credentials manages provider API-key storage for graycode-router, combining an OS keychain and an env-file store (CombinedStore) and providing import of env-file and deprecated keychain credentials into the current scheme.
Package credentials manages provider API-key storage for graycode-router, combining an OS keychain and an env-file store (CombinedStore) and providing import of env-file and deprecated keychain credentials into the current scheme.
Package engine is the stable, host-facing GraycodeRouter API.
Package engine is the stable, host-facing GraycodeRouter API.
examples
basic command
Example: basic chat with graycode-router.
Example: basic chat with graycode-router.
multi-provider command
Example: multi-provider fallback chain.
Example: multi-provider fallback chain.
streaming command
Example: streaming chat with auto-continuation.
Example: streaming chat with auto-continuation.
Package graph defines the portable graph vocabulary shared across hawk-eco.
Package graph defines the portable graph vocabulary shared across hawk-eco.
internal
api
Package api implements graycode-router's internal HTTP API server (Server) and its configuration, including the reranker interface used to score results.
Package api implements graycode-router's internal HTTP API server (Server) and its configuration, including the reranker interface used to score results.
cache
Pluggable distributed cache backend interface.
Pluggable distributed cache backend interface.
grpc
Package grpc holds a dependency-free skeleton for an graycode-router gRPC API.
Package grpc holds a dependency-free skeleton for an graycode-router gRPC API.
health
Package graycode-router (internal/health) provides provider health-check tracking — the HealthState type and helpers that record and report provider liveness.
Package graycode-router (internal/health) provides provider health-check tracking — the HealthState type and helpers that record and report provider liveness.
httputil
Package httputil provides shared HTTP server primitives used across graycode-router's API surfaces.
Package httputil provides shared HTTP server primitives used across graycode-router's API surfaces.
observability
Audit log sink for LLM calls.
Audit log sink for LLM calls.
probehttp
Package probehttp contains shared helpers for the graycode-router credential-probe and catalog-probe call sites.
Package probehttp contains shared helpers for the graycode-router credential-probe and catalog-probe call sites.
shrink
Package shrink compresses LLM tool descriptions before they are sent to the provider.
Package shrink compresses LLM tool descriptions before they are sent to the provider.
Package llm is the canonical provider port contract for the hawk ecosystem.
Package llm is the canonical provider port contract for the hawk ecosystem.
Package graph provides graph-based execution graph implementation for graycode-router.
Package graph provides graph-based execution graph implementation for graycode-router.
Package router contains graycode-router's request-routing building blocks: a CircuitBreaker for failing providers and a ToolFilter for constraining the tools exposed to a given request.
Package router contains graycode-router's request-routing building blocks: a CircuitBreaker for failing providers and a ToolFilter for constraining the tools exposed to a given request.
Package runtime is the **recommended entry point** for host applications (e.g.
Package runtime is the **recommended entry point** for host applications (e.g.
Package setup wires catalog-backed deployment routing for hawk and graycode-router CLIs.
Package setup wires catalog-backed deployment routing for hawk and graycode-router CLIs.
Package storage provides graycode-router's persistence layer: virtual keys and an SQLite-backed budget store (BudgetStore / SQLiteStore) for tracking usage and spend limits.
Package storage provides graycode-router's persistence layer: virtual keys and an SQLite-backed budget store (BudgetStore / SQLiteStore) for tracking usage and spend limits.
Package types holds graycode-router's shared data types — message/content blocks and related request/response shapes — plus small cross-cutting helpers such as retry backoff (BackoffDelay, CryptoRandDuration).
Package types holds graycode-router's shared data types — message/content blocks and related request/response shapes — plus small cross-cutting helpers such as retry backoff (BackoffDelay, CryptoRandDuration).
Package verify provides a data-driven conformance harness that certifies a provider behaves correctly before it is relied on in the catalog.
Package verify provides a data-driven conformance harness that certifies a provider behaves correctly before it is relied on in the catalog.

Jump to

Keyboard shortcuts

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