Aller au contenu
Developer Preview — APIs and language features may change before 1.0

Cookbook

Ce contenu n’est pas encore disponible dans votre langue.

Practical recipes for common tasks. Each recipe is a complete, working pattern you can adapt.

Classify text into categories with confidence scores.

machine classifier
accepts
text as text, required
responds with
category as text
confidence as number
behaves
ask classify, using: "standard"
role
"You classify text into exactly one category."
task
"Classify this text: ${input.text}"
returns
category as text, required
confidence as number, required
verifies
test "classifies text into a category"
assuming classify {category: "billing", confidence: 0.95}
given {text: "My payment failed"}
expect {category: "billing", confidence: 0.95}

Summarize long text with configurable length.

machine summarizer
accepts
text as text, required
max_words as number, default: 100
responds with
summary as text
behaves
ask summarize, using: "standard"
task
"Summarize in ${input.max_words} words or fewer:\n\n${input.text}"
returns
summary as text, required
verifies
test "summarizes the input text"
assuming summarize {summary: "A concise summary."}
given {text: "A very long passage of text about many subjects.", max_words: 20}
expect {summary: "A concise summary."}

Fetch data from an external API with fallback.

machine api_fetcher
accepts
url as text, required
responds with
data as map
error as text
behaves
ask fetch, from: @mashin/actions/http/get
url: input.url
headers: {"Accept": "application/json"}
compute handle_response
{data: steps.fetch.status == 200 ? steps.fetch.body : null, error: steps.fetch.status == 200 ? null : "Failed to fetch"}
ensures
permissions
allowed to network.http to any
verifies
test "returns data on a successful response"
assuming fetch {body: {id: 1, name: "Alice"}, status: 200, headers: {}}
given {url: "https://api.example.com/users/1"}
expect {data: {id: 1, name: "Alice"}, error: null}
test "returns a fallback error on a failed response"
assuming fetch {body: {}, status: 500, headers: {}}
given {url: "https://api.example.com/missing"}
expect {data: null, error: "Failed to fetch"}

Chain multiple LLM calls where each step builds on the previous.

machine research_pipeline
accepts
topic as text, required
responds with
report as text
behaves
ask research, using: "standard"
task
"Research this topic and list 5 key findings: ${input.topic}"
returns
findings as list
ask analyze, using: "standard"
task
"Analyze these findings and identify the most important insight:\n${steps.research.findings.join(\"\\n\")}"
returns
insight as text
ask write, using: "standard"
task
"Write a brief report about ${input.topic}.\nKey insight: ${steps.analyze.insight}"
returns
report as text
ensures
permissions
allowed to model
verifies
test "chains research, analysis and writing into a report"
assuming {research: {findings: ["a", "b", "c", "d", "e"]}, analyze: {insight: "The key insight."}, write: {report: "A brief report."}}
given {topic: "Elixir"}
expect {report: "A brief report."}

Run multiple operations simultaneously.

machine content_analyzer
accepts
text as text, required
responds with
sentiment as text
entities as list
word_count as number
behaves
together
flow analyze_sentiment
ask sentiment, using: "standard"
with task "Rate sentiment as positive/negative/neutral: ${input.text}"
returns sentiment as text
flow extract_entities
ask entities, using: "standard"
with task "Extract named entities: ${input.text}"
returns entities as list
flow count_words
compute count
{word_count: input.text.split(" ").length}
verifies
test "analyzes sentiment, entities and word count together"
assuming {sentiment: {sentiment: "positive"}, entities: {entities: ["Alice", "Bob"]}}
given {text: "Alice met Bob"}
expect {sentiment: "positive", entities: ["Alice", "Bob"], word_count: 3}

Route execution based on input or intermediate results.

machine ticket_router
accepts
message as text, required
priority as text, default: "normal"
responds with
response as text
escalated as boolean
behaves
ask classify, using: "fast"
with task "Is this urgent? Reply yes or no: ${input.message}"
returns urgent as boolean
decide route
when steps.classify.urgent or input.priority == "high"
run handle_urgent
otherwise
run handle_standard
flows
flow handle_urgent
ask escalate, using: "standard"
with task "Handle urgent: ${input.message}"
returns response as text
compute result
{response: steps.escalate.response, escalated: true}
flow handle_standard
compute result
{response: "Queued for standard processing", escalated: false}
verifies
test "routes standard tickets to the standard queue"
assuming {classify: {urgent: false}}
given {message: "Just a question", priority: "normal"}
expect {response: "Queued for standard processing", escalated: false}
test "escalates urgent tickets"
assuming {classify: {urgent: true}, escalate: {response: "Handled immediately"}}
given {message: "Everything is down!", priority: "normal"}
expect {response: "Handled immediately", escalated: true}

Route by category with exhaustive handling.

machine request_handler
accepts
type as text, required
data as map
responds with
result as map
behaves
match input.type
when "create"
compute handle_create
{result: {action: "created", id: "new_123"}}
when "update"
compute handle_update
{result: {action: "updated", id: input.data?.id ?? "unknown"}}
when "delete"
compute handle_delete
{result: {action: "deleted", id: input.data?.id ?? "unknown"}}
otherwise
compute handle_unknown
{result: {action: "rejected", reason: "Unknown type: " ++ input.type}}
verifies
test "handles create"
given {type: "create", data: {}}
expect {result: {action: "created", id: "new_123"}}
test "handles update with a supplied id"
given {type: "update", data: {id: "abc"}}
expect {result: {action: "updated", id: "abc"}}
test "rejects an unknown type"
given {type: "frobnicate", data: {}}
expect {result: {action: "rejected", reason: "Unknown type: frobnicate"}}

Handle deeply nested optional data without crashes.

