Nous.Messages.OpenAI (nous v0.15.8)

View Source

OpenAI format message conversion.

Handles conversion between internal Message structs and OpenAI API format.

Summary

Functions

Decode an OpenAI tool-call arguments JSON string into a map.

Convert OpenAI format messages to internal Message structs.

Parse OpenAI response into a Message.

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

Convert messages to OpenAI format.

Functions

decode_arguments(arguments)

@spec decode_arguments(String.t() | nil) :: map()

Decode an OpenAI tool-call arguments JSON string into a map.

Falls back to %{"error" => "Invalid JSON arguments", "raw" => raw} and logs a warning when the JSON is malformed. Used by both the non-streaming response parser and the streaming ToolCallAccumulator.

from_messages(openai_messages)

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

Convert OpenAI format messages to internal Message structs.

from_response(response)

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

Parse OpenAI response into a Message.

Examples

iex> response = %{"choices" => [%{"message" => %{"role" => "assistant", "content" => "Hello"}}]}
iex> Messages.OpenAI.from_response(response)
%Message{role: :assistant, content: "Hello"}

parse_usage(usage_data)

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

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

Returns an empty %Usage{} for nil. Accepts both atom and string keys.

to_format(messages)

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

Convert messages to OpenAI format.

Examples

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