Thin OpenAI API client for MoonBit built on gaato/mttp_core: models, embeddings, responses (buffered and streaming).
moon add gaato/openai
moon add gaato/mttp///|
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)
}
}///|
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)
}
}
})
}///|
/// 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) },
)
}///|
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)
}
}| Outcome | Meaning |
|---|---|
| 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 TransportError | The network failed, a deadline passed, or a body went over its limit (TooLarge). |
| raised by your callback | An error your stream callback raises stops the stream and reaches the caller. |
| Setting (on OpenAI::new) | Default |
|---|---|
| retry | 2 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_ms | 600 s for each attempt, and for each read while streaming. |
| total_timeout_ms | None. Bounds the whole call, retries, waits and stream callbacks included. Needs timer=; without one the call raises InvalidRequest. |
| max_body_bytes | 64 MiB for a buffered response. |
| Stream events | 16 MiB for each event. |
| Provider | base_url | Tested | SDK handling |
|---|---|---|---|
| Ollama | http://localhost:11434/v1 | chat, streaming, Responses, embeddings, models, retrieve_model | Reads reasoning as reasoning_content. |
| OpenRouter | https://openrouter.ai/api/v1 | chat, streaming, Responses, embeddings, models | Numeric error codes and errors in HTTP 200 become Api. |
| DeepSeek | https://api.deepseek.com (no /v1) | chat, streaming, Responses, models | Model.created can be None. |
| Gemini | https://generativelanguage.googleapis.com/v1beta/openai | chat, streaming, tool calls, embeddings | Errors wrapped in a JSON array; an omitted embedding index reads as 0. |
| Moonshot / Kimi | https://api.moonshot.ai/v1 | chat, streaming, Responses, models | |
| Zhipu | https://open.bigmodel.cn/api/paas/v4 | chat, streaming, embeddings | Quota codes 1113, 1308 and 1310 stop retries. |
| DashScope / Qwen | your region's compatible-mode/v1 URL | chat, streaming, Responses, embeddings | prompt_tokens can be None. |
| Voyage AI | https://api.voyageai.com/v1 | embeddings | Integer vectors decode; a string detail error becomes the Api message. |
| Package | What it is |
|---|---|
| gaato/openai | The OpenAI client and its request, response and event types |
| gaato/openai/gen | Request builders, decoders and wire types for the same operations, generated from OpenAI's OpenAPI spec |
test {
let error : @openai.ApiErrorBody = {
message: "invalid request",
type_: Some("invalid_request_error"),
param: None,
code: None,
}
assert_eq(error.message, "invalid request")
}test {
let message = @openai.ChatMessage::user("hello")
assert_eq(message.role, "user")
assert_eq(message.content, "hello")
}test {
assert_eq(@openai.ChatMessage::assistant("hello").role, "assistant")
}fn ChatMessage::assistant_tool_calls(tool_calls : Array[ToolCall], content? : String, reasoning_content? : String) -> ChatMessagetest {
let message = @openai.ChatMessage::assistant_tool_calls([
{ id: "call_1", name: "lookup", arguments: "{}", extra: {}, },
])
assert_eq(message.tool_calls.unwrap().length(), 1)
}test {
assert_eq(@openai.ChatMessage::system("Be concise").role, "system")
}test {
let message = @openai.ChatMessage::tool(tool_call_id="call_1", content="done")
assert_eq(message.tool_call_id, Some("call_1"))
}test {
assert_eq(@openai.ChatMessage::user("hello").role, "user")
}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]) -> ChatRequesttest {
let request = @openai.ChatRequest::new(model="gpt-4o-mini", messages=[
@openai.ChatMessage::user("hello"),
])
assert_eq(request.messages.length(), 1)
}fn EmbeddingRequest::new(model~ : String, input~ : Array[String], dimensions? : Int, user? : String, extra? : Map[String, Json]) -> EmbeddingRequesttest {
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")))
}pub struct OpenAI {
// private fields
}async fn OpenAI::chat_completion(self : OpenAI, request : ChatRequest) -> Result[ChatCompletion, OpenAIFailure]async fn OpenAI::create_embeddings(self : OpenAI, request : EmbeddingRequest) -> Result[EmbeddingResponse, OpenAIFailure]async fn OpenAI::create_response(self : OpenAI, request : ResponseRequest) -> Result[Response, OpenAIFailure]async fn OpenAI::stream_chat_completion(self : OpenAI, request : ChatRequest, f : async (ChatEvent) -> Unit) -> Result[Unit, OpenAIFailure]async fn OpenAI::stream_response(self : OpenAI, request : ResponseRequest, f : async (ResponseEvent) -> Unit) -> Result[Unit, OpenAIFailure]pub(all) enum OpenAIFailure {
Response(ResponseFailure)
Validation(String)
Api(ResponseHead, ApiErrorBody, body~ : Bytes)
} derive(Debug)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)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]) -> ResponseRequesttest {
let request = @openai.ResponseRequest::new(model="gpt-4.1", input="hello")
assert_eq(request.extra, {})
}fn ResponseRequest::with_tool_outputs(self : ResponseRequest, outputs : Array[(String, String)]) -> ResponseRequesttest {
let request = @openai.ResponseRequest::new(model="gpt-4.1", input="continue").with_tool_outputs([
("call_1", "done"),
],
)
assert_eq(request.input, "continue")
}test {
let call : @openai.ToolCall = {
id: "call_1",
name: "lookup",
arguments: "{\"id\":1}",
extra: {},
}
assert_eq(call.arguments_json(), { "id": 1 })
}pub struct ToolCallAccumulator {
// private fields
}test {
let calls = @openai.ToolCallAccumulator::new()
calls.feed(index=0, id="call_1", name="lookup", arguments="{}")
assert_eq(calls.finish()[0].arguments, "{}")
}fn ToolCallAccumulator::feed(self : ToolCallAccumulator, index~ : Int, id? : String, name? : String, arguments~ : String, extra? : Map[String, Json]) -> Unittest {
let tool = @openai.ToolDef::new(name="lookup", parameters={ "type": "object" })
assert_eq(tool.name, "lookup")
}Install
Download zipThin OpenAI API client for MoonBit built on gaato/mttp_core: models, embeddings, responses (buffered and streaming).