AI providers and tool calling
The core framework has no HTTP client for AI and never needs a model to run. A provider (a hosted
service or a local server) is an addon that implements the traits of erp_sdk::ai:
ModelProvider: text completion, streaming and token counting withCompletionRequestandCompletionResponse. Every completion and embedding call reports aUsageRecord(tokens, cost, latency).EmbeddingProvider: vector embeddings.ToolModelProvider: tool turns, on top ofModelProvider. A provider that cannot call tools does not implement it, so code that needs tool calling does not compile against it.
Design: docs/design/m3-ai0-iface.md (text and embeddings) and docs/design/ai1-sdk-tools.md
(tool calling); decision record ADR 0188.
Looking up readable models
Section titled “Looking up readable models”Call erp_addon_ai_base::catalog::find_models_spec() for the static provider tool declaration.
Pass the caller’s existing transaction and a typed ToolCall to catalog::find_models.
The sole argument is query, a string. An empty query looks across all concrete installed models.
Names and bounded descriptions match case-insensitively. The result carries the original call ID
and labelled JSON data containing models in technical-name order and a has_more flag.
Each row contains name, description and description_truncated. Narrow the query when
has_more is true. Hidden models are omitted before deciding whether more results exist.
The tool requires an ordinary user and a current company. A future HTTP turn handler must also establish an interactive session and verify CSRF. The native tool does not open an endpoint. No fields, business records or record counts are returned.
The database’s technical System Parameters govern each search:
| Parameter | Default | Allowed range |
|---|---|---|
ai_base.catalog_query_bytes | 256 | 1–1024 UTF-8 bytes |
ai_base.catalog_result_rows | 20 | 1–80 readable models |
ai_base.catalog_help_chars | 160 | 1–2000 Unicode scalar values |
ai_base.catalog_result_bytes | 32768 | 4096–65536 labelled JSON bytes |
If the first model’s description alone would exhaust the byte budget, the result keeps its technical name and marks its description as truncated.
Reading selected records
Section titled “Reading selected records”The native erp_cli::assistant_read::search_records entry accepts the configured RPC service,
Auth service, browser session secret, selected company, and a typed tool call. It executes
web_search_read against the target model using that session. The host owns the trusted company
selection. The provider cannot supply a session, context or company override.
For example, {"model":"purchase.order","domain":[["state","=","draft"]],"fields":["name","state"],"limit":5,"order":"id desc"}
asks for five recent draft orders visible in the chosen company. The required domain is a
nonempty AND list of direct scalar comparisons. Operators are =, !=, >, <, >=,
<= and ilike. Dates use the ordinary RPC field format. Specify one simple sort field and
optional asc or desc. Direct stored scalar fields are supported. Relation paths, computed
and delegated values, secret, binary and group-masked fields are excluded. A refused filter
or sort field fails the call. The explicit projection omits ineligible fields and requires at
least one readable field. Each output row carries an ID. The truncated flag covers count,
text or payload limits. When the first complete row exceeds the byte limit only its ID is returned.
Technical System Parameters under ai_base.search_ set the admissible maximum rows (20; 1–80),
fields (16; 1–64), conditions (12; 1–64), operand bytes (256; 1–2048), characters per returned
string (512; 1–2000) and labelled result bytes (32768; 4096–65536). Reads follow the database’s
installed record rules and the RPC service’s read-audit policy.
Tool turns
Section titled “Tool turns”A tool turn is a ToolTurnRequest: a model name, the conversation as TurnMessages and the
ToolSpecs the model may call. Each message is a role (TurnRole::System, User, Assistant) and a
list of ContentParts:
| Part | Who sends it | What it is |
|---|---|---|
Instruction | system | text built from &'static str pieces and typed values |
UserText | user | what the user typed |
Data (LabelledData) | user side | a value a tool read, labelled with its DataSource (tool, model, record ids) |
ToolResult | user side | the answer to one tool call, tied to it by id, holding LabelledData |
ToolCall | assistant | a call as the model produced it: id, name and arguments, kept as received |
AssistantText | assistant | the model’s own prose, resent with the history (any String) |
TurnMessage::new refuses a part its role may not carry and an empty message.
ToolTurnRequest::new refuses two tools with one name, a repeated tool call id, a tool result for a
call no earlier assistant message made, and a second result for one call. A provider answer is
a ToolTurnResponse with assistant parts only, and finish_reason is FinishReason::ToolUse when the
model waits for tool results.
Instruction has no conversion from a runtime String, no parsing, no deserialization and no
default; LabelledData has none from any string, and its only constructor is
LabelledData::new(source, value). Compile-fail cases and a compile-time probe pin this
(SPEC-AIA-001, partial). The types do not close every path. Three are review rules for ai_base:
- A leaked
String(String::leak) is a&'static strand passesInstruction::from_static. Only string literals go there. - Any crate can call
LabelledData::new. Only the tool executor builds it. ContentPart::AssistantTextholds anyString. Only provider responses supply assistant parts.
use erp_sdk::ai::{DataSource, Instruction, LabelledData, ToolName};
let instruction = Instruction::from_static("You answer questions about ") .then_integer(3) .then_static(" records; read only: ") .then_flag(true);assert_eq!(instruction.render(), "You answer questions about 3 records; read only: true");
let source = DataSource::new(ToolName::new("search_read")?, Some("res.partner".to_owned()), vec![7, 9])?;let data = LabelledData::new(source, serde_json::json!({"name": "Azure Interior"}));assert_eq!(data.source().ids(), &[7, 9]);Limits
Section titled “Limits”| Value | Rule |
|---|---|
ToolName | 1 to 64 characters from A-Z a-z 0-9 _ - (the common subset of the hosted providers’ rules) |
ToolSpec description | not blank, at most 1,024 characters |
ToolSpec input schema | a JSON object whose top-level "type" is "object" |
ToolCallId | 1 to 256 bytes, no control or Unicode format (Cf) characters |
ToolCall name | at most 256 bytes; it need not be a valid ToolName, so the executor can answer “unknown tool” |
DataSource model | not empty when present |
Each refusal is a ToolTypeError variant naming the value or position. An adapter that cannot
represent a provider’s answer (an empty id, an oversized name) returns
ProviderError::InvalidResponse, never a guessed value.
Implementing a provider
Section titled “Implementing a provider”Implement ModelProvider first, then ToolModelProvider::complete_turn.
For the configured Anthropic Messages or OpenAI-compatible Chat Completions route, create
one encoder with ConfiguredRoute::request_encoder() at the start of the assistant turn and
reuse it for each encode(&request). It uses the route’s exact provider family and model.
It builds a JSON body without credentials, and returns ProviderError::InvalidRequest for
histories or options it cannot represent.
Instruction renders in the system channel. A ToolResult carries its call ID and
labelled JSON in the provider’s tool-result block or tool-role message. Unpaired
LabelledData uses a separate user-role text block with a random per-turn delimiter since
it has no call ID. Tool results must immediately follow their assistant call batch, before
additional user text. Anthropic requires a positive max_tokens and leading instructions.
OpenAI-compatible schemas must already describe closed objects with all properties required.
Declare optional inputs as required nullable values. The encoder preserves schema semantics
and refuses unsupported keywords. The route applies ai.max_request_bytes before building
the JSON and checks the final compact body size. Both providers share the same structural
entry and nesting limits.
Call decode_response(&body) on the same encoder with the complete JSON body
from a successful non-streaming exchange. The decoder preserves assistant text and
tool calls as typed parts. It retains the returned model and validated token counts for
metering. Unsupported provider blocks, malformed JSON, inconsistent tool finish reasons
and unusable usage records return ProviderError::InvalidResponse without echoing the
response. Duplicate tool argument keys are detected directly from the response JSON before
conversion to SDK values. JSON bodies are capped at 1 MiB. A transport must separately enforce its read limit
before buffering any response.
Provider transport, retry and streaming belong to the provider transport implementation. A decoded tool call still needs normal executor validation, access checks and any required user confirmation.
Testing with the scripted provider
Section titled “Testing with the scripted provider”erp_testkit::ai::ScriptedModelProvider answers each tool turn with the next queued reply and
records every request:
use erp_sdk::ai::ToolModelProvider;use erp_testkit::ai::{ScriptedModelProvider, ScriptedReply};
let provider = ScriptedModelProvider::new("scripted-llm");provider.push_reply(ScriptedReply::tool_call("call_01", "search_read", serde_json::json!({"model": "res.partner"}))?);provider.push_reply(ScriptedReply::text("There are 5 customers.")?);// provider.complete_turn(&request).await? returns the replies in order;// provider.recorded_requests() returns the requests it received.push_error queues a ProviderError. When the script runs out, complete_turn returns
ProviderError::Backend naming the call number, never a default answer. Text-only requests
(complete, stream, count_tokens) behave like MockModelProvider, which echoes the prompt. The
scripted name and arguments are kept as given, so a test can script a call to a tool that does not
exist. The round trip is tested in crates/erp-testkit/tests/ai_tools.rs (SPEC-AIA-002).
The native ai_base addon can now send a typed non-streaming turn to a node-bound Anthropic
or OpenAI-compatible endpoint. The configured route controls the provider and allowed model.
See native HTTP exchange and limits.