ExAgent.Providers.Anthropic (ExAgent v0.1.0)

Copy Markdown View Source

Implementation for providers that speak the Anthropic Messages API: POST {base_url}/v1/messages.

The Anthropic wire format differs from OpenAI Chat Completions in several load-bearing ways, all handled here:

  • system is top-levelSystemPrompt parts are lifted out of the message stream and sent as the system parameter, not as a message.
  • Content is an array of blocks — every message body is a list of {"type": "text" | "tool_use" | "tool_result", ...} blocks.
  • Tool calls — the model emits tool_use blocks (with an input object, not a JSON string); the agent replies with tool_result blocks in a user message keyed by tool_use_id.
  • Authx-api-key (real Anthropic) or Authorization: Bearer (e.g. Z.AI's /api/anthropic), plus the anthropic-version header.

Pointing this at Z.AI's Anthropic-compatible endpoint gives access to GLM models (glm-4.5-air, glm-4.7, glm-5.2, …) using the native format.

Summary

Functions

Split a message history into a top-level system block list and the conversation messages (with System parts removed and consecutive same-role messages merged — Anthropic requires strict alternation).

Encode Tool list into the Anthropic tools payload (or nil).

Perform a (non-streaming) Messages API request.

Perform a streaming Messages API request. Returns a lazy stream of

Functions

encode_messages(messages)

@spec encode_messages([ExAgent.Message.t()]) :: {[map()], [map()]}

Split a message history into a top-level system block list and the conversation messages (with System parts removed and consecutive same-role messages merged — Anthropic requires strict alternation).

encode_tools(model_request_parameters)

@spec encode_tools(ExAgent.ModelRequestParameters.t()) :: [map()] | nil

Encode Tool list into the Anthropic tools payload (or nil).

parse_response(body, config)

@spec parse_response(
  map(),
  struct()
) :: ExAgent.Message.Response.t()

request(model, messages, settings, params)

Perform a (non-streaming) Messages API request.

request_stream(model, messages, settings, params)

@spec request_stream(
  struct(),
  [ExAgent.Message.t()],
  ExAgent.ModelSettings.t() | nil,
  ExAgent.ModelRequestParameters.t()
) :: Enumerable.t() | {:error, term()}

Perform a streaming Messages API request. Returns a lazy stream of:

  • {:text_delta, binary},
  • {:response, Response.t()} (final assembled),
  • {:error, reason} on failure.