Installation
Quickstart
Building Your Agent
Communication to and from agents all happens asynchronously through Events. Before defining your agent, define what
events it will
listen for and what events it will emit.
Let's start with something simple.
| from mojentic import Event
class RequestEvent(Event):
text: str
class ResponseEvent(Event):
text: str
|
The BaseLLMAgent provides a convenient way to make a call to an LLM, using its generate_response
method. Events are
sent to the agent through the receive_event
method, and any events it wishes to push back into the system are created
and returned.
| from mojentic.agents import BaseLLMAgent
from mojentic.llm import LLMBroker
class GeographyExpertAgent(BaseLLMAgent):
def __init__(self, llm: LLMBroker):
super().__init__(
llm,
"You are a friendly encyclopedia," # This will be the
" specializing in geography.") # system prompt
def receive_event(self, event):
# event.text contains the user's input, used as a prompt for the LLM
response = self.generate_response(event.text)
# we can generate any number of events, we'll just generate one for
# the LLM's response text
return [
ResponseEvent(
source=type(self),
correlation_id=event.correlation_id, # include the source
# event's correlation_id
text=response)
]
|
Hey, maybe we should assign the emitted events' correlation_id automatically. That would be a nice feature.
Let's prepare to set the agent in motion.
Because we're extending the BaseLLMAgent, first we need to define the LLM that we'll use. By default, Mojentic will use
a local Ollama instance, and look for the name of the model you specify when creating the LLMBroker
.
| llm = LLMBroker("llama3.1-instruct-8b-32k")
|
We'll create our agent with a reference to the LLM we want it to use.
| geo_agent = GeographyExpertAgent(llm)
|
Let's include an OutputAgent, which will just print any incoming events to the console.
| from mojentic.agents import OutputAgent
output_agent = OutputAgent()
|
Now, let's use the Router to define the flow of events through the system.
| from mojentic import Router
router = Router({
# RequestEvents will go to both the GeographyExpertAgent and OutputAgent.
RequestEvent: [geo_agent, output_agent],
# ResponseEvents generated by the GeographyExpertAgent will only go to
# the OutputAgent.
ResponseEvent: [output_agent]
})
|
The Dispatcher manages event propagation through the system, to each agent in its own thread.
| dispatcher = Dispatcher(router)
|
Finally, let's inject a new event into the system.
| dispatcher.dispatch(
RequestEvent(
source=str,
text="What is the capitol of Canada?"
)
)
|