machine profile_extractor
accepts
user_data as map
responds with
display_name as text
city as text
behaves
compute extract
let name = input.user_data?.profile?.display_name ?? input.user_data?.name ?? "Anonymous"
let city = input.user_data?.address?.city ?? "Unknown"
{display_name: name, city: city}
verifies
test "reads a deeply nested display name and city"
given {user_data: {profile: {display_name: "Ada"}, address: {city: "London"}}}
expect {display_name: "Ada", city: "London"}
test "falls back when the nested data is missing"
given {user_data: {}}
expect {display_name: "Anonymous", city: "Unknown"}

Choose cheaper models when budget is low.

machine smart_analyzer
has introspection
accepts
text as text, required
responds with
analysis as text
behaves
decide select_model
when me.token_budget > 5000 and me.cost < 10.0
ask analyze, using: "standard"
task "Deep analysis: ${input.text}"
returns analysis as text
otherwise
ask analyze, using: "fast"
task "Quick analysis: ${input.text}"
returns analysis as text
ensures
permissions
allowed to model
verifies
test "produces an analysis regardless of the selected model"
assuming {analyze: {analysis: "A thorough analysis."}}
given {text: "Some input to analyze."}
expect {analysis: "A thorough analysis."}

Process each item in a list.

machine batch_processor
accepts
items as list, required
responds with
results as list
behaves
for each item in input.items
compute process
{name: item.name.toUpperCase(), processed: true}
compute collect
{results: steps.process}
verifies
test "uppercases and marks each item as processed"
given {items: [{name: "alice"}, {name: "bob"}]}
expect {results: [{name: "ALICE", processed: true}, {name: "BOB", processed: true}]}

Persist data across executions.

machine note_taker
accepts
action as text, required
content as text
query as text
responds with
result as text
behaves
decide act
when input.action == "save"
run save_flow
otherwise
run recall_flow
flows
flow save_flow
remember save_note
key: "note:" ++ input.content.substring(0, 20)
value: input.content
compute done
{result: "Saved"}
flow recall_flow
recall find_notes
query: input.query
limit: 5
compute done
{result: steps.find_notes.join("\n")}
verifies
test "saves a note"
assuming {save_note: {success: true}}
given {action: "save", content: "Buy milk on the way home", query: ""}
expect {result: "Saved"}
test "recalls notes matching a query"
assuming {find_notes: ["note one", "note two"]}
given {action: "recall", content: "", query: "milk"}
expect {result: "note one\nnote two"}

Define shared logic used across steps.

machine data_processor
defines
clean(text) => text.trim().toLowerCase()
score(items) => items.length > 10 ? "large" : "small"
format_result(data, label) => {label: label, count: data.length, size: score(data)}
accepts
items as list, required
label as text, default: "dataset"
responds with
summary as map
behaves
compute process
let cleaned = input.items.map(i => clean(i.name))
{summary: format_result(cleaned, input.label)}
verifies
test "cleans items and summarizes the dataset"
given {items: [{name: " Alice "}, {name: "BOB"}], label: "people"}
expect {summary: {label: "people", count: 2, size: "small"}}

Define and use a persistent data store.

machine user_service
accepts
action as text, required
name as text
email as text
responds with
user as map
behaves
decide act
when input.action == "create"
run create_flow
otherwise
run find_flow
flows
flow create_flow
save create_user
store: "users"
resource: "user"
data: {name: input.name, email: input.email}
compute created
{user: steps.create_user}
flow find_flow
query find_user
store: "users"
resource: "user"
filter: {email: input.email}
compute found
{user: steps.find_user}
stores
store users
resource user
field name as text
field email as text
field created_at as datetime
id unique_email: [email]
create add_user
read list_user
verifies
test "creates a user record"
assuming {create_user: {id: "user_1", name: "Alice", email: "[email protected]"}}
given {action: "create", name: "Alice", email: "[email protected]"}
expect {user: {id: "user_1", name: "Alice", email: "[email protected]"}}
test "finds a user by email"
assuming {find_user: {id: "user_1", name: "Alice", email: "[email protected]"}}
given {action: "find", email: "[email protected]"}
expect {user: {id: "user_1", name: "Alice", email: "[email protected]"}}

Set cost limits and permission boundaries.

machine governed_agent
has agency
accepts
task as text, is required
responds with
result as text
behaves
ask execute, using: "standard"
with task "Complete this task: ${input.task}"
returns
result as text
ensures
permissions
allowed to model
not allowed to filesystem
not allowed to shell
budget
cost: 5.00
tokens: 100000
verifies
test "completes a task within its budget"
assuming execute {result: "Task complete."}
given {task: "Summarize the quarterly report"}
expect {result: "Task complete."}

Test your machine’s behavior as part of the definition.

machine calculator
accepts
a as number, required
b as number, required
op as text, required
responds with
result as number
behaves
match input.op
when "add"
compute calc
{result: input.a + input.b}
when "multiply"
compute calc
{result: input.a * input.b}
otherwise
compute calc
{result: 0}
verifies
test "adds numbers"
given {a: 2, b: 3, op: "add"}
expect {result: 5}
test "multiplies numbers"
given {a: 4, b: 5, op: "multiply"}
expect {result: 20}
test "handles unknown op"
given {a: 1, b: 1, op: "unknown"}
expect {result: 0}

Expose a machine as an API endpoint.

machine api_service
accepts
query as text, required
responds with
answer as text
behaves
ask respond, using: "standard"
task "Answer: ${input.query}"
returns answer as text
expresses
api
path: "/api/ask"
method: "POST"
verifies
test "answers the query"
assuming respond {answer: "42"}
given {query: "What is the meaning of life?"}
expect {answer: "42"}