Skip to content

Define canonical provider request/response contract #81

Closed

Description

@stackbilt-admin

Context

The intended role of llm-providers is provider abstraction: normalize Anthropic, OpenAI, Groq, Cerebras, NVIDIA, Cloudflare Workers AI, and future vendor-specific request/response shapes into one StackBilt execution contract.

This matters for AEGIS CLI and llm-gateway: Codex/Claude/Ollama-style clients may speak different wire protocols, but downstream routing should be based on task capability and model catalog metadata, not vendor-shaped request objects.

Desired Outcome

Define and harden a canonical provider request/response contract that captures the capabilities StackBilt needs independent of vendor API shape.

The contract should support at least:

  • normalized messages and system prompt
  • tool schemas and tool choice
  • structured output / JSON response format
  • streaming and non-streaming output
  • vision/media inputs where supported
  • use-case metadata such as TOOL_CALLING, LONG_CONTEXT, COST_EFFECTIVE, VISION, BALANCED
  • provider/model capability checks
  • normalized tool-call and tool-result semantics
  • normalized errors/fallback metadata
  • normalized usage/cost/latency metadata

Acceptance Criteria

  • There is a documented canonical LLMRequest and LLMResponse boundary that is not Anthropic-shaped or OpenAI-shaped by default.
  • Provider adapters translate from the canonical request into vendor-specific APIs.
  • Provider responses translate back into one canonical response shape.
  • Tool calling behavior is explicitly marked by capability, including graceful degradation where a provider cannot preserve a requested tool protocol.
  • Model selection remains catalog-driven through MODEL_CATALOG / rankModels, not hardcoded in gateway clients.
  • Tests cover at least OpenAI-compatible, Anthropic-compatible, Groq/Cerebras, NVIDIA, and Cloudflare Workers AI paths where available.

Notes

This is the foundation for running AEGIS/Codex-style harnesses primarily through NVIDIA, Cerebras, Groq, and Cloudflare Workers AI without depending on Anthropic API as the default backend.

Activity

  1. stackbilt-admin commented on Jun 5, 2026

    @stackbilt-admin
    MemberAuthor

    Related gateway implementation issue: Stackbilt-dev/llm-gateway#4

  2. stackbilt-admin commented on Jun 5, 2026

    @stackbilt-admin
    MemberAuthor

    Reviewing current main, I think this issue is valid and should stay open. The repo has good primitives already, but the canonical boundary is still partly implicit and partly mixed with provider/client dialects.

    Findings:

    • High: LLMRequest / LLMResponse exist, but LLMRequest is still partly vendor-shaped. toolChoice and response_format mirror OpenAI-style wire naming/shape, while provider-specific knobs like lora, topP, frequencyPenalty, reasoning, and prediction live directly on the canonical request surface. This makes the boundary harder for llm-gateway to target as a truly provider-neutral contract.
    • Medium: fallback/degradation metadata is not canonical yet. LLMResponse has a generic metadata?: Record<string, unknown>, and provider adapters attach provider-specific metadata. Factory fallback is mostly hook-based rather than expressed in a normalized response contract, so callers do not get a stable shape for fallback chain, degradation, selected provider/model reason, or unsupported capability handling.
    • Medium: capability checks exist, but the public inspection surface is too coarse for gateway routing/debugging. Catalog/model capabilities are detailed, but provider health reports provider-level tool support, which can overstate support for providers where only some models support tools.
    • Low: adapter tests are strong, but I do not see a dedicated contract-level suite asserting the same canonical request/response behavior across OpenAI-compatible, Anthropic, Groq/Cerebras, NVIDIA, and Cloudflare paths.

    Already covered / useful foundation:

    • Model selection is already catalog-driven through MODEL_CATALOG / rankModels; this part is aligned with the desired architecture.
    • Tool calls/results, response-format translation, vision inputs, schema drift handling, usage normalization, and provider fixtures already exist and are good building blocks.

    Recommended implementation lane:

    1. Add a documented/exported canonical contract section and contract fixtures/tests first, without breaking existing callers.
    2. Introduce canonical names/structures for structured output, tool choice, media parts, use-case metadata, capability requirements, fallback/degradation metadata, and provider extensions.
    3. Preserve current fields as compatibility aliases where needed, but move provider-specific options behind a namespaced extension bag.
    4. Add response metadata with stable fields for selected provider/model, fallback chain, capability degradation, unsupported tool behavior, usage/cost/latency, and normalized error/fallback information.
    5. Extend tests so the same canonical request fixture is translated through OpenAI-compatible, Anthropic-compatible, Groq/Cerebras, NVIDIA, and Cloudflare adapters and returns the same normalized response contract.

    Baseline checked locally on main: npm test passes, 19 test files / 421 tests.

  3. stackbilt-admin commented on Jun 5, 2026

    @stackbilt-admin
    MemberAuthor

    Specific guidance for the implementation session:

    Treat this as an additive hardening pass, not a breaking rewrite. The win is to make the canonical boundary explicit and testable while preserving current LLMRequest / LLMResponse callers as compatibility input.

    Recommended first PR shape

    1. Add exported canonical types, preferably in a small dedicated module such as src/canonical.ts or a clearly marked section of src/types.ts.
    2. Add a normalizer from current public LLMRequest into the canonical request shape.
    3. Preserve current fields as aliases for now. Do not remove response_format, toolChoice, lora, topP, frequencyPenalty, reasoning, or prediction yet.
    4. Move the meaning of provider-specific knobs into a namespaced provider extension bag in the canonical shape.
    5. Add contract fixtures/tests that prove the same canonical request can be prepared for OpenAI-compatible, Anthropic-compatible, Groq/Cerebras, NVIDIA, and Cloudflare paths without leaking vendor wire shapes into the caller-facing contract.

    Canonical request target

    The canonical center should be capability-oriented, not vendor-oriented. Suggested shape:

    export interface CanonicalLLMRequest {
      messages: CanonicalMessage[];
      system?: string;
      model?: string;
      stream?: boolean;
    
      sampling?: {
        temperature?: number;
        maxTokens?: number;
        seed?: number;
      };
    
      tools?: CanonicalTool[];
      toolMode?: 'auto' | 'none' | 'required' | { toolName: string };
      builtInTools?: BuiltInTool[];
    
      output?: {
        kind: 'text' | 'json_object' | 'json_schema';
        schemaName?: string;
        schema?: Record<string, unknown>;
        strict?: boolean;
      };
    
      media?: CanonicalMediaPart[];
    
      workload?: ModelRecommendationUseCase;
      requirements?: {
        toolCalling?: boolean;
        structuredOutput?: boolean;
        vision?: boolean;
        longContext?: boolean;
        builtInTools?: boolean;
      };
    
      providerOptions?: {
        cloudflare?: { lora?: string; topP?: number; frequencyPenalty?: number };
        cerebras?: { reasoning?: LLMRequest['reasoning']; prediction?: string };
        groq?: Record<string, unknown>;
        nvidia?: Record<string, unknown>;
        openai?: Record<string, unknown>;
        anthropic?: Record<string, unknown>;
      };
    
      metadata?: {
        requestId?: string;
        tenantId?: string;
        gateway?: GatewayMetadata;
        cache?: CacheHints;
        custom?: Record<string, unknown>;
      };
    }

    Exact names can change. The important part is that OpenAI wire names like response_format and provider knobs like lora are aliases into the canonical shape, not the canonical shape itself.

    Canonical response target

    Add stable response metadata instead of relying on open-ended metadata.

    export interface CanonicalLLMResponse {
      id?: string;
      message: string;
      model: string;
      provider: ProviderName;
      finishReason?: 'stop' | 'length' | 'tool_calls' | 'content_filter' | 'error';
      toolCalls?: ToolCall[];
      usage: TokenUsage;
      responseTime: number;
      routing?: {
        selectedProvider: ProviderName;
        selectedModel: string;
        selectionReason?: string;
        fallbackChain?: Array<{ provider: ProviderName; model?: string; reason?: string }>;
        degradations?: Array<{
          capability: string;
          action: 'stripped' | 'downgraded' | 'emulated' | 'failed';
          reason: string;
        }>;
      };
      error?: {
        class: string;
        provider?: ProviderName;
        retryable?: boolean;
        message: string;
      };
      metadata?: Record<string, unknown>; // compatibility / provider raw extras only
    }

    Tests to add first

    • Normalization tests from legacy LLMRequest to CanonicalLLMRequest.
    • Structured output alias test: response_format maps to output.
    • Tool choice alias test: OpenAI-shaped toolChoice maps to toolMode.
    • Provider options test: lora, topP, frequencyPenalty, reasoning, and prediction land under providerOptions.
    • Response metadata test: fallback/degradation/selected model have stable fields.
    • Contract fixture test: one canonical request fixture is accepted by provider preparation paths for OpenAI-compatible, Anthropic-compatible, Groq/Cerebras, NVIDIA, and Cloudflare without requiring live API calls.

    Non-goals for the first pass

    • Do not remove existing public fields.
    • Do not refactor every provider adapter at once.
    • Do not solve perfect cross-provider agentic tool loops in this issue.
    • Do not make Anthropic a required safety fallback. The canonical contract should support an Anthropic-free stack with NVIDIA, Cerebras, Groq, and Cloudflare Workers AI.

    Gateway handoff

    Once this lands, llm-gateway#4 should consume the canonical normalizer and stop constructing provider-shaped requests itself. Gateway should only translate client protocols into the canonical request, then delegate selection/execution to llm-providers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions