Anthropic Service Client#

Source: examples/clients/anthropic_service_client.py

Introduction#

Anthropic hosted inference is useful when teams want strong instruction-following and tool-use support from one managed API while keeping application code on provider-neutral LLM contracts. This example exercises the Anthropic service client path with trace capture and deterministic output support for CI.

Technical Implementation#

  1. Configure Tracer with JSONL + console sinks so each run emits machine-readable traces.

  2. Build runtime inputs through public package APIs and invoke AnthropicServiceLLMClient.generate(...).

  3. Construct LLMRequest payload fields and execute one representative remote-style call.

  4. Print a compact JSON payload that includes trace metadata for docs and deterministic tests.

        flowchart LR
    A["Prompt input"] --> B["main(): tracing setup"]
    B --> C["AnthropicServiceLLMClient.generate(...)"]
    C --> D["LLMRequest and LLMResponse contracts"]
    C --> E["Tracer JSONL + console events"]
    D --> F["Output payload"]
    E --> F
    F --> G["Printed JSON result"]
    
 1from __future__ import annotations
 2
 3import json
 4from pathlib import Path
 5
 6import design_research_agents as drag
 7
 8
 9def _build_payload() -> dict[str, object]:
10    # Build the hosted Anthropic client using public runtime APIs, then execute one representative request.
11    client = drag.AnthropicServiceLLMClient(
12        name="anthropic-prod",
13        default_model="claude-3-5-haiku-latest",
14        api_key_env="ANTHROPIC_API_KEY",
15        base_url="https://api.anthropic.com",
16        max_retries=3,
17        model_patterns=("claude-3-5-haiku-latest", "claude-3-5-*"),
18    )
19    description = client.describe()
20    prompt = "In one sentence, when should teams run architecture red-team reviews?"
21    response = client.generate(
22        drag.LLMRequest(
23            messages=(
24                drag.LLMMessage(role="system", content="You are a concise engineering design assistant."),
25                drag.LLMMessage(role="user", content=prompt),
26            ),
27            model=client.default_model(),
28            temperature=0.0,
29            max_tokens=120,
30        )
31    )
32    llm_call = {
33        "prompt": prompt,
34        "response_text": response.text,
35        "response_model": response.model,
36        "response_provider": response.provider,
37        "response_has_text": bool(response.text.strip()),
38    }
39    return {
40        "client_class": description["client_class"],
41        "default_model": description["default_model"],
42        "llm_call": llm_call,
43        "backend": description["backend"],
44        "capabilities": description["capabilities"],
45        "server": description["server"],
46    }
47
48
49def main() -> None:
50    """Run traced Anthropic service client call payload."""
51    # Fixed request id keeps traces and docs output deterministic across runs.
52    request_id = "example-clients-anthropic-service-call-001"
53    tracer = drag.Tracer(
54        enabled=True,
55        trace_dir=Path("artifacts/examples/traces"),
56        enable_jsonl=True,
57        enable_console=True,
58    )
59    payload = tracer.run_callable(
60        agent_name="ExamplesAnthropicServiceClientCall",
61        request_id=request_id,
62        input_payload={"scenario": "anthropic-service-client-call"},
63        function=_build_payload,
64    )
65    assert isinstance(payload, dict)
66    payload["example"] = "clients/anthropic_service_client.py"
67    payload["trace"] = tracer.trace_info(request_id)
68    # Print the results
69    print(json.dumps(payload, ensure_ascii=True, indent=2, sort_keys=True))
70
71
72if __name__ == "__main__":
73    main()

Expected Results#

Run Command

PYTHONPATH=tests/example_monkeypatch:src DRA_EXAMPLE_LLM_MODE=deterministic python examples/clients/anthropic_service_client.py

This checkout-only command reproduces the documented output without a live backend. For real installs, credentials, and backend-specific setup, see LLM Clients.

Example output captured with DRA_EXAMPLE_LLM_MODE=deterministic (timestamps, durations, and trace filenames vary by run):

{
  "backend": {
    "api_key_env": "ANTHROPIC_API_KEY",
    "base_url": "https://api.anthropic.com",
    "default_model": "claude-3-5-haiku-latest",
    "kind": "anthropic_service",
    "max_retries": 3,
    "model_patterns": [
      "claude-3-5-haiku-latest",
      "claude-3-5-*"
    ],
    "name": "anthropic-prod"
  },
  "capabilities": {
    "json_mode": "native",
    "max_context_tokens": null,
    "streaming": true,
    "tool_calling": "native",
    "vision": false
  },
  "client_class": "AnthropicServiceLLMClient",
  "default_model": "claude-3-5-haiku-latest",
  "example": "clients/anthropic_service_client.py",
  "llm_call": {
    "prompt": "In one sentence, when should teams run architecture red-team reviews?",
    "response_has_text": true,
    "response_model": "claude-3-5-haiku-latest",
    "response_provider": "example-test-monkeypatch",
    "response_text": "Run architecture red-team reviews before committing high-impact changes with uncertain failure modes."
  },
  "server": null,
  "trace": {
    "request_id": "example-clients-anthropic-service-call-001",
    "trace_dir": "artifacts/examples/traces",
    "trace_path": "artifacts/examples/traces/run_20260222T162206Z_example-clients-anthropic-service-call-001.jsonl"
  }
}

References#