openai

    Thin OpenAI API client for MoonBit built on gaato/mttp_core: models, embeddings, responses (buffered and streaming).

    openai
    llm
    sdk
    responses
    embeddings
    Download zip
    Author
    Version
    0.11.0
    License
    Apache-2.0
    Last updated
    13 days ago
    Downloads
    391

    #gaato/openai

    An unofficial OpenAI API client for MoonBit. It sends Responses and Chat Completions requests, buffered or streamed, with function tools; creates embeddings; and lists and retrieves models. Through base_url, the same client talks to other servers that implement the OpenAI API, such as Ollama, OpenRouter or DeepSeek.

    The client does no I/O of its own. It sends through an HTTP Backend and reads time from a Clock that you pass in, so it builds for every MoonBit target and a test can hand it a fake backend. gaato/mttp supplies the real ones.

    Not affiliated with OpenAI. A minor release can change the API; the changelog lists every change.

    What it does not cover:

    • OpenAI endpoints other than the ones above, such as images, audio, files, batches or the Realtime API.
    • Image, audio or file inputs. Chat message content and Responses input are plain strings, and extra cannot replace them.
    • Base64 embeddings. Vectors are decoded from JSON number arrays.

    #Install

    moon add gaato/openai moon add gaato/mttp

    An application imports gaato/openai and gaato/mttp. A library that wraps this client adds gaato/mttp_core instead of gaato/mttp, and takes the backend and clock from its caller.

    #Ask a question

    ask sends one question and returns the reply's text:

    ///|
    pub async fn ask(
    client : @openai.OpenAI,
    model : String,
    question : String,
    ) -> Result[String, @openai.OpenAIFailure] {
    let request = @openai.ChatRequest::new(model~, messages=[
    @openai.ChatMessage::user(question),
    ])
    match client.chat_completion(request) {
    Ok(reply) => Ok(reply.text)
    Err(failure) => Err(failure)
    }
    }

    A native command-line program around it imports gaato/openai, gaato/mttp, moonbitlang/core/env and moonbitlang/core/debug in its moon.pkg. Set OPENAI_API_KEY and OPENAI_MODEL, and OPENAI_BASE_URL for a compatible server, then run moon run <package> --target native -- "What is a lunar eclipse?".

    ///|
    fn main {
    guard @env.args() is [_, question] else {
    println("Pass one quoted question.")
    @env.exit(2)
    }
    guard @env.get_env_var("OPENAI_API_KEY") is Some(api_key) &&
    @env.get_env_var("OPENAI_MODEL") is Some(model) else {
    println("Set OPENAI_API_KEY and OPENAI_MODEL.")
    @env.exit(2)
    }
    @mttp.run(async fn() {
    let backend = @mttp.backend()
    defer backend.close()
    let openai = @openai.OpenAI::new(
    api_key~,
    backend,
    @mttp.clock(),
    timer=@mttp.timer(),
    base_url?=@env.get_env_var("OPENAI_BASE_URL"),
    )
    match ask(openai, model, question) {
    Ok(text) => println(text)
    Err(failure) => {
    println(@debug.to_string(failure))
    @env.exit(1)
    }
    }
    })
    }

    Build one OpenAI value and reuse it for every call. To keep a conversation going, pass the earlier ChatMessage::system, user and assistant turns in messages with each request.

    #Stream text as it arrives

    ///|
    /// Streams a response, passing each piece of text to `on_text` as it arrives.
    pub async fn stream_text(
    openai : @openai.OpenAI,
    model~ : String,
    on_text : (String) -> Unit,
    ) -> Result[Unit, @openai.OpenAIFailure] {
    openai.stream_response(
    @openai.ResponseRequest::new(model~, input="Write a haiku about rivers."),
    event => if event is OutputTextDelta(text) { on_text(text) },
    )
    }

    The callback receives every ResponseEvent; this one keeps only the text. stream_chat_completion takes the same ChatRequest as chat_completion and delivers ChatEvents: Delta text, ReasoningDelta, ToolCallDelta, Finished and Usage. Feed each ToolCallDelta to a ToolCallAccumulator, including its extra map, and call finish() for the complete ToolCalls. The call returns when the stream ends, which can happen without a Finished event. Event, status and finish-reason enums keep unknown values and are #non_exhaustive, so a match on them needs a _ arm.

    #Let the model call your function

    Here the application supplies stock_for, which looks up a product by SKU and returns its availability as text. The model either answers at once or asks for lookups; each result goes back with its call's ID, and the second reply is the answer.

    ///|
    pub async fn answer_with_stock(
    client : @openai.OpenAI,
    model : String,
    question : String,
    stock_for : (String) -> String,
    ) -> Result[String, @openai.OpenAIFailure] {
    let tools = [
    @openai.ToolDef::new(
    name="lookup_stock",
    description="Look up availability for a product SKU",
    parameters={
    "type": "object",
    "properties": { "sku": { "type": "string" } },
    "required": ["sku"],
    },
    ),
    ]
    let messages = [@openai.ChatMessage::user(question)]
    let first = match
    client.chat_completion(@openai.ChatRequest::new(model~, messages~, tools~)) {
    Ok(reply) => reply
    Err(failure) => return Err(failure)
    }
    if first.tool_calls.is_empty() {
    return Ok(first.text)
    }
    // The assistant turn goes back first, with any reasoning the server sent.
    messages.push(
    @openai.ChatMessage::assistant_tool_calls(
    first.tool_calls,
    content=first.text,
    reasoning_content?=first.reasoning_content,
    ),
    )
    for call in first.tool_calls {
    let args = Some(call.arguments_json()) catch { _ => None }
    let result = match (call.name, args) {
    ("lookup_stock", Some({ "sku": String(sku), .. })) => stock_for(sku)
    _ => "Lookup failed: expected lookup_stock with a string sku."
    }
    messages.push(
    @openai.ChatMessage::tool(tool_call_id=call.id, content=result),
    )
    }
    // `tool_choice="none"` asks for the answer instead of another lookup.
    let request = @openai.ChatRequest::new(
    model~,
    messages~,
    tools~,
    tool_choice="none",
    )
    match client.chat_completion(request) {
    Ok(reply) => Ok(reply.text)
    Err(failure) => Err(failure)
    }
    }

    ToolCall.arguments is the model's raw text; arguments_json() parses it and raises if it is not JSON. assistant_tool_calls also sends back each call's extra fields, such as Gemini's thought signatures.

    With the Responses API, pass tools to ResponseRequest::new, read Response.tool_calls, and send the results in a new request with previous_response_id=first.id and .with_tool_outputs([(call.id, output)]). That request still sends its input as a user message beside the outputs.

    #Other operations

    list_models(), retrieve_model(id) and create_embeddings(@openai.EmbeddingRequest::new(model~, input=[...])) return Models and an EmbeddingResponse whose data[i].embedding is an Array[Double]. ChatCompletion.raw and Response.raw keep the full JSON for fields the typed view leaves out.

    extra on ChatRequest, ResponseRequest and EmbeddingRequest adds JSON fields to the request body for provider options. A key the request type manages itself, such as model, messages, input, tools or stream, returns a Validation failure, even when its typed option is unset. OpenAI::new also takes organization and project, sent as the openai-organization and openai-project headers.

    #Failures

    Every call returns a Result, and raises only for failures outside the API:

    OutcomeMeaning
    Err(Validation(message))Refused before sending: a colliding extra key, an API key that is not a valid header value (surrounding whitespace, for one), base64 embeddings.
    Err(Api(head, error, body~))The server returned an error envelope, on any HTTP status including 200, or inside a stream. api_error(failure) returns its ApiErrorBody (message, type_, param, code, with numeric codes as strings). At most 1 MiB of the body is kept.
    Err(Response(failure))Any other unexpected status, or a body that does not decode.
    raised TransportErrorThe network failed, a deadline passed, or a body went over its limit (TooLarge).
    raised by your callbackAn error your stream callback raises stops the stream and reaches the caller.

    In a Responses stream, a data: frame of type: "error" reaches the callback as ResponseEvent::Error, and the call can still return Ok(()) when the stream ends; match Error if the caller must know. A frame named event: error, or an error envelope in either kind of stream, stops delivery and returns Err(Api(...)).

    #Retries, deadlines and limits

    Setting (on OpenAI::new)Default
    retry2 retries on 408, 409, 429, every 5xx, timeouts and network failures, for every method, POST included. Waits back off from 0.5 s to 8 s; x-should-retry is obeyed; a Retry-After over 2 minutes returns the failure instead of waiting.
    timeout_ms600 s for each attempt, and for each read while streaming.
    total_timeout_msNone. Bounds the whole call, retries, waits and stream callbacks included. Needs timer=; without one the call raises InvalidRequest.
    max_body_bytes64 MiB for a buffered response.
    Stream events16 MiB for each event.

    The default follows OpenAI's official Python SDK, so a retried generation can run, and be billed, twice. retry=@mttp.RetryPolicy::conservative() retries a POST only when the failure proves the request was not sent, and @mttp.RetryPolicy::none() turns retries off. A 429 whose body carries a quota, balance or disabled-account code (insufficient_quota, for one) stops at once, even under x-should-retry: true. A stream is never retried once its callback has received an event.

    The API key travels in authorization, which is marked as a credential. A redirect strips it when the host, port or scheme changes, except for a same-host HTTP port 80 to HTTPS port 443 upgrade, and HTTPS to HTTP is refused by default. Debug output of an OpenAI value hides it.

    For other headers or client settings, build an mttp Client with @mttp.client(...) and pass it to OpenAI::from_client. That client's own retry, timeout and limit settings then apply instead of the defaults above, and no authorization is added, so put "Bearer <key>" in its headers.

    #OpenAI-compatible servers

    Pass the server's API root as base_url to OpenAI::new. The SDK's tests replay responses built from each provider's documentation, not recorded from live servers, for the endpoints listed below. An endpoint not listed is untested with that provider; its documentation says whether it exists, and support varies by model.

    Providerbase_urlTestedSDK handling
    Ollamahttp://localhost:11434/v1chat, streaming, Responses, embeddings, models, retrieve_modelReads reasoning as reasoning_content.
    OpenRouterhttps://openrouter.ai/api/v1chat, streaming, Responses, embeddings, modelsNumeric error codes and errors in HTTP 200 become Api.
    DeepSeekhttps://api.deepseek.com (no /v1)chat, streaming, Responses, modelsModel.created can be None.
    Geminihttps://generativelanguage.googleapis.com/v1beta/openaichat, streaming, tool calls, embeddingsErrors wrapped in a JSON array; an omitted embedding index reads as 0.
    Moonshot / Kimihttps://api.moonshot.ai/v1chat, streaming, Responses, models
    Zhipuhttps://open.bigmodel.cn/api/paas/v4chat, streaming, embeddingsQuota codes 1113, 1308 and 1310 stop retries.
    DashScope / Qwenyour region's compatible-mode/v1 URLchat, streaming, Responses, embeddingsprompt_tokens can be None.
    Voyage AIhttps://api.voyageai.com/v1embeddingsInteger vectors decode; a string detail error becomes the Api message.

    Providers may restrict temperature, tool choices or streaming tools; Ollama does not implement tool_choice, which the tool example above sets. Provider options go in extra, for example { "input_type": "query" } on a Voyage EmbeddingRequest. Thinking models return ChatCompletion.reasoning_content and stream ReasoningDelta pieces; send the reasoning back with the assistant turn, as the tool example does, when the provider asks for it.

    #Packages

    PackageWhat it is
    gaato/openaiThe OpenAI client and its request, response and event types
    gaato/openai/genRequest builders, decoders and wire types for the same operations, generated from OpenAI's OpenAPI spec

    #License

    Apache-2.0

    ApiErrorBody

    pub(all) struct ApiErrorBody {
    message : String
    type_ : String?
    param : String?
    code : String?
    } derive(Eq,
    Debug
    )

    The error body returned by the OpenAI API.

    test {
    let error : @openai.ApiErrorBody = {
    message: "invalid request",
    type_: Some("invalid_request_error"),
    param: None,
    code: None,
    }
    assert_eq(error.message, "invalid request")
    }

    ApiErrorBody::equal

    Compares API error bodies field by field.

    ApiErrorBody::not_equal

    fn ApiErrorBody::not_equal(x : ApiErrorBody, y : ApiErrorBody) -> Bool

    Compares API error bodies field by field.

    ApiErrorBody::to_repr

    Debug representation of an API error body.

    ChatCompletion

    pub(all) struct ChatCompletion {
    id : String
    model : String
    text : String
    reasoning_content : String?
    finish_reason : FinishReason?
    usage : Usage?
    tool_calls : Array[ToolCall]
    raw :
    Json

    } derive(Eq,
    Debug
    )

    A buffered chat completion together with its original JSON value.

    ChatCompletion::equal

    Compares chat completions field by field.

    ChatCompletion::not_equal

    fn ChatCompletion::not_equal(x : ChatCompletion, y : ChatCompletion) -> Bool

    Compares chat completions field by field.

    ChatCompletion::to_repr

    Debug representation of a chat completion.

    ChatEvent

    pub(all) enum ChatEvent {
    Delta(String)
    ReasoningDelta(String)
    ToolCallDelta(index~ : Int, id~ : String?, name~ : String?, arguments~ : String, extra~ : Map[String,
    Json
    ])
    Finished(FinishReason)
    Usage(Usage)
    Other(String,
    Json
    )
    } derive(Eq,
    Debug
    )

    One event from a streaming chat completion. Unknown chunks retain raw JSON.

    ChatEvent::equal

    fn ChatEvent::equal(ChatEvent, ChatEvent) -> Bool

    Compares chat events, including retained unknown JSON.

    ChatEvent::not_equal

    fn ChatEvent::not_equal(x : ChatEvent, y : ChatEvent) -> Bool

    Compares chat events, including retained unknown JSON.

    ChatEvent::to_repr

    Debug representation of a chat event.

    ChatMessage

    pub(all) struct ChatMessage {
    role : String
    content : String
    name : String?
    tool_calls : Array[ToolCall]?
    tool_call_id : String?
    reasoning_content : String?
    } derive(Eq,
    Debug
    )

    One text message sent to the Chat Completions API.

    test {
    let message = @openai.ChatMessage::user("hello")
    assert_eq(message.role, "user")
    assert_eq(message.content, "hello")
    }

    ChatMessage::assistant

    fn ChatMessage::assistant(content : String, reasoning_content? : String) -> ChatMessage

    Creates an assistant chat message.

    test {
    assert_eq(@openai.ChatMessage::assistant("hello").role, "assistant")
    }

    ChatMessage::assistant_tool_calls

    fn ChatMessage::assistant_tool_calls(tool_calls : Array[ToolCall], content? : String, reasoning_content? : String) -> ChatMessage

    Creates an assistant message containing function tool calls. When content is absent it is encoded without a content field. Provider extensions are copied, including nested objects and arrays.

    test {
    let message = @openai.ChatMessage::assistant_tool_calls([
    { id: "call_1", name: "lookup", arguments: "{}", extra: {}, },
    ])
    assert_eq(message.tool_calls.unwrap().length(), 1)
    }

    ChatMessage::equal

    fn ChatMessage::equal(ChatMessage, ChatMessage) -> Bool

    Compares chat messages field by field.

    ChatMessage::not_equal

    fn ChatMessage::not_equal(x : ChatMessage, y : ChatMessage) -> Bool

    Compares chat messages field by field.

    ChatMessage::system

    fn ChatMessage::system(content : String) -> ChatMessage

    Creates a system chat message.

    test {
    assert_eq(@openai.ChatMessage::system("Be concise").role, "system")
    }

    ChatMessage::to_repr

    Debug representation of a chat message.

    ChatMessage::tool

    fn ChatMessage::tool(tool_call_id~ : String, content~ : String) -> ChatMessage

    Creates a tool result message associated with one model tool call.

    test {
    let message = @openai.ChatMessage::tool(tool_call_id="call_1", content="done")
    assert_eq(message.tool_call_id, Some("call_1"))
    }

    ChatMessage::user

    fn ChatMessage::user(content : String) -> ChatMessage

    Creates a user chat message.

    test {
    assert_eq(@openai.ChatMessage::user("hello").role, "user")
    }

    ChatRequest

    pub(all) struct ChatRequest {
    model : String
    messages : Array[ChatMessage]
    max_tokens : Int?
    temperature : Double?
    reasoning_effort : String?
    tools : Array[ToolDef]?
    tool_choice :
    Json
    ?
    extra : Map[String,
    Json
    ]
    } derive(Eq,
    Debug
    )

    Input accepted by buffered and streaming Chat Completions operations.

    ChatRequest::equal

    fn ChatRequest::equal(ChatRequest, ChatRequest) -> Bool

    Compares chat requests field by field.

    ChatRequest::new

    fn ChatRequest::new(model~ : String, messages~ : Array[ChatMessage], max_tokens? : Int, temperature? : Double, reasoning_effort? : String, tools? : Array[ToolDef], tool_choice? :
    Json
    , extra? : Map[String,
    Json
    ]) -> ChatRequest

    Creates a chat request and snapshots its message history, tool array, and extra fields. The extra fields on the request and its tool calls are copied recursively.

    test {
    let request = @openai.ChatRequest::new(model="gpt-4o-mini", messages=[
    @openai.ChatMessage::user("hello"),
    ])
    assert_eq(request.messages.length(), 1)
    }

    ChatRequest::not_equal

    fn ChatRequest::not_equal(x : ChatRequest, y : ChatRequest) -> Bool

    Compares chat requests field by field.

    ChatRequest::to_repr

    Debug representation of a chat request.

    Embedding

    pub(all) struct Embedding {
    index : Int
    embedding : Array[Double]
    } derive(Eq,
    Debug
    )

    One embedding vector and its provider-supplied index, which defaults to zero when omitted.

    Embedding::equal

    fn Embedding::equal(Embedding, Embedding) -> Bool

    Compares embedding values field by field.

    Embedding::not_equal

    fn Embedding::not_equal(x : Embedding, y : Embedding) -> Bool

    Compares embedding values field by field.

    Embedding::to_repr

    Debug representation of an embedding value.

    EmbeddingRequest

    pub(all) struct EmbeddingRequest {
    model : String
    input : Array[String]
    dimensions : Int?
    user : String?
    extra : Map[String,
    Json
    ]
    } derive(Eq,
    Debug
    )

    Input accepted by the embeddings operation.

    EmbeddingRequest::equal

    Compares embedding requests field by field.

    EmbeddingRequest::new

    fn EmbeddingRequest::new(model~ : String, input~ : Array[String], dimensions? : Int, user? : String, extra? : Map[String,
    Json
    ]) -> EmbeddingRequest

    Creates an embedding request and snapshots its input array and extra fields, including nested JSON objects and arrays.

    test {
    let request = @openai.EmbeddingRequest::new(
    model="embedding-model",
    input=["hello"],
    extra={ "input_type": "query", "output_dimension": 256 },
    )
    assert_eq(request.extra.get("input_type"), Some(Json("query")))
    }

    EmbeddingRequest::not_equal

    fn EmbeddingRequest::not_equal(x : EmbeddingRequest, y : EmbeddingRequest) -> Bool

    Compares embedding requests field by field.

    EmbeddingRequest::to_repr

    Debug representation of an embedding request.

    EmbeddingResponse

    pub(all) struct EmbeddingResponse {
    data : Array[Embedding]
    model : String
    prompt_tokens : Int?
    total_tokens : Int?
    } derive(Eq,
    Debug
    )

    The flattened result of an embeddings operation. Unreported token counts are None.

    EmbeddingResponse::equal

    Compares embedding responses field by field.

    EmbeddingResponse::not_equal

    fn EmbeddingResponse::not_equal(x : EmbeddingResponse, y : EmbeddingResponse) -> Bool

    Compares embedding responses field by field.

    EmbeddingResponse::to_repr

    Debug representation of an embedding response.

    FinishReason

    pub(all) enum FinishReason {
    Stop
    Length
    ToolCalls
    ContentFilter
    Unknown(String)
    } derive(Eq,
    Debug
    )

    Why a chat completion stopped. Unknown values are retained.

    FinishReason::equal

    Compares finish reasons, including unknown raw values.

    FinishReason::not_equal

    fn FinishReason::not_equal(x : FinishReason, y : FinishReason) -> Bool

    Compares finish reasons, including unknown raw values.

    FinishReason::to_repr

    Debug representation of a finish reason.

    Model

    pub(all) struct Model {
    id : String
    created : Int64?
    owned_by : String?
    } derive(Eq,
    Debug
    )

    Basic information about an OpenAI model.

    Model::equal

    fn Model::equal(Model, Model) -> Bool

    Compares model information field by field.

    Model::not_equal

    fn Model::not_equal(x : Model, y : Model) -> Bool

    Compares model information field by field.

    Model::to_repr

    Debug representation of model information.

    OpenAI

    pub struct OpenAI {
    // private fields
    }

    A thin OpenAI client backed by the runtime-free mttp Client.
    impl Debug for OpenAI

    OpenAI::chat_completion

    async fn OpenAI::chat_completion(self : OpenAI, request : ChatRequest) -> Result[ChatCompletion, OpenAIFailure]

    Creates and buffers one Chat Completions response.

    OpenAI::create_embeddings

    async fn OpenAI::create_embeddings(self : OpenAI, request : EmbeddingRequest) -> Result[EmbeddingResponse, OpenAIFailure]

    Creates embeddings for every input string in the request.

    OpenAI::create_response

    async fn OpenAI::create_response(self : OpenAI, request : ResponseRequest) -> Result[Response, OpenAIFailure]

    Creates and buffers one model response.

    OpenAI::from_client

    Wraps a preconfigured runtime client for compatible APIs, Azure, and tests.

    OpenAI::list_models

    async fn OpenAI::list_models(self : OpenAI) -> Result[Array[Model], OpenAIFailure]

    Lists the models visible to the configured account.

    OpenAI::new

    fn OpenAI::new(api_key~ : String, backend : &
    Backend
    , clock : &
    Clock
    , base_url? : String, organization? : String, project? : String, retry? :
    RetryPolicy
    , timer? : &
    Timer
    , timeout_ms? : Int, max_body_bytes? : Int, total_timeout_ms? : Int) -> OpenAI

    Creates an OpenAI client using bearer authentication and optional tenant headers.

    retry defaults to the official SDK's behaviour (openai-python, _base_client.py): an SDK-local policy with two retries of 408, 409, 429 and every 5xx, and of a timeout or network failure, for every method including POST, so a generation can run twice; x-should-retry is obeyed, and a Retry-After over two minutes is not waited for. Pass retry=@client.RetryPolicy::conservative() to retry a POST only on failures that prove nothing was sent, unless explicitly declared replay-safe. Recognized quota, balance and disabled-account codes in a 429 body stop retries even when x-should-retry is true; unknown codes retain this policy.

    Each attempt is limited to timeout_ms (600 s, the official default) and, when total_timeout_ms is given, the whole call, retries included, to that. A total deadline requires a supplied Timer and includes admission, waits and stream callbacks. Backend phase deadlines can finish attempts earlier.

    OpenAI::retrieve_model

    async fn OpenAI::retrieve_model(self : OpenAI, model : String) -> Result[Model, OpenAIFailure]

    Retrieves one model by identifier.

    OpenAI::stream_chat_completion

    async fn OpenAI::stream_chat_completion(self : OpenAI, request : ChatRequest, f : async (ChatEvent) -> Unit) -> Result[Unit, OpenAIFailure]

    Dispatches Chat Completions events in wire order, including final usage. EOF, [DONE], decoding failure and callback failure close the stream.

    OpenAI::stream_response

    async fn OpenAI::stream_response(self : OpenAI, request : ResponseRequest, f : async (ResponseEvent) -> Unit) -> Result[Unit, OpenAIFailure]

    Dispatches Responses events in wire order, closing on EOF, [DONE] or failure. A typed error in an ordinary data frame reaches the callback as Error. The stream can still return Ok(()) at EOF after delivering this event. User callback failures happen outside the retry attempt.

    OpenAI::to_repr

    Redacted debug representation of an OpenAI client.

    OpenAIFailure

    An expected SDK failure. TransportError and unknown user errors remain raised.

    OpenAIFailure::to_repr

    Formats an expected failure with its original response metadata.

    Response

    pub(all) struct Response {
    id : String
    status : ResponseStatus
    model : String
    output_text : String
    usage : Usage?
    tool_calls : Array[ToolCall]
    raw :
    Json

    } derive(Eq,
    Debug
    )

    A decoded response together with its original JSON value.

    Response::equal

    fn Response::equal(Response, Response) -> Bool

    Compares decoded responses field by field.

    Response::not_equal

    fn Response::not_equal(x : Response, y : Response) -> Bool

    Compares decoded responses field by field.

    Response::to_repr

    Debug representation of a decoded response.

    ResponseEvent

    pub(all) enum ResponseEvent {
    Created(Response)
    InProgress(Response)
    OutputTextDelta(String)
    OutputTextDone(String)
    FunctionCallArgumentsDelta(item_id~ : String, delta~ : String)
    FunctionCallArgumentsDone(item_id~ : String, arguments~ : String)
    Completed(Response)
    Failed(Response)
    Incomplete(Response)
    Error(ApiErrorBody)
    Other(String,
    Json
    )
    } derive(Eq,
    Debug
    )

    One event from a streaming response. Unknown event types retain their raw JSON.

    ResponseEvent::equal

    Compares response events, including retained unknown JSON.

    ResponseEvent::not_equal

    fn ResponseEvent::not_equal(x : ResponseEvent, y : ResponseEvent) -> Bool

    Compares response events, including retained unknown JSON.

    ResponseEvent::to_repr

    Debug representation of a response event.

    ResponseRequest

    pub(all) struct ResponseRequest {
    model : String
    input : String
    instructions : String?
    max_output_tokens : Int?
    temperature : Double?
    previous_response_id : String?
    tools : Array[ToolDef]?
    tool_choice :
    Json
    ?
    extra : Map[String,
    Json
    ]
    // private fields
    } derive(Eq,
    Debug
    )

    Input accepted by buffered and streaming response creation.

    ResponseRequest::equal

    Compares response requests field by field.

    ResponseRequest::new

    fn ResponseRequest::new(model~ : String, input~ : String, instructions? : String, max_output_tokens? : Int, temperature? : Double, previous_response_id? : String, tools? : Array[ToolDef], tool_choice? :
    Json
    , extra? : Map[String,
    Json
    ]) -> ResponseRequest

    Creates a response request and snapshots its extra fields, including nested JSON objects and arrays.

    test {
    let request = @openai.ResponseRequest::new(model="gpt-4.1", input="hello")
    assert_eq(request.extra, {})
    }

    ResponseRequest::not_equal

    fn ResponseRequest::not_equal(x : ResponseRequest, y : ResponseRequest) -> Bool

    Compares response requests field by field.

    ResponseRequest::to_repr

    Debug representation of a response request.

    ResponseRequest::with_tool_outputs

    fn ResponseRequest::with_tool_outputs(self : ResponseRequest, outputs : Array[(String, String)]) -> ResponseRequest

    Returns a request with function outputs appended to its input items.

    test {
    let request = @openai.ResponseRequest::new(model="gpt-4.1", input="continue").with_tool_outputs([
    ("call_1", "done"),
    ],
    )
    assert_eq(request.input, "continue")
    }

    ResponseStatus

    pub(all) enum ResponseStatus {
    Completed
    Failed
    InProgress
    Incomplete
    Cancelled
    Queued
    Unknown(String)
    } derive(Eq,
    Debug
    )

    A response lifecycle status. Unknown values are retained for forward compatibility.

    ResponseStatus::equal

    Compares response statuses, including unknown raw values.

    ResponseStatus::not_equal

    fn ResponseStatus::not_equal(x : ResponseStatus, y : ResponseStatus) -> Bool

    Compares response statuses, including unknown raw values.

    ResponseStatus::to_repr

    Debug representation of a response status.

    ToolCall

    pub(all) struct ToolCall {
    id : String
    name : String
    arguments : String
    extra : Map[String,
    Json
    ]
    } derive(Eq,
    Debug
    )

    A function call produced by a model. Arguments remain raw text until parsed.

    ToolCall::arguments_json

    Parses the model-produced argument string as JSON on demand.

    test {
    let call : @openai.ToolCall = {
    id: "call_1",
    name: "lookup",
    arguments: "{\"id\":1}",
    extra: {},
    }
    assert_eq(call.arguments_json(), { "id": 1 })
    }

    ToolCall::equal

    fn ToolCall::equal(ToolCall, ToolCall) -> Bool

    Compares tool calls field by field.

    ToolCall::not_equal

    fn ToolCall::not_equal(x : ToolCall, y : ToolCall) -> Bool

    Compares tool calls field by field.

    ToolCall::to_repr

    Debug representation of a tool call.

    ToolCallAccumulator

    pub struct ToolCallAccumulator {
    // private fields
    }

    Incrementally reconstructs tool calls from streamed chat deltas.

    test {
    let calls = @openai.ToolCallAccumulator::new()
    calls.feed(index=0, id="call_1", name="lookup", arguments="{}")
    assert_eq(calls.finish()[0].arguments, "{}")
    }

    ToolCallAccumulator::feed

    fn ToolCallAccumulator::feed(self : ToolCallAccumulator, index~ : Int, id? : String, name? : String, arguments~ : String, extra? : Map[String,
    Json
    ]) -> Unit

    Adds one tool-call delta. The first supplied id and name for an index win. Pass the event's extra fields to preserve an independent copy of provider metadata.

    ToolCallAccumulator::finish

    Returns reconstructed calls ordered by their stream index. Missing ids or names are returned as empty strings. Each result owns a copy of its provider metadata.

    ToolCallAccumulator::new

    Creates an empty streamed tool-call accumulator.

    ToolDef

    pub(all) struct ToolDef {
    name : String
    description : String?
    parameters :
    Json

    strict : Bool?
    } derive(Eq,
    Debug
    )

    A function tool definition shared by Chat Completions and Responses.

    test {
    let tool = @openai.ToolDef::new(name="lookup", parameters={ "type": "object" })
    assert_eq(tool.name, "lookup")
    }

    ToolDef::equal

    fn ToolDef::equal(ToolDef, ToolDef) -> Bool

    Compares tool definitions field by field.

    ToolDef::new

    fn ToolDef::new(name~ : String, parameters~ :
    Json
    , description? : String, strict? : Bool) -> ToolDef

    Creates a function tool definition with a JSON Schema parameter object.

    ToolDef::not_equal

    fn ToolDef::not_equal(x : ToolDef, y : ToolDef) -> Bool

    Compares tool definitions field by field.

    ToolDef::to_repr

    Debug representation of a tool definition.

    Usage

    pub(all) struct Usage {
    input_tokens : Int
    output_tokens : Int
    total_tokens : Int
    } derive(Eq,
    Debug
    )

    Token usage reported by a response.

    Usage::equal

    fn Usage::equal(Usage, Usage) -> Bool

    Compares response usage field by field.

    Usage::not_equal

    fn Usage::not_equal(x : Usage, y : Usage) -> Bool

    Compares response usage field by field.

    Usage::to_repr

    Debug representation of response usage.

    api_error

    fn api_error(error : OpenAIFailure) -> ApiErrorBody?

    Extracts a provider error body from an HTTP status failure or an Api failure. Returns None for transport, decode, configuration, and malformed error bodies.