Nous.Messages.Anthropic (nous v0.15.5)

View Source

Anthropic format message conversion.

Handles conversion between internal Message structs and Anthropic API format.

Summary

Functions

Convert Anthropic format messages to internal Message structs.

Parse Anthropic response into a Message.

Parse an Anthropic-format usage map into a %Nous.Usage{} struct.

Convert messages to Anthropic format.

Functions

from_messages(anthropic_messages)

@spec from_messages([map()]) :: [Nous.Message.t()]

Convert Anthropic format messages to internal Message structs.

from_response(response)

@spec from_response(map()) :: Nous.Message.t()

Parse Anthropic response into a Message.

Examples

iex> response = %{"content" => [%{"type" => "text", "text" => "Hello"}], "model" => "claude-3"}
iex> Messages.Anthropic.from_response(response)
%Message{role: :assistant, content: "Hello"}

parse_usage(usage_data)

@spec parse_usage(map() | nil) :: Nous.Usage.t()

Parse an Anthropic-format usage map into a %Nous.Usage{} struct.

Used by both the non-streaming response parser and the streaming normalizer (message_delta carries incremental output tokens).

to_format(messages)

@spec to_format([Nous.Message.t()]) :: {String.t() | nil, [map()]}

Convert messages to Anthropic format.

Returns {system_prompt, messages} where system prompt is extracted and combined, and messages are converted to Anthropic format.

Examples

iex> messages = [Message.system("Be helpful"), Message.user("Hello")]
iex> Messages.Anthropic.to_format(messages)
{"Be helpful", [%{"role" => "user", "content" => "Hello"}]}