Files
TradingAgents/tradingagents/llm_clients/anthropic_client.py
T
Yijia-Xiao a420ad0f3b fix(cli): honor env precedence for LLM and run config
Interactive selections and flag defaults overrode TRADINGAGENTS_* env vars.
Rule: an explicit env value or CLI flag wins; otherwise the env-applied
default is kept.

- Research depth: skip the prompt when both round-count env vars are set, and
  stop overwriting them (#977).
- Checkpoint: --checkpoint/--no-checkpoint is tri-state; omitting it keeps
  TRADINGAGENTS_CHECKPOINT_ENABLED (#976).
- Docker ollama: use TRADINGAGENTS_LLM_PROVIDER + OLLAMA_BASE_URL, not a bare
  LLM_PROVIDER the overlay never reads (#975).
- Reasoning/thinking knobs: settable via env; the prompt is skipped when set.
- Effort gating: forward effort only to models that accept it (Anthropic
  Opus 4.5+/Sonnet 4.6+, OpenAI reasoning models); drop it elsewhere.
- Boolean env values: raise a named error on invalid input instead of
  silently becoming False.
2026-06-21 21:03:05 +00:00

76 lines
2.6 KiB
Python

import re
from typing import Any
from langchain_anthropic import ChatAnthropic
from .base_client import BaseLLMClient, normalize_content
from .validators import validate_model
_PASSTHROUGH_KWARGS = (
"timeout", "max_retries", "api_key", "max_tokens", "temperature",
"callbacks", "http_client", "http_async_client", "effort",
)
# Anthropic's extended-thinking ``effort`` parameter is accepted by Opus 4.5+
# and Sonnet 4.6+ only. Sonnet 4.5 and any Haiku version 400 with
# ``"This model does not support the effort parameter"`` (#831). The per-family
# minimum version below is forward-compatible: future ``claude-{opus,sonnet}-X-Y``
# releases inherit support automatically, while Sonnet 4.5 and Haiku stay excluded.
_EFFORT_EXACT = {
"claude-mythos-preview", # non-standard preview name; effort-capable
}
_EFFORT_MODEL = re.compile(r"^claude-(opus|sonnet)-(\d+)-(\d+)$")
_EFFORT_MIN_VERSION = {"opus": (4, 5), "sonnet": (4, 6)}
def _supports_effort(model: str) -> bool:
"""Whether Anthropic accepts the ``effort`` parameter for this model."""
model_lc = model.lower()
if model_lc in _EFFORT_EXACT:
return True
match = _EFFORT_MODEL.match(model_lc)
if not match:
return False
family, major, minor = match.group(1), int(match.group(2)), int(match.group(3))
return (major, minor) >= _EFFORT_MIN_VERSION[family]
class NormalizedChatAnthropic(ChatAnthropic):
"""ChatAnthropic with normalized content output.
Claude models with extended thinking or tool use return content as a
list of typed blocks. This normalizes to string for consistent
downstream handling.
"""
def invoke(self, input, config=None, **kwargs):
return normalize_content(super().invoke(input, config, **kwargs))
class AnthropicClient(BaseLLMClient):
"""Client for Anthropic Claude models."""
def __init__(self, model: str, base_url: str | None = None, **kwargs):
super().__init__(model, base_url, **kwargs)
def get_llm(self) -> Any:
"""Return configured ChatAnthropic instance."""
self.warn_if_unknown_model()
llm_kwargs = {"model": self.model}
if self.base_url:
llm_kwargs["base_url"] = self.base_url
for key in _PASSTHROUGH_KWARGS:
if key not in self.kwargs:
continue
if key == "effort" and not _supports_effort(self.model):
continue
llm_kwargs[key] = self.kwargs[key]
return NormalizedChatAnthropic(**llm_kwargs)
def validate_model(self) -> bool:
"""Validate model for Anthropic."""
return validate_model("anthropic", self.model)