Adding a New Agent to a MoonBit Golem Component
Overview
An agent is a durable, stateful unit of computation in Golem. Each agent type is defined as a struct annotated with #derive.agent and has a constructor fn AgentName::new(...) plus public methods pub fn AgentName::method(self: Self).
Steps
- Create the agent file — add a new file
src/<agent_name>.mbt - Define the agent struct — annotate with
#derive.agent - Add constructor —
fn AgentName::new(param: Type) -> AgentName - Add methods —
pub fn AgentName::method(self: Self) -> ReturnType - Build — run
golem buildto verify
Agent Definition
#derive.agent
struct MyAgent {
name: String
mut count: UInt
}
fn MyAgent::new(name: String) -> MyAgent {
{ name, count: 0 }
}
pub fn MyAgent::get_count(self: Self) -> UInt {
self.count
}
pub fn MyAgent::increment(self: Self) -> UInt {
self.count = self.count + 1
self.count
}Custom Types
All parameter and return types must have schema support. For custom structs and enums, annotate with #derive.golem_schema:
#derive.golem_schema
struct MyData {
field1: String
field2: UInt
}
#derive.golem_schema
enum Status {
Active
Inactive(String)
}Key Constraints
- Constructor parameters form the agent identity — two agents with the same parameters are the same agent
- Agents are created implicitly on first invocation — no separate creation step
- Invocations are processed sequentially in a single thread — no concurrency within a single agent
- Method names use
snake_case - Never edit generated files —
golem_reexports.mbt,golem_agents.mbt, andgolem_derive.mbtare auto-generated bygolem build - Only
pub fnmethods are exposed as agent methods — private functions are not exported