Nous.Messages.OpenAI (nous v0.15.6)
View SourceOpenAI 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 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.
@spec from_messages([map()]) :: [Nous.Message.t()]
Convert OpenAI format messages to internal Message structs.
@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"}
@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.
@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"}
]