Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
fix(llms): address Qodo review findings on Anthropic wrapper
Zohaib Hassnainca7f743dabff
diff --git a/docs/guides/llm-integrations.md b/docs/guides/llm-integrations.mdindex 4dc03666..78b32df4 100644--- a/docs/guides/llm-integrations.md+++ b/docs/guides/llm-integrations.md@@ -148,21 +148,25 @@ The default model `gpt-3.5-turbo` is fine for classification and light extractio## Anthropic — Complex Reasoning and Structured Extraction-**Anthropic** provides the Claude model family, built with an emphasis on careful, instruction-following behavior and strong performance on multi-step reasoning, long-document analysis, and code-related tasks. Claude models tend to be more cautious about ambiguous instructions than other providers , useful when the cost of a confidently wrong answer is high.+**Anthropic** provides the Claude model family, built with an emphasis on careful, instruction-following behavior and strong performance on multi-step reasoning, long-document analysis, and code-related tasks. Claude models tend to be more cautious about ambiguous instructions than other providers. That matters when the cost of a confidently wrong answer is high.The `Anthropic` provider wraps the Claude API. Reach for it when the task involves reasoning through several dependent steps (not just single-turn extraction), when you're processing long source documents that need to stay in context, or when you need schema-validated structured output rather than best-effort JSON.+Install with `pip install "semantica[llm-anthropic]"` (or just `pip install anthropic`) before using this provider.+```pythonfrom semantica.llms import Anthropic-claude = Anthropic(model="claude-sonnet-5", api_key="YOUR_ANTHROPIC_KEY")+claude = Anthropic(model="claude-3-sonnet-20240229", api_key="YOUR_ANTHROPIC_KEY")# api_key falls back to the ANTHROPIC_API_KEY environment variable-# Always health-check before the first call in a long-running process+# is_available() only confirms a client was constructed from some key.+# It does not validate the key or check network reachability - an+# invalid or expired key still passes this check and fails at generate().if not claude.is_available():- raise RuntimeError("Anthropic provider unreachable — check ANTHROPIC_API_KEY")+ raise RuntimeError("Anthropic provider not configured - set ANTHROPIC_API_KEY")-# Plain generation — multi-step reasoning over a contract clause+# Plain generation - multi-step reasoning over a contract clauseverdict = claude.generate("A vendor contract has a 30-day termination-for-convenience clause ""but a 90-day data-return obligation that survives termination. "@@ -171,7 +175,7 @@ verdict = claude.generate(temperature=0.1,)print(verdict)-# "Day 120 from termination notice , the 90-day return period runs from+# "Day 120 from termination notice. The 90-day return period runs from# the termination date (day 30), not from the notice date."# Structured, schema-validated output@@ -192,7 +196,7 @@ print(risk.risk_level, risk.days_to_deadline)# "medium" 90```-Model selection: `claude-haiku` for high-volume classification where cost matters more than depth, `claude-sonnet` as the default for most extraction and reasoning tasks, `claude-opus` when a task genuinely needs the deepest reasoning available and latency/cost are secondary.+Model selection follows the same tier structure as the other providers: a Haiku model for high-volume classification where cost matters more than depth, a Sonnet model as the default for most extraction and reasoning tasks, an Opus model when a task genuinely needs the deepest reasoning available and latency/cost are secondary. Check Anthropic's docs for the current model identifiers, since they're versioned and change over time.## LiteLLM — One Interface, 100+ Providersdiff --git a/semantica/llms/__init__.py b/semantica/llms/__init__.pyindex 3f06de81..390a9e8d 100644--- a/semantica/llms/__init__.py+++ b/semantica/llms/__init__.py@@ -35,7 +35,7 @@ Example Usage:>>> response = llm.generate("Hello, world!")>>>>>> # Anthropic provider- >>> claude = Anthropic(model="claude-sonnet-5", api_key="the-key")+ >>> claude = Anthropic(model="claude-3-sonnet-20240229", api_key="the-key")>>> response = claude.generate("Hello, world!")Author: Semantica Contributorsdiff --git a/semantica/llms/anthropic.py b/semantica/llms/anthropic.pyindex 2983e50e..6af86854 100644--- a/semantica/llms/anthropic.py+++ b/semantica/llms/anthropic.py@@ -4,7 +4,7 @@ Anthropic LLM ProviderWrapper for Anthropic Claude API provider with clean interface"""-from typing import Any, Dict, Optional+from typing import Any, Dict, List, Optional, Unionfrom ..semantic_extract.providers import AnthropicProviderfrom ..utils.exceptions import ProcessingError@@ -20,13 +20,13 @@ class Anthropic:Example:>>> from semantica.llms import Anthropic- >>> claude = Anthropic(model="claude-sonnet-5", api_key="the-key")+ >>> claude = Anthropic(model="claude-3-sonnet-20240229", api_key="the-key")>>> response = claude.generate("What is API key?")"""def __init__(self,- model: str = "claude-sonnet-5",+ model: str = "claude-3-sonnet-20240229",api_key: Optional[str] = None,**kwargs):@@ -34,7 +34,7 @@ class Anthropic:Init Anthropic provider.Args:- model: Model name(default is sonnet 5)+ model: Model name (default: claude-3-sonnet-20240229)api_key: Anthropic API key (default: from ANTHROPIC_API_KEY env var)**kwargs: Addition provider options"""@@ -68,17 +68,18 @@ class Anthropic:)return self.provider.generate(prompt, **kwargs)- def generate_structured(self, prompt: str, **kwargs) -> Dict [str, Any]:+ def generate_structured(self, prompt: str, **kwargs) -> Union[Dict[str, Any], List[Any]]:"""Generates structured JSON output.Args:prompt: Input prompt text**kwargs: Generation options-+Returns:- An instance of `schema`, populated from the model's response-+ Parsed JSON response. A dict for a top-level JSON object, or a+ list if the model returns a top-level JSON array.+Raises:ProcessingError: If provider is not available or generation fails"""diff --git a/tests/test_llm_anthropic.py b/tests/test_llm_anthropic.pyindex d61979b2..847db5d5 100644--- a/tests/test_llm_anthropic.py+++ b/tests/test_llm_anthropic.py@@ -10,13 +10,20 @@ from semantica.utils.exceptions import ProcessingErrordef test_construction_stores_model_and_api_key():"""Anthropic(...) should not crash and should remember what it was given."""- claude = Anthropic(model="claude-sonnet-5", api_key="fake-key")- assert claude.model == "claude-sonnet-5"+ claude = Anthropic(model="claude-3-sonnet-20240229", api_key="fake-key")+ assert claude.model == "claude-3-sonnet-20240229"assert claude.api_key == "fake-key"-def test_is_available_false_with_no_key():- """Without a real key/package, is_available() must be a real False, not truthy junk."""+def test_is_available_false_with_no_key(monkeypatch):+ """Without a real key, is_available() must be a real False, not truthy junk.++ api_key=None alone isn't enough to prove this: AnthropicProvider falls+ back to the ANTHROPIC_API_KEY environment variable, so this test has to+ clear it too or it would pass/fail depending on whoever's machine or CI+ runner happens to run it.+ """+ monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)claude = Anthropic(api_key=None)assert claude.is_available() is False