Skip to content

About

Build AI agents in Rust with the fluency of RustCFML

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

RustCFML Extension: AI

Language models from CFML. Chat, embeddings and tool-using agents with one fluent AI() API, against OpenAI, Anthropic, Gemini, Ollama, vLLM, LM Studio or any OpenAI-compatible server, with nothing to run beside your application.

Static Badge

ai = AI( "anthropic" );                               // ANTHROPIC_API_KEY from the environment

writeOutput( ai.model( "claude-opus-5-5" ).chat( "Say hello in French" ).text );

result = ai.model( "claude-opus-5-5" ).agent()
    .instructions( "Answer using the tools." )
    .tool( "weather", "Current weather for a city",
        { type = "object", properties = { city = { type = "string" } }, required = [ "city" ] },
        function( city ) { return weatherService.now( arguments.city ); } )
    .run( "Do I need an umbrella in Leeds?" );

writeOutput( result.text );          // the answer
writeDump( result.toolCalls );       // what it called, with what, and how long it took

Powered by Rig, the Rust library for building on language models. Rig does the talking to each provider: their wire formats, streaming, tool-call encoding and usage accounting. You never see a Rig type; you write CFML and get structs back.

Install

Take the file for your platform from the latest release and install it:

rustcfml ext install ai-0.1.0-linux-x86_64.rcx --user
rustcfml ext list

Current build (v0.1.0): macos-aarch64 · linux-x86_64 · linux-aarch64 · windows-x86_64

…or drop it into your application's extensions/ directory and check it into the project. Each file is 6.5–7.5 MB and carries one platform's library. Requires RustCFML v0.753.0 or newer; an older engine refuses to load it and says why.

New to .rcx extensions? The engine documentation covers installing one: --user vs --dir, checking load status with rustcfml ext list, and where extensions are found.

Check it loaded:

writeDump( aiVersion() );   // { extension, rig, formats, vendors, mcp, hooks }

What it is good at

  • Asking a model something from a page, a task or a scheduled job, and getting text, or a validated struct, back.
  • Agents that call your code. Tools are CFML closures or a component's methods. They run in your request, with your scopes, datasources and services, so an agent can look things up and do things the way the rest of your application does.
  • Extraction and classification with structured output: give a JSON schema, get a CFML struct that fits it.
  • Retrieval (RAG): embeddings for search, with MariaDB's VECTOR type or your own index, and documents passed to the model with citations.
  • Long-running work with a person in the loop. A run can stop for approval, be stored in your database, and continue days later in another request.
  • Local and private models. Ollama, vLLM, LM Studio and llama.cpp are first-class, and chat and embeddings can come from different servers.

Entry points

AI( providerOrRef [, options] )   // a provider
aiLoad( pathOrGlob [, options] )  // files read for a model's context, PDFs as text
aiVersion()                       // what is installed and which vendors it knows
isAIObject( value )               // true for AI, AIModel and AIAgent objects

AI() gives a provider, a provider gives models (.model( name )), and a model gives agents (.agent()).

Build providers once. Each AI() has its own HTTP connection pool, so create them in onApplicationStart and keep them in application scope. An agent built there can be run by any number of requests at once:

// Application.cfc
function onApplicationStart() {
    application.ai = AI( "anthropic", { timeout = 60000 } );
    application.support = application.ai.model( "claude-opus-5-5" ).agent()
        .instructions( "You answer customer questions about their orders." )
        .tools( "services.OrderTools" );
}

// any request
answer = application.support.run( form.question ).text;

Providers

providerOrRef is one of:

"openai-compatible" (or "custom", "local") any OpenAI-style server; needs baseUrl
"http://host:port/v1" the same, with the base URL inline
"openai", "anthropic", "gemini" / "google", "ollama", "openrouter", "groq", "mistral", "deepseek", "xai", "together", "azure", … a vendor by name (the full list is aiVersion().vendors)
"anthropic/claude-opus-5-5", "ollama/qwen3:4b" a vendor plus a default model
"zai/anthropic" a vendor in a named format, where it speaks more than one

Options:

option
apiKey the key; otherwise read from the vendor's own variable (OPENAI_API_KEY, ANTHROPIC_API_KEY, …)
baseUrl where to send requests; otherwise the vendor's variable (OLLAMA_API_BASE_URL, …), then its default
format openai, anthropic or gemini: the grammar to speak. A name that is not a known vendor is accepted only with a baseUrl and a format (a gateway of your own); without a format it is an error, never a guess
timeout ms for every call made through this provider (default 120000)
headers a struct of extra HTTP headers on every request
model the default model, for model() with no name and the shortcuts on AI
api OpenAI family: chat (Chat Completions) or responses. Official OpenAI defaults to responses, everything else to chat
anthropicVersion, anthropicBeta Anthropic's anthropic-version and anthropic-beta (string or array)

Keys never appear in info(), error messages or stored conversations. Prefer the environment over apiKey so they stay out of your code.

Any OpenAI-compatible server, for chat and embeddings. Point baseUrl at the path that ends just before /chat/completions:

ai = AI( "openai-compatible", { baseUrl = "http://localhost:8000/v1", apiKey = "optional" } );
ai.model( "meta-llama/Llama-3.1-8B-Instruct" ).chat( "…" );
ai.model( "BAAI/bge-small-en-v1.5" ).embed( "…" );

The key is optional (a server started without one gets no Authorization header at all), and so is usage on embeddings. Ollama, vLLM, LM Studio, llama.cpp, LiteLLM, Text Generation Inference and hosted gateways all fit.

Vendors by name know their own paths, authentication and quirks, and price the model where they can (usage.cost):

AI( "openai" ).model( "gpt-5.2" )                 // OPENAI_API_KEY; the Responses API
AI( "openai", { api = "chat" } ).model( "…" )     // Chat Completions instead
AI( "openrouter" ).model( "anthropic/claude-opus-5-5" )
AI( "ollama/qwen3:4b" ).chat( "…" )               // OLLAMA_API_BASE_URL or localhost:11434
AI( "mistral", { apiKey = key } ).model( "mistral-embed" ).embed( "…" )

Anthropic speaks the Messages API natively, so Claude keeps what only it has: documents with citations, prompt caching, extended thinking, and thinking replayed correctly on the next turn.

claude = AI( "anthropic" ).model( "claude-opus-5-5" );
r = claude.agent().cache( "short", [ "system" ] ).run( "What does the contract say about notice?", {
    documents = [ { text = contractText, title = "Contract", citations = true } ]
} );
for ( c in r.citations ) writeOutput( c.text & " ← " & c.sources[1].cited_text );

Anthropic requires a maxTokens on every request. Claude models known by name get a default; for any other name (a gateway's alias, say) set one with model( name, { maxTokens = 4096 } ), or you get ai.request.

Any Messages-format gateway works the same way: AI( "my-proxy", { format = "anthropic", baseUrl = "https://proxy.example.com" } ).

Gemini: AI( "gemini" ) (or "google") with GEMINI_API_KEY, for chat, tools, streaming and embeddings.

Anthropic has no embeddings API, and embed() there says so. Embed through an OpenAI-compatible or Gemini provider instead (Voyage, OpenAI, Ollama, …).

AI

Method Returns
model( [name] [, options] ) AIModel options are defaults for that model: system, temperature, maxTokens, dimensions, timeout, params, and the generation options below
info() struct { vendor, format, baseUrl, api, keySource, defaultModel, timeout }. keySource says where the key came from (options, a variable name, none), never the key
models() array the model ids the server lists
chat(…), embed(…), agent() shortcuts on the default model

AIModel

Method Returns
chat( promptOrMessages [, options] ) { text, usage, finishReason, model, toolCalls, reasoning, citations, message [, output] [, raw] }
embed( stringOrArray [, options] ) one array of floats for a string, an array of them for an array
transcribe( pathOrBinary [, options] ) { text, language, duration, segments, usage, model [, raw] }
generateImage( prompt [, options] ) { image, mediaType, bytes, usage, model [, raw] }
speak( text [, options] ) { audio, mediaType, bytes, usage, model [, raw] }
agent() AIAgent
name() string

Chat

chat() is one request to the model, with no loop:

m = AI( "openai" ).model( "gpt-5.2" );
r = m.chat( "Summarise this complaint in one sentence: #complaint#", { maxTokens = 200 } );
writeOutput( r.text );

promptOrMessages is a string, a message struct, or an array of messages (shape below). Options: system, temperature, maxTokens, params, tools (declarations only: calls come back in toolCalls and are not run), toolChoice, output (a JSON schema; output in the result is the parsed answer), documents, images, files, raw, timeout, and the generation options.

Generation options, accepted by model(), chat() and the agent: topP, seed, stop, reasoning (off, minimal, low, medium, high, xhigh, max or a token budget), cache (none, short, long), cachePoints ("tools", "system" or a message count), parallelToolCalls, and onUnsupported (error, the default, or ignore to drop an option the model cannot honour instead of failing). Each is mapped onto the provider's own spelling, so the same code works across providers.

params is the escape hatch. Its keys are merged into the request body as given, so anything a provider offers is reachable even when this API has no name for it:

m.chat( "…", { params = { top_k = 40, response_format = { type = "json_object" } } } );
agent.option( "thinking", { type = "enabled", budget_tokens = 4000 } );   // Anthropic
agent.option( "provider", { order = [ "groq" ] } );                       // OpenRouter routing

usage is { inputTokens, outputTokens, totalTokens, cachedInputTokens, cacheWriteTokens, reasoningTokens [, cost] }. What a provider does not report is zero; cost appears when the model's price is known.

Agents

An agent is a model in a loop: it calls tools, reads their results and goes on until it has an answer. AIAgent is a builder. Mutators return the agent, so calls chain. Terminals return data.

Mutator
instructions( text ) the system prompt
temperature( n ), maxTokens( n ), topP( n ), seed( n ), stop( stringOrArray )
reasoning( level ), cache( retention [, points] ) portable options, mapped per provider
maxTurns( n ) model calls per run (default 10)
timeout( ms ) the deadline for each run
option( name, value ), options( struct ) raw request-body keys (null removes one)
output( schema [, mode] ) structured output, below
tool( name, description, parameters [, fn] ) declare a tool, below
tools( componentOrPath [, { needsApproval } ] ) every tool-annotated method of a component
mcp( url [, { headers, prefix, timeout } ] ) every tool of an MCP server, below
toolChoice( choice ) auto, none, required, a tool name or an array of names
on( event, handler ) a lifecycle hook, below
off( [event] ) remove an event's hooks, or all of them
budget( { tokens, cost, toolCalls } ) limits on each run, below
Terminal Returns
run( input [, options] ) the result struct
stream( input, onDelta [, options] ) the same, after calling onDelta( text ) per fragment
resume( messages, input [, options] ) the same, continuing a stored conversation
step( messagesOrInput [, input [, options] ] ) one step of the loop, below
describe() the builder's configuration, tools and hooks included

Run options: tools (implementations, below), timeout, maxTurns, onMaxTurns (error or return), messages (history to start from), documents, images, files, hooks ({ event = handler }, after the agent's own, for this run only), budget, raw.

The result:

{
  text, output, outputMode,
  usage,                      // summed over every turn
  turnUsage: [ usage, … ],    // each model call's own
  turns,
  toolCalls: [ { id, name, args, result, isError, ms } ],
  messages,                   // the whole conversation, ready to store
  finishReason,               // the last turn's
  stopReason,                 // complete | approval | maxTurns | stopped | budget
  stopDetail,                 // why, for stopped and budget
  pending: [ { id, name, args } ],   // calls waiting for approval
  model, reasoning, citations [, raw]
}

Tools

A tool is declared with a name, a description and a JSON schema for its arguments, and implemented by a CFML closure or a component method. The model's arguments arrive by name, so function( city, days ) receives { "city": …, "days": … } as arguments.city and arguments.days. What it returns goes back to the model: a string as it is, anything else as JSON.

schema = { type = "object", properties = { city = { type = "string" } }, required = [ "city" ] };

// 1. Kept with the agent:
agent.tool( "weather", "Current weather", schema, function( city ) { return svc.now( arguments.city ); } );

// 2. Supplied at run time (overrides a kept one of the same name):
agent.tool( "weather", "Current weather", schema );
agent.run( "…", { tools = { weather = function( city ) { … } } } );

// 3. From a component:
agent.tools( new WeatherTools() );          // this instance, kept with the agent
agent.tools( "services.WeatherTools" );     // a fresh instance per run

A component's tools are its public functions with a tool annotation. The annotation's text is the description; tool=true uses the hint. Argument types become JSON types, required becomes required, and an argument's hint (or a doc-comment @name line) becomes its description:

component {
    /**
     * Current weather for a city.
     * @city The city name, e.g. Paris
     */
    public string function weather( required string city ) tool=true { … }

    public numeric function price( required string ticker ) tool="Latest price for a ticker" { … }
}

Tools run in the request that called run(). They see that request's request, session and application scopes, its locks and its datasources, exactly as if you had called them yourself. A closure also sees what it captured where it was created. So an agent built once in onApplicationStart and run by many requests does the right thing for each.

A tool that throws does not end the run. The model receives the error as the tool's result (Error: no data for Atlantis (weather.missing)) and can retry or explain, and toolCalls[n].isError is true. A call to a tool that does not exist is answered the same way. A declared tool with no implementation is refused before the run starts. An abort or a redirect inside a tool ends the request, as it would anywhere else.

The run's deadline covers the whole run, tools included. A slow tool is not interrupted mid-call, but the run fails with ai.timeout as soon as it returns past the deadline.

MCP servers

agent.mcp( url ) adds every tool of an MCP server (Streamable HTTP) to the agent. The connection opens on the first run and stays with the agent; prefix keeps their names apart from yours, and headers carries authentication.

agent.mcp( "https://mcp.example.com/mcp", { headers = { Authorization = "Bearer #token#" }, prefix = "crm_" } );

Structured output

person = { type = "object", properties = { name = { type = "string" }, age = { type = "integer" } }, required = [ "name", "age" ] };
r = model.agent().output( person ).run( "Who wrote the first published algorithm?" );
r.output.name;   // a CFML struct, already validated against the schema

The answer is validated against the schema. If it does not fit (or is not JSON at all), the model is told what was wrong and asked once more; if it still does not fit, the run raises ai.output with the problems and what the model said.

Servers differ in what they support, so there are four modes:

mode
auto (default) the provider's native JSON-schema mode; if the server refuses it, the same run switches to tool
native native only
tool a final_result tool whose arguments are the answer, with the call forced; works on any server with tool calling
json the schema in the prompt, plus response_format: json_object on OpenAI-format servers

result.outputMode says which one answered. Structured output combines with ordinary tools and with streaming. chat( …, { output = schema } ) is the one-shot form, without the retry.

Embeddings

v  = model.embed( "one text" );                         // [ 0.01, -0.2, … ]
vs = model.embed( [ "a", "b", "c" ] );                  // [ [ … ], [ … ], [ … ] ]
d  = model.embed( texts, { dimensions = 256, detail = true } );
// d.vectors, d.dimensions, d.count, d.usage, d.model

dimensions (per call, or as a model() option) asks the provider for that width, and the returned width is checked against it: a server that ignores the request raises ai.provider rather than handing back vectors that would not fit your index. Large batches are split into requests of 256 inputs and the usage summed.

Storing them in MariaDB 11.7+ is plain SQL:

queryExecute( "insert into doc_vectors ( id, embedding ) values ( :id, VEC_FromText( :v ) )",
    { id = doc.id, v = serializeJSON( model.embed( doc.text ) ) } );

hits = queryExecute( "select id from doc_vectors order by VEC_DISTANCE_COSINE( embedding, VEC_FromText( :q ) ) limit 5",
    { q = serializeJSON( model.embed( question ) ) } );

examples/support/MariaDbVectorStore.cfc is a complete store, and examples/rag.cfm puts it to work.

Streaming

r = agent.stream( "Tell me a story", function( text ) {
    writeOutput( text ); flush;
} );

onDelta gets each text fragment as it arrives, in your request, and the result is the same struct run() returns. Tools still run between turns. If onDelta returns false the run stops there and returns what it has (stopReason = "stopped"); if it throws, the run stops and that error is what you catch. Reasoning and tool-call arguments stream to hooks.

Hooks

on( event, handler ) runs your CFML at each point of the loop: to log, to enforce a policy, to change a request, or to stop. A handler gets the event as a struct, and a second struct that is shared by every hook of one run and fresh for the next (somewhere to keep notes). It returns nothing to carry on, or a struct of actions. Several handlers for one event run in order; a later key wins and a stop ends the round. A handler that throws ends the run with its error.

event when, and what it sees actions
start before the first model call: input, messages input (rewrite), stop
request before each model call: turn, messages, instructions, toolChoice, tools, usage so far for this call only: instructions, temperature, maxTokens, toolChoice, tools (narrow to these names), params, documents (context, added to the last user message), messages, model (a name on the same provider, or an AIModel); stop
response after each model call: turn, text, toolCalls, usage (this call's), finishReason, reasoning, model, maxTokens, raw, ms retry (a string: keep the reply and send it as feedback; true: discard and ask again; only for a turn without tool calls, and it uses a turn), stop
toolCall before each call runs: turn, id, name, args, resumed deny (or skip): answer with this reason, as an error; result: answer with this, as a success; args: run with these; approve: run a gated call now; pause: wait for a person (stopReason = "approval"); stop
toolResult after each call: turn, id, name, args, result, isError, ms result (what the model sees), isError, stop
invalidToolCall a call to a tool that does not exist: name, args, available repair (a real tool's name), deny, result, stop
turn after a turn's model call and its tools: turn, text, toolCalls, usage, totalUsage stop
toolCallStart, toolCallDelta, toolCallEnd a streamed tool call taking shape: index, name; delta, text so far, partial (the arguments parsed so far); id, args stop (before the call runs)
reasoningDelta streamed reasoning: text none
end the run finished or failed: stopReason, stopDetail, text, turns, usage, or error none

Every event also carries event, its name. Registering a streamed event makes run() stream, so it fires. A stop returns the run with stopReason = "stopped" and the reason in stopDetail; the conversation so far is in messages.

// allow-list one tool, cap the other
agent.on( "toolCall", function( call ) {
    if ( call.name == "search_web" ) return;
    if ( call.name == "transfer_funds" && call.args.amount <= 1000 ) return;
    return { deny = "denied by policy: transfers over $1000 need a person" };
} );

// force a tool on the first turn only
agent.on( "request", function( e ) { if ( e.turn == 1 ) return { toolChoice = "required" }; } );

// a cheap model gathers, a strong one answers
agent.on( "request", function( e ) { return { model = e.turn == 1 ? fast : strong }; } );

// log every model call
agent.on( "response", function( e ) {
    writeLog( file = "ai", text = "turn #e.turn#: #e.usage.inputTokens# in, #e.usage.outputTokens# out, #e.ms#ms" );
} );

Budgets

budget( { tokens, cost, toolCalls } ), or the budget run option, limits each run. Tokens and cost are checked before each model call, so the call that crosses the line is the overshoot; the run then returns with stopReason = "budget". Tool calls past toolCalls are answered with a message instead of running, so the model can finish with what it has.

Conversations, approvals and resuming

result.messages is plain data (structs, arrays and strings), so it can be stored anywhere (serializeJSON into a database, a session, a file) and continued in another request, or after a restart, with a freshly built agent:

// request 1
r = agent.run( "Plan my trip to Lisbon" );
saveConversation( id, serializeJSON( r.messages ) );

// request 2, days later
r = agent.resume( loadConversation( id ), "Make it three days, not two" );

resume() accepts the array or its JSON text. run( input, { messages } ) does the same starting from any history.

Approvals. Mark a tool needsApproval and the run stops before calling it, with stopReason = "approval" and the calls in pending. Nothing is held in memory while a person decides:

agent.tool( "refund", "Refund an order", schema, { handler = function( order, amount ) { … }, needsApproval = true } );
// or: agent.tools( new Billing(), { needsApproval = [ "refund" ] } )

r = agent.run( "Refund order 1042" );
if ( r.stopReason == "approval" ) {
    savePending( r.pending, serializeJSON( r.messages ) );   // show a person
}

// later, any request:
r = agent.resume( messages, { approve = [ callId ] } );               // runs it, then continues
r = agent.resume( messages, { deny = true, reason = "Over the limit." } );
r = agent.resume( messages, { approve = true, content = "Go ahead" } );   // approve all, and say something

needsApproval may also be a function of the call's arguments, by name like the tool itself, so only some calls wait: { handler = refund, needsApproval = function( order, amount ) { return arguments.amount > 100; } }. When a turn has a call that must wait, nothing of that turn runs until resume(). On resume every open call is settled before the model is asked again: a gated call neither approved nor denied is answered as declined, and an ordinary call from the same turn simply runs.

Stepping

step() runs one step of the loop and returns: a model call, or the tool calls that call asked for. The conversation is the state, so it can be stored between steps, for a queue worker or a page that shows each step:

s = agent.step( "What is 2 + 5?" );           // step = "model", pending = [ add(…) ]
s = agent.step( serializeJSON( s.messages ) ); // step = "tools": the calls ran
s = agent.step( s.messages );                  // step = "model", done = true

A step result adds step (model or tools) and done. Approval works as in resume(): step( messages, { approve = [ id ] } ).

Messages

{ role: "user", content: "…", documents: [ … ], images: [ … ] }
{ role: "assistant", content: "…", toolCalls: [ { id, name, args } ], native: "…" }
{ role: "tool", toolCallId: "…", name: "weather", content: "…", isError: false }
{ role: "system", content: "…" }

OpenAI-shaped messages (tool_calls, tool_call_id, content parts) are read too. native is the provider's own form of an assistant turn, kept so that what must be replayed exactly (Anthropic's signed thinking, Gemini's thought signatures) survives storage. Treat it as opaque; a message without it is replayed from the plain fields.

Files, documents and loading them

A user message can carry files, by URL or as base64: video, audio, PDFs, images. Each is sent as the provider's own kind of attachment, chosen by kind or mediaType; params go into it as the provider's own fields:

gemini = AI( "gemini" );
gemini.model( "gemini-2.5-pro" ).chat( "Summarise the video.", { files = [
    { url = "https://www.youtube.com/watch?v=emtHJIxLwEc", params = { videoMetadata = { fps = 0.2 } } }
] } );

aiLoad( pathOrGlob [, { ignoreErrors } ] ) reads files for retrieval or for documents: [ { path, name, text, pages } ], UTF-8 text as it is and a PDF's text page by page. A file that is neither is an error unless ignoreErrors. Relative paths resolve against the working directory, so use expandPath():

docs = aiLoad( expandPath( "/policies/*.pdf" ) );
r = claude.agent().run( "What is our refund window?", {
    documents = docs.map( function( d ) { return { text = d.text, title = d.name, citations = true }; } )
} );

Transcription, images and speech

On OpenAI-compatible and Gemini providers (Anthropic has none):

openai = AI( "openai" );
t = openai.model( "whisper-1" ).transcribe( expandPath( "meeting.mp3" ), { language = "en" } );
img = openai.model( "gpt-image-1" ).generateImage( "a flat banana icon", { size = "1024x1024" } );
fileWrite( expandPath( "banana.png" ), img.image );
s = openai.model( "tts-1" ).speak( "Have a wonderful day!", { voice = "alloy" } );

gemini.model( "gemini-3.1-flash-image" ).generateImage( "…", { width = 16, height = 9 } );  // aspect ratio
gemini.model( "gemini-3.8-flash-lite-tts" ).speak( "…", { voice = "Kore" } );

transcribe() takes a path or binary, plus filename, language, prompt, temperature. generateImage() takes width/height or size, and images (references to edit or compose from). speak() takes voice and speed. All three take params, timeout and raw. Images and audio come back as binary, with their mediaType read from the bytes.

Errors

Every failure is a catchable CFML error with a type:

type
ai.timeout the deadline passed; the request is abandoned, never left running
ai.connection nothing answered: wrong base URL, refused, DNS, TLS. The message names the URL
ai.auth 401/403, or no key where one is required (the message names the variables tried)
ai.rateLimit 429
ai.provider any other error reply; the message carries the status and the provider's body
ai.request the request could not be built, or the model cannot honour an option
ai.config the provider was configured wrongly (unknown vendor, missing baseUrl)
ai.output structured output still invalid after the retry
ai.maxTurns the turn cap; pass onMaxTurns = "return" to get the conversation instead
Expression a wrong argument to one of these methods
try {
    r = agent.run( question );
} catch ( "ai.rateLimit" e ) {
    // back off and queue it
} catch ( "ai.timeout" e ) {
    // tell the user it is taking too long
}

Examples

examples/ has 61 runnable files: every example in Rig's own repository, ported to CFML. They cover prompt chaining, routing, orchestrators, evaluator-optimiser loops, debates, extraction, RAG with an in-memory or MariaDB VECTOR index, human-in-the-loop and durable approvals, hooks, budgets, stepping, MCP, streaming and media. They read their provider from AI_* environment variables:

AI_BASE_URL=http://localhost:11434/v1 AI_MODEL=qwen3:4b rustcfml examples/agent_with_tools.cfm
AI_PROVIDER=anthropic AI_MODEL=claude-opus-5-5 rustcfml examples/agent_with_approval_policy.cfm

Notes and limits

  • What has run against real providers. Every feature is tested against a fake provider that speaks OpenAI, Anthropic, Gemini and MCP, and the chat, tool and agent examples have run against a live OpenAI-compatible server. Not yet run against a real provider: OpenAI's Responses API (the default for AI( "openai" ); api = "chat" uses Chat Completions), images in messages, the reasoning and cache options, transcription, image and speech generation, and files. They are expected to work; reports welcome.
  • AWS Bedrock and Google Vertex AI are not built in. Reach them through an OpenAI-compatible gateway such as LiteLLM.
  • run() and chat() hold the calling request until they finish, so put long runs in a task or cfthread rather than a page. Concurrent requests do not queue behind each other's model calls.
  • Build providers once, in onApplicationStart, rather than per request: each AI() has its own connection pool.
  • onDelta receives answer text only; reasoning and tool-argument fragments go to the reasoningDelta and toolCallDelta hooks.
  • A tool that throws becomes a tool error the model reads, and the run goes on. A needsApproval check, a hook or an onDelta that throws ends the run with its own error.
  • API keys are never written to info(), error messages or messages.

Building from source

rustcfml ext build .
rustcfml ext install ai-0.1.0.rcx --user
./tests/run.sh

It needs a RustCFML checkout beside this one. See docs/development.md for the layout, the tests, CI, releases and how a run works inside.

Licence

This extension's own code is MIT: see LICENSE.

It is a thin layer over other people's work. Rig (© Playgrounds Analytics Inc., MIT) does the talking to models, and RustCFML (© the RustCFML Team, MIT) is the engine it plugs into.

A built .rcx statically links Rig and the crates it depends on, so it carries their notice obligations. THIRD-PARTY.txt reproduces every one of them, and is packaged inside the archive together with NOTICE and the licence, so the attribution travels with the library.

About

Build AI agents in Rust with the fluency of RustCFML

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages