Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:2aronS Duel Agents DuelClient

From Leeroopedia
Knowledge Sources
Domains Networking, API_Design
Last Updated 2026-10-27 14:00 GMT

Overview

Concrete tool for routing LLM requests via OpenAI- and Anthropic-compatible protocols through the Duel proxy, provided by the @duel-agents/sdk package.

Description

The DuelClient class is the public SDK surface for the Duel Agents proxy. It exposes two API namespaces that mirror the upstream OpenAI and Anthropic SDKs:

  • duel.chat.completions.create(params) — OpenAI-compatible chat completions (POST /chat/completions)
  • duel.messages.create(params) — Anthropic-compatible messages (POST /messages)

Both delegate to a private request<T> method that handles:

  • Header injection — Authorization: Bearer <key> and Content-Type: application/json always; anthropic-version: 2023-06-01 and x-api-key added for the Anthropic protocol
  • Timeout — AbortSignal.timeout(timeoutMs) (default 60s)
  • Response parsing — res.text() then JSON.parse; falls back to raw text if parse fails; null if body empty
  • Error mapping — 401/403 → DuelAuthError; other non-2xx → DuelApiError with status and body

The constructor validates the key via requireApiKey (throws DuelAuthError if missing), defaults baseUrl to DEFAULT_PROXY_URL, and allows injecting a custom fetch implementation for testing.

Streaming is explicitly not supported — createChatCompletion throws DuelApiError (status 400) if stream: true.

Usage

Import this class when you need to:

  • Make programmatic LLM calls through the Duel proxy from TypeScript/JavaScript
  • Support both OpenAI and Anthropic request formats from a single client
  • Inject a custom fetch for testing or proxying through a custom transport

Code Reference

Source Location

  • Repository: Duel-Agents
  • File: packages/sdk/src/client.ts (lines 62-169)

Signature

export interface DuelClientOptions {
  apiKey: string;
  baseUrl?: string;            // default: DEFAULT_PROXY_URL
  fetch?: typeof fetch;        // injectable; default: global fetch
  timeoutMs?: number;          // default: 60_000
}

export interface ChatMessage {
  role: "system" | "user" | "assistant";
  content: string;
}

export interface ChatCompletionCreateParams {
  model: string;
  messages: ChatMessage[];
  max_tokens?: number;
  temperature?: number;
  stream?: boolean;
}

export interface ChatCompletion {
  id: string;
  object: string;
  created: number;
  model: string;
  choices: Array<{
    index: number;
    message: ChatMessage;
    finish_reason: string | null;
  }>;
}

export interface AnthropicMessage {
  role: "user" | "assistant";
  content: string | Array<{ type: string; text?: string }>;
}

export interface MessagesCreateParams {
  model: string;
  max_tokens: number;
  messages: AnthropicMessage[];
  system?: string;
}

export interface MessagesResponse {
  id: string;
  type: string;
  role: string;
  content: Array<{ type: string; text: string }>;
  model: string;
  stop_reason: string | null;
}

export class DuelClient {
  readonly apiKey: string;
  readonly baseUrl: string;
  readonly chat: {
    completions: {
      create(params: ChatCompletionCreateParams): Promise<ChatCompletion>;
    };
  };
  readonly messages: {
    create(params: MessagesCreateParams): Promise<MessagesResponse>;
  };

  constructor(opts: DuelClientOptions);
  async createChatCompletion(params: ChatCompletionCreateParams): Promise<ChatCompletion>;
  async createMessage(params: MessagesCreateParams): Promise<MessagesResponse>;
  private async request<T>(path: string, body: unknown, protocol: "openai" | "anthropic"): Promise<T>;
}

Import

import { DuelClient } from "@duel-agents/sdk";

I/O Contract

Inputs

Name Type Required Description
opts.apiKey string Yes Duel key (throws DuelAuthError if missing)
opts.baseUrl string No Proxy URL (default DEFAULT_PROXY_URL)
opts.fetch typeof fetch No Injectable fetch impl (for testing)
opts.timeoutMs number No Request timeout in ms (default 60000)

Outputs

Name Type Description
chat.completions.create returns Promise<ChatCompletion> OpenAI-style response
messages.create returns Promise<MessagesResponse> Anthropic-style response
throws DuelAuthError 401/403: key rejected
throws DuelApiError Other non-2xx; carries status and body
throws DuelApiError stream: true (400, not supported yet)

Usage Examples

OpenAI-Compatible Chat Completion

import { DuelClient } from "@duel-agents/sdk";

const duel = new DuelClient({ apiKey: process.env.DUEL_API_KEY! });

const completion = await duel.chat.completions.create({
  model: "duel-auto",
  messages: [
    { role: "system", content: "You are a helpful assistant." },
    { role: "user", content: "Explain concurrent agents in one sentence." },
  ],
  temperature: 0,
});

console.log(completion.choices[0].message.content);

Anthropic-Compatible Messages

import { DuelClient } from "@duel-agents/sdk";

const duel = new DuelClient({ apiKey: process.env.DUEL_API_KEY! });

const response = await duel.messages.create({
  model: "duel-auto",
  max_tokens: 1024,
  system: "You are a helpful assistant.",
  messages: [
    { role: "user", content: "Explain concurrent agents in one sentence." },
  ],
});

console.log(response.content[0].text);

Error Handling

import { DuelClient, DuelAuthError, DuelApiError } from "@duel-agents/sdk";

try {
  const result = await duel.chat.completions.create(params);
} catch (e) {
  if (e instanceof DuelAuthError) {
    console.error("Key rejected. Renew at https://duelagents.com/dashboard/settings");
  } else if (e instanceof DuelApiError) {
    console.error(`API error ${e.status}:`, e.body);
  }
}

Custom Fetch (Testing)

import { DuelClient } from "@duel-agents/sdk";

const mockFetch = async (url: string, init: RequestInit) =>
  new Response(JSON.stringify({ /* mock ChatCompletion */ }), {
    status: 200,
    headers: { "Content-Type": "application/json" },
  });

const duel = new DuelClient({ apiKey: "duel_abcd1234_...", fetch: mockFetch });

Related Pages

Implements Principle

Requires Environment

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment