コンテンツにスキップ
Developer Preview — APIs and language features may change before 1.0

Cookbook

このコンテンツはまだ日本語訳がありません。

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

Classification

Classify text into categories with confidence scores.

machine classifier
accepts
text as text, required
responds with
category as text
confidence as number
implements
ask classify, using: "gpt-4o"
role
"You classify text into exactly one category."
task
"Classify this text: ${input.text}"
returns
category as text, required
confidence as number, required

Summarization

Summarize long text with configurable length.

machine summarizer
accepts
text as text, required
max_words as number, default: 100
responds with
summary as text
implements
ask summarize, using: "gpt-4o"
task
"Summarize in ${input.max_words} words or fewer:\n\n${input.text}"
returns
summary as text, required

API Call with Error Handling

Fetch data from an external API with fallback.

machine api_fetcher
accepts
url as text, required
responds with
data as map
error as text
ensures
permissions
allowed to http
implements
ask fetch, from: @mashin/actions/http/get
url: input.url
headers: {"Accept": "application/json"}
on failure
compute handle_error
{data: null, error: "Failed to fetch"}

Multi-Step Pipeline

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

machine research_pipeline
accepts
topic as text, required
responds with
report as text
ensures
permissions
allowed to reason
implements
ask research, using: "gpt-4o"
task
"Research this topic and list 5 key findings: ${input.topic}"
returns
findings as list
ask analyze, using: "gpt-4o"
task
"Analyze these findings and identify the most important insight:\n${steps.research.findings.join('\n')}"
returns
insight as text
ask write, using: "gpt-4o"
task
"Write a brief report about ${input.topic}.\nKey insight: ${steps.analyze.insight}"
returns
report as text

Parallel Processing

Run multiple operations simultaneously.

machine content_analyzer
accepts
text as text, required
responds with
sentiment as text
entities as list
word_count as number
implements
together
ask sentiment, using: "gpt-4o"
task "Rate sentiment as positive/negative/neutral: ${input.text}"
returns sentiment as text
ask entities, using: "gpt-4o"
task "Extract named entities: ${input.text}"
returns entities as list
compute count
{word_count: input.text.split(" ").length}

Conditional Routing

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
implements
ask classify, using: "gpt-4o-mini"
task "Is this urgent? Reply yes or no: ${input.message}"
returns urgent as boolean
decide route
if steps.classify.urgent or input.priority == "high"
ask escalate, using: "gpt-4o"
task "Handle urgent: ${input.message}"
returns response as text
compute result
{response: steps.escalate.response, escalated: true}
else
compute result
{response: "Queued for standard processing", escalated: false}

Pattern Matching

Route by category with exhaustive handling.

machine request_handler
accepts
type as text, required
data as map
responds with
result as map
implements
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}}

Safe Navigation (Optional Chaining)

Handle deeply nested optional data without crashes.

machine profile_extractor
accepts
user_data as map
responds with
display_name as text
city as text
implements
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}

Budget-Aware Model Selection

Choose cheaper models when budget is low.

machine smart_analyzer
has introspection
accepts
text as text, required
responds with
analysis as text
ensures
permissions
allowed to reason
implements
decide select_model
if me.token_budget > 5000 and me.cost < 10.0
ask analyze, using: "gpt-4o"
task "Deep analysis: ${input.text}"
returns analysis as text
else
ask analyze, using: "gpt-4o-mini"
task "Quick analysis: ${input.text}"
returns analysis as text

Iteration Over Collections

Process each item in a list.

machine batch_processor
accepts
items as list, required
responds with
results as list
implements
for each item in input.items
compute process
{name: item.name.toUpperCase(), processed: true}

Memory (Store and Retrieve)

Persist data across executions.

machine note_taker
accepts
action as text, required
content as text
query as text
responds with
result as text
implements
decide act
if input.action == "save"
remember save_note
key: "note:" ++ input.content.substring(0, 20)
value: input.content
compute done
{result: "Saved"}
else
recall find_notes
query: input.query
limit: 5
compute done
{result: steps.find_notes.join("\n")}

Reusable Functions (defines)

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
implements
compute process
let cleaned = input.items.map(i => clean(i.name))
{summary: format_result(cleaned, input.label)}

Machine with Domain Store

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
stores
store users
resource user
field name as text
field email as text
field created_at as datetime
identity email
create
read
implements
decide act
if input.action == "create"
save create_user
store: "users"
resource: "user"
data: {name: input.name, email: input.email}
else
query find_user
store: "users"
resource: "user"
filter: {email: input.email}

Governance with Guards

Set cost limits and permission boundaries.

machine governed_agent
has agency
accepts
task as text, required
responds with
result as text
ensures
permissions
allowed to reason
allowed to http
not allowed to filesystem
not allowed to exec
guards
max_cost: 5.00
max_tokens: 100000
implements
ask execute, using: "gpt-4o"
task "Complete this task: ${input.task}"
returns result as text

Inline Tests

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
implements
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}

Surface: REST API

Expose a machine as an API endpoint.

machine api_service
accepts
query as text, required
responds with
answer as text
expresses
api
path: "/api/ask"
method: "POST"
implements
ask respond, using: "gpt-4o"
task "Answer: ${input.query}"
returns answer as text