Generating Text
Generate text with model aliases, prompt templates, conversation history, and tools.
Text Generation with generate()
The generate() function uses a session-admitted model alias to generate text.
The Rust tool-server manifest maps the alias to its provider, upstream model,
endpoint and credential source. Configure the matching client grant first;
see Text model bindings.
Examples that omit model require a configured session default and an
admitted route for its selected alias.
Linked repository examples require Kaya repository access and are not included in the standalone archive.
Basic Usage
let greeting = generate(
message: "Write a friendly greeting for Alice"
)
"{{greeting}}"Generates text based on your prompt.
With Message Parameter
let name = "Alice"
let poem = generate(
message: "Write a short haiku about {{name}}"
)The message parameter accepts template variables with {{}}.
With System Prompt
let translation = generate(
systemPrompt: "You are a professional French translator",
message: "Translate to French: {{englishText}}"
)Use systemPrompt to set the LLM's role or behavior.
Specifying Model
let story = generate(
message: "Write a short story about a robot",
model: "gemini-fast"
)gemini-fast is the logical binding in the configuration example. Choose
any alias your deployment binds and your session grants; upstream IDs and
provider prefixes do not create routes. See Supported Models
for connector examples and credential references.
Chat Context
// Silent generation (default) — result returned, chat history untouched
let analysis = generate(
message: "Analyze sentiment of: {{userInput}}"
)
// Opt in to chat history
let response1 = generate(
message: "What is your name?",
chat: true
)chat defaults to false: by default the message and response are NOT added to the conversation history. Pass chat: true when you want the exchange recorded so it affects future history-aware generations (or use chat(), which always records and sends history automatically).
Complete Example
let userName = "Alice"
let userAge = 30
let userInterests = ["coding", "hiking", "photography"]
let bio = generate(
systemPrompt: "You are a professional bio writer",
message: "Write a short bio for {{userName}}, age {{userAge}}, who enjoys {{userInterests | join: ', '}}",
model: "gemini-fast",
chat: true
)
"Generated bio: {{bio}}"Tool Calling
Exposing Kaya functions to the LLM as tools now has its own page — see Agents → Tool Calling.
Type coercion with as
LLM-powered type coercion (the as operator and its three tiers) now lives under AI Language Features → Type System.
Example Workflows
Tool-Assisted Data Processing
#description:"Extract structured data from text"
function extractData(text: string): json {
// Parsing logic
return {name: "...", date: "...", amount: 123}
}
#description:"Validate extracted data"
function validateData(data: json): boolean {
return data.name && data.date && data.amount > 0
}
#description:"Save data to database"
function saveToDatabase(data: json): boolean {
"Saving: {{data | json}}"
return true
}
let rawText = "Invoice for John Smith dated 2024-01-15 for $1,500"
let result = generate(
message: "Process this invoice: {{rawText}}",
tools: [
{"function": "extractData"},
{"function": "validateData"},
{"function": "saveToDatabase"}
]
)
"Processing complete: {{result}}"Best Practices
For generate()
- Be specific in prompts: Clear, detailed prompts produce better results
- Use system prompts: Set the LLM's role or constraints
- Choose the right model: Use cheaper models for simple tasks, powerful models for complex ones
- Manage chat context: generation is silent by default; pass
chat: trueonly when the exchange should join the conversation history - Include examples: Show the LLM what you want with few-shot examples in your prompt
For Tool Calling
- Clear descriptions: Write helpful
#descriptionannotations - Type your parameters: Use type annotations for validation
- Keep tools focused: Each tool should do one thing well
- Return structured data: Return objects, not plain strings when possible
- Handle errors gracefully: Validate inputs and return clear error messages
Testing AI Features
First attach the scripted Rust model provider and grant its model route.
Its mock <response> form supplies canned text without provider API calls;
the session still needs ordinary ToolMap authority:
// Mock text generation — everything after "mock " is the canned response
let result = generate(
message: "Test prompt",
model: "mock This is a mock response!"
)
// Multiple responses, separated by ";" — cycles through them per call
let answers = generate(
message: "Test prompt",
model: "mock First answer;Second answer"
)
// The scripted provider also parses tool(...) in a canned response
let toolResult = generate(
message: "Use the tool",
model: "mock tool(myTool,{\"param\":\"value\"});Tool executed!",
tools: [{"function": "myTool"}]
)Mock model formats:
- Text:
mock <response>(space-separated;;separates multiple responses that cycle per call) - Tool calling:
mock tool(toolName,{jsonArgs});final response(subsequent canned responses advance on later model calls) - Images: bind an alias such as
image-fixtureto the scripted Rust media provider; it returns deterministic, structurally valid PNGs without network access or credentials
Other Generation Guides
- Generating Images — prompts, image sizes, variations, and combined text/image workflows.
- Generating Speech — voices, delivery, audio formats, and speaker information.
- Generating Video — text-to-video and image-to-video workflows.
Next Steps
- Functions - Using functions as LLM tools
- Control Flow - Combining AI with loops and conditionals
- Standard Library Reference - Complete stdlib documentation
- Syntax Reference - Complete language specification