AnthropicCompatibleProvider#

Connect a provider and configure retries, credentials, and transport. See the guide.

class zett_agent.providers.anthropic_compatible.AnthropicCompatibleProvider(*, model, api_key, base_url=None, transport=None, retry=RetryOptions(base_delay=0.25, max_delay=8.0, max_retries=3), timeout=TimeoutOptions(connect=5.0, first_byte=60.0, idle=600.0), prompt_cache=False, max_tokens=16384, extra_headers=None, extra_query=None, extra_body=None)[源代码]#

Stream a service that speaks the Anthropic Messages protocol.

This is the base class of AnthropicProvider and the providers for the services that bend the protocol. A provider for another one is a subclass that sets provider_name and overrides the hooks below where the service differs; it does not copy the stream loop.

Claude 5.x binds a signed thinking block to the system prompt, the tools, and the messages before it. When one of them changed, for instance because compaction replaced older turns with a summary, the service refuses the block with 400 ... bound to a different conversation. The provider then drops the signed blocks of that request, sends it once more, and no longer replays them, which is Anthropic's documented fallback. The model loses its earlier reasoning from then on, so each occurrence is logged as a warning.

参数:
  • model (str) -- Model identifier the endpoint accepts.

  • api_key (str) -- API credential supplied by the application.

  • base_url (str | None) -- API root. Required unless the subclass sets default_base_url. A value that already names the /v1/messages endpoint is accepted, and the path is trimmed before the client is built; the trimmed value is what the client keeps.

  • transport (httpx.AsyncBaseTransport | None) -- Optional HTTPX transport for isolated tests or custom routing.

  • retry (RetryOptions) -- Exponential backoff for transient failures before output starts.

  • timeout (TimeoutOptions) -- How long the provider may stay silent before the request is given up on. See TimeoutOptions.

  • prompt_cache (bool) -- Mark cache breakpoints, for a service that reads them. Off by default. A request's cache_mode can narrow this to the stable prefix or turn it off.

  • max_tokens (int) -- Output budget for one response. Thinking is paid out of it.

  • extra_headers (Mapping[str, str] | None) -- HTTP headers sent on every request after the adapter's own.

  • extra_query (Mapping[str, str] | None) -- URL query parameters sent on every request.

  • extra_body (Mapping[str, JsonValue] | None) -- JSON fields merged into every request body last.

provider_name: str = 'anthropic'#

Name stored on messages this provider produced. Signed blocks are sent back only to the same name and model.

bearer_auth: ClassVar[bool] = False#

Authenticate with Authorization: Bearer as well as x-api-key. The services that take only the bearer token ignore the other header.

native_deferred_tools: bool = False#

See zett_agent.model.NativeDeferredToolsModel.native_deferred_tools. Only Anthropic itself loads a defer_loading tool when a tool_reference names it.

default_base_url: ClassVar[str | None] = None#

API root used when no base_url is given. A subclass for one service sets it.

vendor_headers()[源代码]#

Return the headers this service wants on every request.

They are sent before extra_headers, so the application can still replace one.

返回类型:

dict[str, str]

request_fields(request)[源代码]#

Return the reasoning and output-budget fields of request.

These are merged over the standard body. The default is Anthropic's: adaptive thinking, with the reasoning level sent as output_config.effort and no token budget, so max_tokens is left as configured. The model decides how much to think within that level. Thinking cannot be combined with a forced tool choice, and is explicitly disabled when the level is OFF. A field given in extra_body replaces one returned here.

参数:

request (ModelRequest)

返回类型:

dict[str, JsonValue]

mark_cache(body, client_tools)[源代码]#

Put cache markers into body (and the tool definitions in client_tools).

The default marks Anthropic's breakpoints on the largest stable request prefixes: the tool definitions, the whole system prompt, and the conversation so far. Anthropic caches only what a cache_control marker asks for, then reads each cached prefix at a fraction of the input price. A prefix shorter than the model's minimum cacheable length is ignored silently. Nothing is marked unless prompt_cache is on. Called only for CacheMode.READ_WRITE; CacheMode.READ calls mark_stable_cache() instead.

参数:
返回类型:

None

mark_stable_cache(body, client_tools)[源代码]#

Mark only the stable tool and system prefix, for CacheMode.READ.

Override this hook when a service needs different stable-prefix markers. The base version marks the last loaded tool definition and the system prompt, and nothing newer; the newest turn is left unmarked so a one-off request can reuse a warm prefix without writing its new content.

参数:
返回类型:

None

start_usage(usage)[源代码]#

Read the usage object of the message_start event.

Cache reads and writes are reported next to input_tokens, not inside it, so the total input is their sum. Only a reported read count measures the hit rate, which is a share of the input that was read: a payload without that counter, or with only the one written, leaves the rate unknown rather than a verified zero. Anthropic itself always reports both.

参数:

usage (Mapping[str, JsonValue])

返回类型:

ModelUsage

finish_usage(usage, update)[源代码]#

Fold the usage object of the message_delta event into usage.

Anthropic updates only output_tokens there; a relay that buffers the response often reports the whole usage at the end instead, and counters the update names are the final ones. A counter it names as zero is kept only when it was zero already: a relay that pads its delta to a fixed schema writes zero where it has nothing to say, and the earlier measurement is the real one.

input_tokens is the uncached part throughout, never the total: one the update leaves out is whatever the counts before it carried beyond the cache they had already accounted for. That subtraction assumes input_tokens includes the cache, as every ModelUsage this class produces does. An update that names no counter at all is skipped, which also keeps a delta padded entirely with zeros off the arithmetic below.

抛出:

ValueError -- A counter went negative, which a subclass whose start_usage reports the uncached input rather than the total can cause.

参数:
返回类型:

ModelUsage

message_stop(finish_reason, details, *, has_tool_calls)[源代码]#

Say why the response ended, from stop_reason and stop_details.

参数:
  • finish_reason (str | None)

  • details (Mapping[str, JsonValue])

  • has_tool_calls (bool)

返回类型:

StopInfo

status_error(error)[源代码]#

Turn an SDK failure from opening the request into the typed error the runtime reports.

参数:

error (AnthropicError)

返回类型:

ProviderError

async aclose()[源代码]#

Close the owned SDK connection pool.

返回类型:

None

response: bool = False#

Whether this adapter uses a Responses-style endpoint instead of its provider's traditional message or chat-completions endpoint. Only the providers read it; the runtime does not.

sync(*, runtime=None)#

Return a context-managed synchronous view; optionally share a runtime.

Omitting runtime creates a new background thread for this view. Passing an existing runtime reuses its loop and leaves its shutdown to the caller. This API is for service entry points, not Extension lifecycle hooks.

示例

Use a model or tool from a plain function:

with read_file.sync() as read:
    result = read({"file_path": "README.md"})
参数:

runtime (SyncRuntime | None)

返回类型:

SyncObject[Self]