|
// retoor <retoor@molodetz.nl>
|
|
|
|
import "http" for Http
|
|
import "json" for Json
|
|
import "env" for Environment
|
|
|
|
var apiKey = Environment.get("OPENROUTER_API_KEY")
|
|
if (apiKey == null || apiKey.count == 0) {
|
|
System.print("Error: OPENROUTER_API_KEY environment variable not set")
|
|
Fiber.abort("Missing API key")
|
|
}
|
|
|
|
System.print("=== OpenRouter API Demo ===\n")
|
|
|
|
var model = "x-ai/grok-code-fast-1"
|
|
var prompt = "What is 2 + 2? Reply with just the number."
|
|
|
|
System.print("Model: %(model)")
|
|
System.print("Prompt: %(prompt)")
|
|
System.print("")
|
|
|
|
var requestBody = {
|
|
"model": model,
|
|
"messages": [
|
|
{"role": "user", "content": prompt}
|
|
]
|
|
}
|
|
|
|
var headers = {
|
|
"Authorization": "Bearer " + apiKey,
|
|
"Content-Type": "application/json"
|
|
}
|
|
|
|
System.print("Sending request to OpenRouter...")
|
|
|
|
var response = Http.post("https://openrouter.ai/api/v1/chat/completions", requestBody, headers)
|
|
|
|
System.print("Status: %(response.statusCode)")
|
|
System.print("")
|
|
|
|
if (response.ok) {
|
|
let text = response.body
|
|
if(text.startsWith("```")){
|
|
text = text.trim("```")
|
|
text = text.trim("json")
|
|
text = text.trim("\n")
|
|
|
|
}
|
|
System.print(text)
|
|
var data = Json.parse(text)
|
|
if (data != null && data["choices"] != null && data["choices"].count > 0) {
|
|
var message = data["choices"][0]["message"]
|
|
if (message != null && message["content"] != null) {
|
|
System.print("Response: %(message["content"])")
|
|
}
|
|
}
|
|
System.print("\nModel used: %(data["model"])")
|
|
if (data["usage"] != null) {
|
|
System.print("Tokens - prompt: %(data["usage"]["prompt_tokens"]), completion: %(data["usage"]["completion_tokens"])")
|
|
}
|
|
} else {
|
|
System.print("Error: %(response.body)")
|
|
}
|