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 ChatDuel

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

Overview

Concrete tool for routing LangChain prompts through the Duel Agents proxy via a thin subclass of ChatOpenAI that injects Duel defaults (model, base URL, API key) through a Pydantic validator, provided by the langchain-duel Python package.

Description

The ChatDuel class is a LangChain chat model that routes prompts through the Duel proxy. It subclasses langchain_openai.ChatOpenAI and only changes defaults — all upstream methods (invoke, stream, ainvoke, tool calling) are inherited unchanged.

Default injection is performed by _set_duel_defaults, a Pydantic v2 @model_validator(mode="before") class method that runs on the raw input dict before Pydantic coerces types:

  • model → defaulted to "duel-auto" if not provided
  • base_url → defaulted to os.getenv("DUEL_PROXY_URL", "https://duelagents.com/v1")
  • api_key → filled from os.getenv("DUEL_API_KEY") if neither api_key nor openai_api_key is set

The lc_secrets property maps openai_api_key to the env var DUEL_API_KEY, so the key is not serialized in plaintext. is_lc_serializable returns False because third-party namespaces are not registered with the LangChain loader.

The _llm_type property returns "duel-chat".

Usage

Import this class when you need to:

  • Use the Duel proxy inside a LangChain chain or agent
  • Drop in a Duel-routed chat model with one import change from ChatOpenAI
  • Run LangChain streaming, tool calling, or async through the Duel proxy

Code Reference

Source Location

  • Repository: Duel-Agents
  • File: python/langchain-duel/langchain_duel/chat_models.py (lines 1-83)

Signature

from langchain_openai import ChatOpenAI
from pydantic import model_validator

DUEL_API_BASE = "https://duelagents.com/v1"
DEFAULT_MODEL = "duel-auto"

class ChatDuel(ChatOpenAI):
    @property
    def lc_secrets(self) -> dict[str, str]:
        return {"openai_api_key": "DUEL_API_KEY"}

    @property
    def _llm_type(self) -> str:
        return "duel-chat"

    @classmethod
    def is_lc_serializable(cls) -> bool:
        return False

    @model_validator(mode="before")
    @classmethod
    def _set_duel_defaults(cls, values: Any) -> Any:
        if not isinstance(values, dict):
            return values
        values.setdefault("model", DEFAULT_MODEL)
        values.setdefault("base_url", os.getenv("DUEL_PROXY_URL", DUEL_API_BASE))
        has_key = any(values.get(f) for f in ("api_key", "openai_api_key"))
        if not has_key:
            env_key = os.getenv("DUEL_API_KEY")
            if env_key:
                values["api_key"] = env_key
        return values

Import

from langchain_duel import ChatDuel

I/O Contract

Inputs

Name Type Required Description
model str No Model name (default duel-auto)
base_url str No Proxy URL (default DUEL_PROXY_URL env or https://duelagents.com/v1)
api_key Optional[str] No Duel key (default DUEL_API_KEY env)
(inherited) various No All ChatOpenAI args (temperature, max_tokens, etc.)

Outputs

Name Type Description
invoke returns AIMessage Inherited from ChatOpenAI
stream yields AIMessageChunk Inherited from ChatOpenAI

Usage Examples

Basic Invocation

from langchain_duel import ChatDuel

llm = ChatDuel(model="duel-auto", temperature=0)
response = llm.invoke("Explain concurrent agents in one sentence.")
print(response.content)

With Environment Variables

import os
os.environ["DUEL_API_KEY"] = "duel_<prefix>_<secret>"
# os.environ["DUEL_PROXY_URL"] = "https://duelagents.com/v1"  # optional

from langchain_duel import ChatDuel
# All defaults filled from env — no args needed
llm = ChatDuel()
response = llm.invoke("What is 2+2?")

Streaming

from langchain_duel import ChatDuel

llm = ChatDuel(model="duel-auto")
for chunk in llm.stream("Write a haiku about agents."):
    print(chunk.content, end="", flush=True)

In a LangChain Chain

from langchain_duel import ChatDuel
from langchain_core.prompts import ChatPromptTemplate

llm = ChatDuel(temperature=0)
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a concise assistant."),
    ("user", "{question}"),
])
chain = prompt | llm
response = chain.invoke({"question": "What is the Duel proxy?"})

Related Pages

Implements Principle

Requires Environment

Page Connections

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