Lab
The connection layer for AI: a lab points at one LLM provider — its endpoint, protocol, and credentials — and hosts the brain models that every agent, evaluator, and intelligence element in a circle resolves against.
Working with it
Opening a Lab drills into its contents on the canvas rather than opening a dedicated workbench.
How it appears
The same element type rendered as a definition, a circle instance, and a live workspace card.
When to use / not
When to use
- Bringing your own API key — wrap an api-token in a lab so your circle's agents bill against your provider account, not the platform's.
- Connecting a self-hosted or third-party endpoint (Ollama, vLLM, Groq, Mistral) that speaks the OpenAI-compatible protocol.
- Overriding a platform provider in your circle — a same-provider lab takes priority in brain resolution, so your key wins over the shared one.
- Exposing your models as an OpenAI-compatible API for an external client to call directly.
When not to use
- Picking a specific model for an agent — that is a brain (the lab's child); the agent names a brain and the runtime resolves which lab owns it.
- Just using a major provider on the defaults — the platform ships pre-configured labs for Anthropic, OpenAI, Gemini, and more; only create a lab to bring a key or a private endpoint.
- Storing the API key itself — keep secrets in an api-token element and point auth.credential_ref at it; the lab never holds the raw key.
Topology
Created from the library and placed inside an app or circle. It is a top-level building block you compose with other elements.
Properties
protocolstring- API protocol. Most providers are OpenAI-compatible.
base_urlstring- Base URL of the provider API (e.g. https://api.openai.com/v1)
authobject- Authentication configuration
modelstring- Default LLM model identifier (e.g. gpt-4o, claude-sonnet-4-6)
max_tokensinteger- Default maximum tokens per response
temperaturenumber- Default sampling temperature (0 = deterministic, 2 = creative)
priorityinteger- Routing priority — lower numbers preferred when multiple labs offer the same brain ID
model_prefixesarray- Model ID prefixes that auto-route to this lab (e.g. 'claude-' routes to Anthropic)
Capabilities
Defined for this element
- Storage
- Crypto
- Observe
Operations
- activityGET
- attachmentsGET
- batch_statsGET
- categorizePOST
- chatPOST
- composePOST
- contextGET
- createPOST
- deleteDELETE
- disablePOST
- enablePOST
- export_bundleGET
- generatePOST
- getGET
- healthGET
- import_bundlePOST
- intentionGET
- invokePOST
- list-brainsGET
- promotePOST
- readmeGET
- readme_updatePOST
- remove-modifierPOST
- restorePOST
- schemaGET
- set-api-keyPOST
- sourceGET
- source_branchesGET
- source_promotePOST
- source_repairPOST
- source_statusGET
- source_validatePOST
- statsGET
- test-brainPOST
- treeGET
- updatePATCH
- update_metaPATCH
- versionGET
Ports
Inputs
- resolverequest
- connectionrequest
Composition
Operation examples
set-api-key
Response
stored: truelist-brains
Response
brains: []
count: 0
lab_id: 00000000-0000-0000-0000-000000000000health
Response
status: configured
protocol: openai
base_url: https://api.example
api_key_set: true
gateway_available: true
element_id: 00000000-0000-0000-0000-000000000000Errors / when it fails
- Set auth.credential_ref to an API token element, or provide auth.env_vars for platform-managed keys
Validation rules
- No base_url configured — set it via the configure operation before making requests
- No authentication configured — most providers require an API key
Lab (lab)
Category: intelligence | Form: | Symbol: Lb
LLM provider that contains brains (models) for AI-powered elements
A Lab is a connection to an AI provider (Anthropic, OpenAI, Mistral, etc.) that contains brains (models). Platform labs come pre-configured with tested brains. Create your own lab to bring your own API key, connect to a self-hosted endpoint, or add custom models. Agents pick a brain — the runtime resolves which lab owns it through the cascade: element-level → circle-level → platform labs.
Guide
An LLM provider connection (Anthropic, OpenAI, Mistral, Bedrock) that hosts brain models
What It Does
A Lab represents a connection to an LLM provider. It holds the API endpoint, authentication credentials, protocol details, and parameter constraints for all models (brains) within it. Labs are compound elements — they contain Brain child elements, each representing a specific model.
The platform comes pre-configured with labs for all major providers (Anthropic, OpenAI, Gemini, Mistral, Groq, Bedrock, Replicate, and more). Users create custom labs to bring their own API keys, connect to self-hosted endpoints (Ollama, vLLM), or add private models.
Element Definition
| Property | Value |
|---|---|
| Type | lab |
| Category | intelligence |
| Form | compound |
| Symbol | Lb / #7C3AED |
Properties
| Field | Type | Default | Description |
|---|---|---|---|
protocol | enum | — | Required. API protocol: openai, anthropic, bedrock, replicate |
base_url | string | — | Required. Provider API endpoint (e.g., https://api.anthropic.com) |
auth.type | enum | bearer | Authentication method: bearer, api_key_header, none |
auth.header | string | Authorization | HTTP header name for credentials |
auth.credential_ref | string | — | Reference to an api-token element (for user labs) |
auth.env_vars | array | [] | Environment variable names to check (for platform labs) |
parameter_constraints | object | {} | Lab-level defaults for temperature, top_p, top_k, penalties |
quirks | object | {} | Provider-specific behavior (see below) |
priority | integer | 500 | Routing priority (0-1000, lower = preferred) |
model_prefixes | array | [] | Model ID prefixes for auto-routing (e.g., ["claude-"]) |
Topology
- Lives in: an
intelligencerepository element - Contains:
brainchild elements - Uses:
api-tokenelements (for credential storage) - Accepts modifiers:
rate-limit,auth-policy,audit
Quick Start
Creating a Custom Lab (Bring Your Own Key)
First, create an api-token element to store your API key securely:
POST /api/{circle}/{project}/
Content-Type: application/json
{
"element_type": "api-token",
"slug": "my-openai-key",
"name": "OpenAI API Key",
"spec": { "token": "sk-..." }
}
Then create the lab:
POST /api/{circle}/{intelligence-repo}/
Content-Type: application/json
{
"element_type": "lab",
"slug": "my-openai",
"name": "My OpenAI",
"spec": {
"protocol": "openai",
"base_url": "https://api.openai.com/v1",
"auth": {
"type": "bearer",
"credential_ref": "my-openai-key"
},
"model_prefixes": ["gpt-"]
}
}
Connecting to a Self-Hosted Endpoint
POST /api/{circle}/{intelligence-repo}/
Content-Type: application/json
{
"element_type": "lab",
"slug": "local-ollama",
"name": "Local Ollama",
"spec": {
"protocol": "openai",
"base_url": "http://localhost:11434/v1",
"auth": { "type": "none" }
}
}
Operations
| Operation | Method | Auth | Description |
|---|---|---|---|
list-brains | GET | viewer | List all brain child elements with capabilities and pricing |
health | GET | viewer | Check provider connectivity, latency, and available brain count |
test-brain | POST | operator | Send a test prompt to verify a specific brain works |
Health Check
GET /api/{circle}/{intelligence-repo}/{lab}/ops/health
Returns provider reachability, response latency, and the number of active brains.
Test a Brain
POST /api/{circle}/{intelligence-repo}/{lab}/ops/test-brain
{
"brain_slug": "claude-sonnet",
"prompt": "Say hello."
}
Provider Protocols
| Protocol | Providers | Notes |
|---|---|---|
openai | OpenAI, Groq, Mistral, Gemini, DeepInfra, Fireworks, Cerebras, Scaleway, Ollama, vLLM | Most widely compatible |
anthropic | Anthropic | Native Messages API |
bedrock | AWS Bedrock | Uses AWS SigV4 auth, not bearer tokens |
replicate | Replicate | Prediction-based API with polling |
Most self-hosted and third-party providers use the OpenAI-compatible protocol.
Provider Quirks
Some providers have behavioral differences that affect parameter handling:
quirks:
mutual_exclusion: [temperature, top_p] # Can't use both (Anthropic)
requires_max_tokens: true # Must always set max_tokens (Anthropic)
Quirks are defined per-lab and enforced at runtime. The constraint system automatically strips conflicting parameters rather than returning errors.
Credential Management
Labs support two credential modes:
| Mode | For | How It Works |
|---|---|---|
credential_ref | User labs | References an api-token element; key is encrypted in Vault and decrypted at resolution time |
env_vars | Platform labs | Reads from server environment variables (e.g., ANTHROPIC_API_KEY) |
Credentials are never exposed to agents or API responses. They’re resolved internally when a brain reference is fulfilled.
Common Patterns
Circle-Level Override
Users can create a lab with the same provider as a platform lab to use their own API key. Brain resolution checks the user’s circle first, so their lab takes priority:
Platform circle: anthropic-lab (env_vars: ANTHROPIC_API_KEY)
User circle: my-anthropic (credential_ref: my-api-key)
Agent brain: "claude-sonnet" → resolves in user circle first
Rate Limiting
Attach a rate-limit modifier to control API call frequency:
POST /api/{circle}/{intelligence-repo}/{lab}/modifiers
{
"modifier_type": "rate-limit",
"spec": { "requests_per_minute": 60 }
}
Common Mistakes
Missing protocol or base_url. Both are required. The platform can’t connect to a provider without knowing which API protocol to speak and where to send requests.
Wrong credential_ref. The credential_ref must point to an existing api-token element in the same circle. If the token element doesn’t exist or the name is wrong, brain resolution will fail with LAB_NO_API_KEY.
Using credential_ref for platform labs. Platform labs use env_vars, not credential_ref. Environment variables are set on the server, not stored as elements.
Creating brains without a lab. Brains must be children of a lab. A brain at the project or circle level has no provider connection and can’t be resolved.
State Guidance
| State | Guidance | Next actions |
|---|---|---|
active | Lab is active and serving models to agents. | |
degraded | Lab is degraded — the provider may be experiencing issues. Check the provider status. | |
draft | Lab is in draft. Add brains and configure the API key to activate. | Add a brain: triform_element(action: "create", element_type: "brain", name: "my-model", parent: "{slug}") |
error | Lab connection failed. Check the API key and provider endpoint. | Reset to draft: triform_ops(action: "call", slug: "{slug}", operation: "lifecycle", input: { target_state: "draft" }) |
Authoring Hints
| Field | Help | Example |
|---|---|---|
auth.credential_ref | API key credential. Slug of a credential element storing the provider’s API key (e.g. ‘openai-key’). Required for external providers. | my-provider-key |
endpoint | API endpoint. Custom API endpoint URL. Only needed for self-hosted or custom providers. | https://api.example.com/v1 |
provider | Provider type. The LLM provider: anthropic, openai, mistral, google, bedrock, replicate, or custom. | anthropic |
Error Recovery
| Error | Recovery guidance | Next actions |
|---|---|---|
auth | Provider authentication failed. The API key may be missing, expired, or have insufficient permissions. | Update API key: triform_ops(action: "call", slug: "{slug}", operation: "update", input: { spec: { auth: { credential_ref: "..." } } }) |
connection | Cannot reach the provider endpoint. Check the URL and network connectivity. | Check endpoint: triform_ops(action: "call", slug: "{slug}", operation: "get") |
quota | Provider quota exhausted. Check your usage dashboard or upgrade your plan. | |
rate_limit | Provider rate limit exceeded. Wait and retry, or upgrade your plan. |
Relationships
- Contains: brain, ears, mouth
- Attaches to: rate-limit, auth-policy
- Uses: api-token, variable
Capabilities
- brain-provider: Contains brains (LLM models) for actors
- parameter-constraints: Enforces model parameter constraints
- byok: Supports bring-your-own-key configuration
Properties
| Property | Type | Default | Description |
|---|---|---|---|
protocol | string | "openai" | API protocol. Most providers are OpenAI-compatible. |
base_url | string | — | Base URL of the provider API (e.g. https://api.openai.com/v1) |
auth | object | — | Authentication configuration |
parameter_constraints | object | — | Default parameter constraints inherited by all brains in this lab |
quirks | object | — | Provider-specific behavioral quirks |
model | string | — | Default LLM model identifier (e.g. gpt-4o, claude-sonnet-4-6) |
max_tokens | integer | 4096 | Default maximum tokens per response |
temperature | number | 1.0 | Default sampling temperature (0 = deterministic, 2 = creative) |
priority | integer | 100 | Routing priority — lower numbers preferred when multiple labs offer the same brain ID |
model_prefixes | array | — | Model ID prefixes that auto-route to this lab (e.g. ‘claude-’ routes to Anthropic) |
Operations
activity
Get /ops/activity | Auth: Read
Get activity events for this element
Scope depends on element capabilities: individual elements query by element_id, project-form elements with activity-scope-members include member activities, circle-level elements with activity-scope-all query the entire circle. Gracefully returns empty list if activities table is missing (old circles).
attachments
Get /ops/attachments | Auth: Read
List all modifiers and resources attached to this element
Returns both modifiers (policy enforcement) and resources (data injection) with is_modifier flag to distinguish. Items in the generated MODIFIER_TYPES list are modifiers; everything else is a resource. Includes cascade_policy and version pin info.
batch_stats
Get /ops/batch_stats | Auth: Read
Get per-element statistics for all children of this element
Returns per-child stats plus an aggregate. Most meaningful on compound or manifest form elements (repositories, circles, projects); atoms have no children so the result is an empty children array with a zeroed aggregate. Uses efficient GROUP BY SQL. Weighted averages for eval scores.
categorize
Post /ops/categorize | Auth: Execute
Categorize content using a brain in this lab
Sends content to a brain for classification into provided categories. Returns the selected category, confidence score, and reasoning. Useful for content routing, tagging, and triage workflows. Optionally provide a brain slug (defaults to the lab’s default model).
chat
Post /ops/chat | Auth: Execute
Send a chat completion request through this lab’s provider
OpenAI-compatible chat completion endpoint. Send a messages array with role/content pairs. Optionally specify a brain slug to select a specific model (defaults to the lab’s default model). The lab resolves connection details and forwards the request to the provider.
compose
Post /ops/compose | Auth: Execute
Batch add and remove modifiers on this element in a single call
Declarative composition: add modifiers by ref path (slug or path@version) and remove by attachment ID, all in one atomic call on the target element. Each ‘add’ entry resolves the source element, validates topology, attaches with optional priority and cascade policy. Each ‘remove’ entry deletes the attachment row. Returns a summary of what was added and removed. Example: compose({ add: [{ref: “my-prompt”}, {ref: “rate-limit/api@v2”, priority: 50}], remove: [{attachment_id: “uuid”}] })
context
Get /ops/context | Auth: Read
Get connected elements (graph traversal)
Graph traversal showing all connected elements with their relationship type (contains, contained_by, references, referenced_by, attaches, etc.). Use ?depth=N to control traversal depth (default 1) and ?types=actor,data to filter by element types.
create
Post /ops/create | Auth: Write
Create child element
POST to the parent path — element_type goes in the request body, NOT the URL. Both element_type and slug are required and must be non-empty. Name is derived from slug if omitted. Writes to both Git and PostgreSQL. All elements are stored flat under the circle — no intermediate library wrapper rows.
delete
Delete /ops/delete | Auth: Admin
Delete element (soft delete)
Soft delete — sets state to ‘deleted’ but retains the record. Cannot delete elements that have children (has_no_bond precondition) or active runs. Requires admin auth and confirmation.
disable
Post /ops/disable | Auth: Admin
Disable element (hides and prevents use)
Idempotent — safe to call on already-disabled elements. Optionally pass a reason string. Disabled elements cannot be invoked or executed. Inverse of enable.
enable
Post /ops/enable | Auth: Admin
Enable element (makes usable and visible)
Idempotent — safe to call on already-enabled elements. Transitions element to ready/enabled state. Cannot enable deleted elements. Inverse of disable.
export_bundle
Get /ops/export/bundle | Auth: Read
Export element as downloadable git bundle
On non-root-namespace elements, returns a binary git bundle. On root-namespace (circle) elements, dispatch hands off to the circle’s own export_bundle op, which returns a multi-element JSON envelope with one base64 bundle per child element — this is intentional, not an error.
generate
Post /ops/generate | Auth: Execute
Generate text from a prompt through this lab
Simplified generation endpoint — send a prompt string and get a response. Internally delegates to the chat completion pipeline with the prompt wrapped as a user message.
get
Get /ops/get | Auth: Read
Get element details
Element is already resolved by the routing layer — this returns the cached element, not a fresh DB query. Use the path /api/{circle}/{slug} to address elements.
health
Get /ops/health | Auth: Read
Check if this lab is reachable and responding
Returns the configuration the lab would use for an outbound chat — the resolved status, transport protocol, base URL, whether an API key is set, gateway availability, and the lab’s element ID. The old
latency_ms/errorshape was YAML-only and never emitted by the executor; the schema now matches the executor’s actual response (rebased 2026-05-06 by IMPROVE-66 contract drift gate).
import_bundle
Post /ops/import/bundle | Auth: Write
Import git bundle into element
Accepts a base64-encoded git bundle in the JSON bundle_base64 field. Use overwrite=true to replace existing elements with same slug (default skips duplicates). Imported elements get new UUIDs. Returns counts of imported/skipped elements and any errors.
intention
Get /ops/intention | Auth: Read
Get element intention with full inheritance chain
Returns three levels: direct (this element’s intention), inherited (from category and root), and resolved (final merged intention). Useful for understanding an element’s purpose in context of its hierarchy.
invoke
Post /ops/invoke | Auth: Execute
Run an inference request through this lab (alias for chat)
Convenience alias for the chat operation. Accepts either a messages array (OpenAI format) or a simple prompt/content string. When used as an automation step, the step input is forwarded directly — so automation edges receive the LLM response, not connection metadata.
list-brains
Get /ops/brains | Auth: Read
List all brain child elements in this lab
Returns all brain elements that are children of this lab — IDs, display names, context lengths, capabilities, and pricing. Brains are child elements (not spec properties), so this enumerates the lab’s children of type “brain”.
promote
Post /ops/promote | Auth: Admin
Promote element configuration to a target environment
Only for manifest-form elements (projects). Environments advance: dev → demo → live. dev→demo requires member+ role, demo→live requires admin. Freezes member versions at promotion time (creates snapshot). Persists environment config to spec.environments.
readme
Get /ops/readme | Auth: Read
Get element README.md content
Reads README.md from the element’s git repository. Returns empty content (not an error) if no README exists. Always returns markdown format.
readme_update
Post /ops/readme_update | Auth: Write
Update element README.md content
Creates or overwrites README.md in the element’s git repo. Commits to the draft branch. Content must be provided as a markdown string.
remove-modifier
Post /ops/remove-modifier | Auth: Execute
Remove an attached modifier from this element by attachment ID
Removes a modifier/resource attachment by its row ID. The ID comes from the attachments or context API. This is the reverse of attach — called on the target element, not the source.
restore
Post /ops/restore | Auth: Admin
Restore element to a specific version
Automatically snapshots the current state before restoring (creates a ‘Before restore to vN’ version entry). Writes restored spec to git as .triform/spec.yaml. Git failures warn but don’t fail the operation — DB state is authoritative. Cannot restore deleted elements.
schema
Get /ops/schema | Auth: Read
Get element input/output schema (MCP tools/list compatible)
Returns type-level port schemas from the TypeRegistry — not instance-specific overrides. Includes direction (input/output), required flag, and JSON schema per port. Useful for understanding what data an element accepts and produces.
set-api-key
Post /ops/set-api-key | Auth: Admin
Store the provider API key securely in the vault
Encrypts and stores the API key in the platform vault, keyed by this lab element’s ID. The key never appears in the element spec — only an [encrypted] marker is stored. Use this instead of setting auth.api_key directly in the spec to ensure keys are vault-encrypted.
source
Get /ops/source | Auth: Read
Get any file’s content from the element’s git repository
Reads an arbitrary file from the element’s CAS-backed git tree by its relative path. Same store as
readme, just generalized. Path safety: rejects..traversal, leading/, and null bytes. Use this to viewmain.pyfor action elements, asset files for SPAs, etc. Returns empty content (not an error) if the file doesn’t exist.
source_branches
Get /ops/source/branches | Auth: Read
List Source branches for this element
Returns the standard draft/demo/live Source branches, their current commits, and promotion relationships. Use GET /api/{element_path}/ops/source/branches.
source_promote
Post /ops/source/promote | Auth: Write
Promote Source branch forward
Promotes draft to demo or demo to live through the generated element op path. Direct Git pushes to demo/live are blocked by Source policy.
source_repair
Post /ops/source/repair | Auth: Write
Inspect or repair the element Source index
Runs Source repair through the element operation path. Defaults to dry_run=true; set dry_run=false only after reviewing a dry-run report.
source_status
Get /ops/source/status | Auth: Read
Get Source control status for this element
Returns the branch-aware clone URL, checkout commands, current draft commit, child source-link count, portable export summary, Source health, warnings, and auth hints for the addressed element. Use the element-first path: GET /api/{element_path}/ops/source/status.
source_validate
Post /ops/source/validate | Auth: Read
Validate Source branch contents
Validates a Source branch before accepting local Git workflow changes or promotion. Defaults to branch=draft and rejects runtime data, generated output, secret material, and unreadable CAS refs.
stats
Get /ops/stats | Auth: Read
Get aggregate statistics for this element
Health status is computed: error if errors_per_day > 5 or success_rate < 0.8, warning if errors_per_day > 0 or success_rate < 0.95. Firing alerts escalate health to error/warning. Default period is ‘day’. Returns runs_per_day, success_rate, avg_duration_ms, and more.
test-brain
Post /ops/test | Auth: Execute
Send a test prompt to verify a specific brain works
Sends a minimal chat completion request to the specified brain to verify it accepts requests. Returns the response and latency. Useful after adding a new brain or changing credentials.
tree
Get /ops/tree | Auth: Read
Get the element’s position in the graph — ancestors, children, references, and subtree statistics
Uses per-circle ElementGraph cache for O(1) lookups. Returns ancestors (containment chain), children (direct), members (references), referenced_by (reverse refs), attachments, and subtree stats. Default depth is 3, max is 10. Pass ?include_metadata=true for name/state on each node.
update
Patch /ops/update | Auth: Write
Update element
Partial update — send only the fields you want to change.
spec,name, andintentionare all independently optional.specMUST be a JSON object when present; deep-merged into the existing spec by default. Empty{"spec":{}}preserves existing spec content but still records a new version (no-op for content, not for version state). To clear/replace the entire spec wholesale send{"spec":{...},"deep":false}. List-typed spec fields use replace semantics (the patch list replaces the existing list, no array merging). Coordinates Git + DB writes. Slug cannot be changed after creation.
update_meta
Patch /ops/update_meta | Auth: Write
Update element metadata (lightweight merge — does NOT bump version or snapshot spec)
Shallow JSONB merge into element.meta. Top-level keys in the provided value replace existing meta values; other keys are preserved. Used for UI metadata like canvas positions, panel state, viewer preferences. Wire-shape op_name is
update_meta(distinct fromupdate) so SSE subscribers + the cache auto-invalidator can distinguish lightweight metadata changes from spec edits without inspecting the payload. The MutatingElementStore wrapper stamps this op_name on the lifecycle event emitted byupdate_element_metastorage calls.
version
Get /ops/version | Auth: Read
Get current version or full history
Returns current version by default. Pass ?history=true for full version history (up to ?limit=N, default 50). Versions are backed by the element_versions table. Every spec update creates a new version entry.
Error Codes
| Code | Class | Retryable | Description |
|---|---|---|---|
LAB_NO_API_KEY | validation | no | No API key configured — set credential_ref or env_vars |
LAB_UNREACHABLE | internal | yes | Cannot reach the provider API |
LAB_BRAIN_NOT_FOUND | not_found | no | Requested brain slug not found as child of this lab |
LAB_AUTH_FAILED | auth | no | API key rejected by the provider |
LAB_RATE_LIMITED | limit | yes | Provider rate limit exceeded |
Observability
Defined for this element
Metrics
- health_check_count
- health_latency_ms
- active_brains
- total_requests
- total_cost_usd
Events
- lab.health.checked
Set it up
- Protocolstring
- API protocol for this provider
- Base URLstring
- Provider API endpoint
- API Keystring
- Provider API key (stored encrypted)