7.7.1. OPENAI-01 — Your First Chat
This tutorial introduces the openai module — a pure-daslang client for
OpenAI-compatible APIs (OpenAI, Ollama, OpenRouter, Kokoro, and any server that
speaks the same REST surface). It builds on dashv for HTTP and
daslib/json_boost for serialization.
The companion .das files are in tutorials/dasOPENAI/. They run against a
small local mock server (tutorial_openai_server.das) so no live LLM is
needed.
7.7.1.1. Setup
Require the section module you need and set options rtti:
options gen2
options rtti // REQUIRED — see below
require openai/openai_chat
options rtti is mandatory on every dasOPENAI script. Without it the
@optional / @rename field annotations are ignored, and requests
serialize every field (e.g. "n":0) — which real servers reject.
7.7.1.2. Constructing a client
openai_client takes a base URL (no trailing slash) and an optional API key:
// local server, no key
let client = openai_client("http://localhost:11434/v1")
// real OpenAI, key from the environment
let client = openai_client("https://api.openai.com/v1", get_env("OPENAI_API_KEY"))
7.7.1.3. The chat_text one-liner
chat_text is the simplest entry point: one user turn in, the assistant’s
text out (empty string on error).
let reply = chat_text(client, "gpt-4o-mini", "Say hello in one short sentence.")
print("{reply}\n")
7.7.1.4. The full chat() call
chat takes a ChatCompletionRequest and returns a ChatResult. When
ok is true, response holds the decoded reply — choices, the assistant
message, and token usage:
let req = ChatCompletionRequest(model = "gpt-4o-mini",
messages <- [ChatMessage(role = "user", content = "What is 2+2?")])
let res = chat(client, req)
if (res.ok) {
print("answer: {res.response.choices[0].message.content}\n")
print("tokens: {res.response.usage.total_tokens}\n")
} else {
print("error [{res.error.kind}/{res.error.status}]: {res.error.message}\n")
}
7.7.1.5. Handling errors
Every call returns a unified OpenAIError rather than crashing. kind is
one of "transport" (could not reach the server), "http", "api" (the
server returned an error body), or "decode" (the response did not parse).
7.7.1.6. Quick Reference
Function |
Description |
|---|---|
|
Build a client for any OpenAI-compatible server |
|
One user turn → assistant text (”” on error) |
|
Full request → |
|
The assistant |
|
Token accounting |
|
Error category and HTTP status |
See also
Full source: tutorials/dasOPENAI/01_first_chat.das
Next tutorial: OPENAI-02 — Conversations and Parameters