Dependencies
moon add tonyfettes/openaifn main {
let client = @openai.Client::new()
let messages = [
@openai.system_message(content="You are a helpful assistant."),
@openai.user_message(content="Hello! How are you?"),
]
let response = client.chat.completions.create(
model="gpt-4",
messages~,
)
match response.choices {
[choice, ..] =>
match choice.message.content {
Some(content) => println(content)
None => println("No response received")
}
[] => println("No choices in response")
}
}fn main {
let client = @openai.Client::new()
let messages = [
@openai.system_message(content="You are a helpful assistant."),
@openai.user_message(
content="Can you please tell me what's the sum of 5 and 10 by calling the adder tool?",
),
]
// Define a tool for adding numbers
let tools = [
@openai.tool(
name="adder",
description="Adds two numbers",
parameters={
"type": "object",
"properties": {
"a": { "type": "number" },
"b": { "type": "number" }
},
"required": ["a", "b"],
}
),
]
let response = client.chat.completions.create(
model="gpt-4",
messages~,
tools~,
)
// Process the response and handle tool calls
let choices = response.choices
if choices.length() > 0 {
let choice = choices[0]
let message = choice.message
// Add the assistant's message to conversation
messages.push(message.to_param())
// Handle tool calls
let tool_calls = message.tool_calls
for tool_call in tool_calls {
if tool_call.function.name == "adder" {
let result = match @json.parse(tool_call.function.arguments) {
{ "a": Number(a, ..), "b": Number(b, ..), .. } => "Result: \{a + b}"
_ => "Invalid arguments"
}
// Add tool response to conversation
messages.push(
@openai.tool_message(content=result, tool_call_id=tool_call.id),
)
}
}
// Get final response
let final_response = client.chat.completions.create(
model="gpt-4",
messages~,
tools~,
)
match final_response.choices[0].message.content {
Some(content) => println(content)
None => println("No final response")
}
}
}// Explicit API key
let client = @openai.Client::new(api_key="your-api-key-here")
// Using environment variable (recommended)
let client = @openai.Client::new()// OpenRouter
let client = @openai.Client::new(base_url="https://openrouter.ai/api/v1")
// Azure OpenAI
let client = @openai.Client::new(base_url="https://your-resource.openai.azure.com/openai/deployments/your-deployment")
// Local server
let client = @openai.Client::new(base_url="http://localhost:8000/v1")pub(open) trait HttpClient {
async fetch(self : Self, url~ : String, method_~ : HttpMethod, headers~ : Map[String, String], body~ : String) -> Response
}pub struct ChatCompletion {
id : String
choices : Array[ChatCompletionChoice]
created : Int
model : String
usage : CompletionUsage?
system_fingerprint : String?
service_tier : ChatCompletionServiceTier?
}pub struct ChatCompletionAssistantMessageParam {
content : String?
name : String?
tool_calls : Array[ChatCompletionMessageToolCall]
function_call : ChatCompletionMessageFunctionCall?
}pub struct ChatCompletionAudio {
id : String?
}pub struct ChatCompletionAudioParam {
voice : String
format : String
}pub struct ChatCompletionChoice {
finish_reason : ChatCompletionChoiceFinishReason
index : Int
message : ChatCompletionMessage
logprobs : ChatCompletionChoiceLogprobs?
}pub enum ChatCompletionChoiceFinishReason {
Stop
Length
ToolCalls
ContentFilter
FunctionCall
}pub struct ChatCompletionChoiceLogprobs {
content : Array[ChatCompletionTokenLogprob]?
refusal : Array[ChatCompletionTokenLogprob]?
}pub struct ChatCompletionChunk {
id : String
choices : Array[ChatCompletionChunkChoice]
created : Int
model : String
usage : CompletionUsage?
system_fingerprint : String?
service_tier : ChatCompletionServiceTier?
}pub struct ChatCompletionChunkChoice {
index : Int
delta : ChatCompletionChunkChoiceDelta
finish_reason : ChatCompletionChoiceFinishReason?
}pub struct ChatCompletionChunkChoiceDelta {
content : String?
role : ChatCompletionRole?
tool_calls : Array[ChatCompletionChunkChoiceDeltaToolCall]?
}pub struct ChatCompletionChunkChoiceDeltaToolCall {
index : Int
id : String?
function : ChatCompletionChunkChoiceDeltaToolCallFunction
}pub struct ChatCompletionChunkChoiceDeltaToolCallFunction {
arguments : String?
name : String?
}pub enum ChatCompletionContentPart {
Text(ChatCompletionContentPartText)
ImageURL(ChatCompletionContentPartImage)
InputAudio(ChatCompletionContentPartInputAudio)
File(ChatCompletionContentPartFile)
}pub struct ChatCompletionContentPartFileFile {
file_id : String
}pub struct ChatCompletionContentPartImageImageURL {
url : String
detail : String?
}pub struct ChatCompletionContentPartInputAudio {
input_audio : ChatCompletionContentPartInputAudioInputAudio
}pub struct ChatCompletionContentPartInputAudioInputAudio {
data : String
format : String
}pub struct ChatCompletionContentPartText {
text : String
}pub struct ChatCompletionMessage {
content : String?
refusal : String?
tool_calls : Array[ChatCompletionMessageToolCall]
annotations : Array[ChatCompletionMessageAnnotation]
audio : ChatCompletionAudio?
function_call : ChatCompletionMessageFunctionCall?
}pub struct ChatCompletionMessageAnnotation {
type_ : String
text : String
file_citation : ChatCompletionMessageAnnotationFileCitation?
file_path : ChatCompletionMessageAnnotationFilePath?
start_index : Int
end_index : Int
}pub struct ChatCompletionMessageAnnotationFileCitation {
file_id : String
quote : String
}pub struct ChatCompletionMessageAnnotationFilePath {
file_id : String
}pub struct ChatCompletionMessageFunctionCall {
arguments : String
name : String
}pub enum ChatCompletionMessageParam {
System(ChatCompletionSystemMessageParam)
User(ChatCompletionUserMessageParam)
Assistant(ChatCompletionAssistantMessageParam)
Tool(ChatCompletionToolMessageParam)
}pub struct ChatCompletionPredictionContent {
type_ : String
content : String
}pub enum ChatCompletionResponseFormat {
JsonObject
JsonSchema(ChatCompletionResponseFormatJsonSchema)
Text
}pub enum ChatCompletionServiceTier {
Auto
Default
Flex
Scale
Priority
}pub struct ChatCompletionStreamOptions {
include_usage : Bool?
}pub struct ChatCompletionSystemMessageParam {
content : String
name : String?
}pub struct ChatCompletionTokenLogprob {
token : String
logprob : Double
bytes : Array[Int]?
top_logprobs : Array[ChatCompletionTopLogprob]
}pub struct ChatCompletionToolMessageParam {
content : String
tool_call_id : String
}pub struct ChatCompletionUserMessageParam {
content : String
name : String?
}pub struct ChatCompletionWebSearchOptions {
max_results : Int?
}pub struct ChatCompletionsService {
// private fields
}async fn ChatCompletionsService::create(self : ChatCompletionsService, messages~ : Array[ChatCompletionMessageParam], model~ : String, tools? : Array[ChatCompletionToolParam], frequency_penalty? : Double, logprobs? : Bool, max_completion_tokens? : Int, max_tokens? : Int, n? : Int, presence_penalty? : Double, seed? : Int, store? : Bool, temperature? : Double, top_logprobs? : Int, top_p? : Double, parallel_tool_calls? : Bool, prompt_cache_key? : String, safety_identifier? : String, user? : String, audio? : ChatCompletionAudioParam, logit_bias? : Map[String, Int], metadata? : Map[String, String], modalities? : Array[String], reasoning_effort? : ReasoningEffort, service_tier? : ChatCompletionServiceTier, stop? : ChatCompletionStopParam, stream_options? : ChatCompletionStreamOptions, verbosity? : Verbosity, prediction? : ChatCompletionPredictionContent, response_format? : ChatCompletionResponseFormat, web_search_options? : ChatCompletionWebSearchOptions) -> ChatCompletionasync fn ChatCompletionsService::stream(self : ChatCompletionsService, messages~ : Array[ChatCompletionMessageParam], model~ : String, tools? : Array[ChatCompletionToolParam]) -> Reader[ChatCompletionChunk]pub struct CompletionUsage {
completion_tokens : Int
prompt_tokens : Int
total_tokens : Int
}type Reader[T]pub enum ReasoningEffort {
Minimal
Low
Medium
High
}fn assistant_message(content? : String, tool_calls? : Array[ChatCompletionMessageToolCall], name? : String) -> ChatCompletionMessageParamfn tool(name~ : String, description~ : String, parameters~ : Map[String, Json], strict? : Bool) -> ChatCompletionToolParamDependencies