Type-safe, OpenAI-compatible LLM client for MoonBit: chat completions, streaming (SSE), tool calling, and multimodal input.
Dependencies
pub(all) suberror LLMError {
Transport(String)
ApiError(code~ : Int, message~ : String)
Decode(String)
Stream(String)
} derive(Debug)pub(all) struct Batch {
id : String
status : String
input_file_id : String
output_file_id : String?
error_file_id : String?
counts : BatchCounts
} derive(Debug)pub(all) struct BatchRequest {
input_file_id : String
endpoint : String
completion_window : String
}impl ToJson for BatchRequestfn BatchRequest::new(input_file_id : String, endpoint? : String, completion_window? : String) -> BatchRequestpub(all) struct ChatRequest {
model : String
messages : Array[Message]
temperature : Double?
max_tokens : Int?
top_p : Double?
stop : Array[String]?
tools : Array[Tool]?
tool_choice : ToolChoice?
frequency_penalty : Double?
presence_penalty : Double?
seed : Int?
n : Int?
response_format : ResponseFormat?
logit_bias : Map[String, Double]?
user : String?
stream : Bool
}impl ToJson for ChatRequestimpl FromJson for ChatResponsepub struct Client {
api_key : String
base_url : String
timeout_ms : Int
extra_headers : Map[String, String]
auth : AuthScheme
}async fn Client::chat_anthropic(self : Client, request : ChatRequest) -> ChatResponse raise LLMErrorasync fn Client::chat_stream(self : Client, request : ChatRequest, on_delta : (String) -> Unit) -> String raise LLMErrorasync fn Client::chat_stream_full(self : Client, request : ChatRequest, on_chunk : (StreamChunk) -> Unit) -> StreamResult raise LLMErrorasync fn Client::chat_with_policy(self : Client, request : ChatRequest, policy : RetryPolicy) -> ChatResponse raise LLMErrorasync fn Client::chat_with_retry(self : Client, request : ChatRequest, max_retries? : Int, base_delay_ms? : Int) -> ChatResponse raise LLMErrorasync fn Client::completion(self : Client, request : CompletionRequest) -> CompletionResponse raise LLMErrorasync fn Client::create_fine_tune(self : Client, request : FineTuneRequest) -> FineTuneJob raise LLMErrorasync fn Client::embeddings(self : Client, request : EmbeddingRequest) -> EmbeddingResponse raise LLMErrorasync fn Client::generate_image(self : Client, request : ImageRequest) -> ImageResponse raise LLMErrorasync fn Client::moderations(self : Client, request : ModerationRequest) -> ModerationResponse raise LLMErrorpub struct ClientBuilder {
api_key : String
base_url : String
timeout_ms : Int
headers : Map[String, String]
auth : AuthScheme
}pub(all) struct CompletionRequest {
model : String
prompt : String
max_tokens : Int?
temperature : Double?
top_p : Double?
stop : Array[String]?
suffix : String?
}impl ToJson for CompletionRequestpub(all) struct CompletionResponse {
id : String
model : String
choices : Array[CompletionChoice]
usage : Usage?
} derive(Debug)impl FromJson for CompletionResponseimpl ToJson for EmbeddingInputpub(all) struct EmbeddingRequest {
model : String
input : EmbeddingInput
dimensions : Int?
user : String?
encoding_format : String?
}impl ToJson for EmbeddingRequestimpl FromJson for EmbeddingResponsepub(all) struct FileObject {
id : String
bytes : Int64
created_at : Int64
filename : String
purpose : String
} derive(Debug)impl FromJson for FileObjectpub(all) struct FineTuneJob {
id : String
model : String
status : String
training_file : String
fine_tuned_model : String?
} derive(Debug)impl FromJson for FineTuneJobpub(all) struct FineTuneRequest {
model : String
training_file : String
validation_file : String?
suffix : String?
n_epochs : Int?
}impl ToJson for FineTuneRequestpub(all) struct GeneratedImage {
url : String?
b64_json : String?
revised_prompt : String?
} derive(Debug)impl FromJson for GeneratedImagepub(all) struct ImageRequest {
prompt : String
model : String?
n : Int?
size : String?
quality : String?
response_format : String?
}impl ToJson for ImageRequestimpl FromJson for ImageResponselet msg = MessageBuilder::user()
.text("What is in these images?")
.image_url("https://a/1.png")
.image_url("https://a/2.png")
.build()fn MessageBuilder::image_base64(self : MessageBuilder, mime : String, data : String) -> MessageBuilderpub(all) struct Model {
id : String
object : String
created : Int64
owned_by : String
} derive(Debug)impl ToJson for ModerationRequestpub(all) struct ModerationResponse {
model : String
results : Array[ModerationResult]
} derive(Debug)impl FromJson for ModerationResponseimpl FromJson for ModerationResultpub(all) struct RequestLog {
path : String
request_body : String
status : Int
response_body : String
ok : Bool
}pub(all) struct ResponseRequest {
model : String
input : String
instructions : String?
max_output_tokens : Int?
temperature : Double?
}impl ToJson for ResponseRequestfn RetryPolicy::new(max_retries : Int, backoff : Backoff, respect_retry_after? : Bool) -> RetryPolicypub struct SSEParser {
event : String?
data : StringBuilder
id : String?
retry : Int?
has_data : Bool
}pub(all) enum Schema {
StrSchema(description~ : String?)
NumSchema(description~ : String?)
IntSchema(description~ : String?)
BoolSchema(description~ : String?)
EnumSchema(values~ : Array[String], description~ : String?)
ArraySchema(items~ : Schema, description~ : String?)
ObjectSchema(fields~ : Array[(String, Schema)], required~ : Array[String], description~ : String?)
}let params = Schema::object(
fields=[
("city", Schema::string(description="City name")),
("units", Schema::enum_(["celsius", "fahrenheit"])),
],
required=["city"],
)pub(all) struct SpeechRequest {
model : String
input : String
voice : String
response_format : String?
speed : Double?
}impl ToJson for SpeechRequestpub(all) struct StreamChunk {
content : String?
tool_calls : Array[ToolCallDelta]
finish_reason : String?
} derive(Eq, Debug)impl ToJson for ToolChoicepub(all) struct TranscriptionResponse {
text : String
language : String?
duration : Double?
} derive(Debug)impl FromJson for TranscriptionResponsepub struct UsageTracker {
calls : Int
prompt_tokens : Int
completion_tokens : Int
prompt_price_per_1k : Double
completion_price_per_1k : Double
}fn UsageTracker::new(prompt_price_per_1k? : Double, completion_price_per_1k? : Double) -> UsageTrackerfn estimate_cost(prompt_tokens : Int, completion_tokens : Int, prompt_price_per_1k~ : Double, completion_price_per_1k~ : Double) -> Doublefn estimate_tokens(text : String) -> Intfn estimate_tokens_by_words(text : String) -> Intfn is_valid_speech_format(fmt : String) -> Boolfn join_url(base : String, path : String) -> Stringfn parse_retry_after(value : String) -> Int?fn parse_sse_line(line : String) -> (String, String)?fn percent_encode(s : String) -> StringType-safe, OpenAI-compatible LLM client for MoonBit: chat completions, streaming (SSE), tool calling, and multimodal input.
Dependencies