Under the hood, Magma uses sessions to handle the context and state of the agent.

sessions are an incredibly powerful feature in the Mamga ecosytem because testing and optimizing agents requires accessing the unique instances of your agent. With sessions, you can snapshot different states, contexts, and interactions of your agent.

A new session is created when a hook is triggered with a new session id, or when the agent is accessed via the agent api with a new session id.

When one of these events is triggered without a session id, a new temporary session is created to handle the agent interactions.

Agent API

The agent api is a way to interact with the agent via websocket or http requests.

When using the agent api, you can specify a session id to interact with a specific session of the agent.

HTTP Request

You can specify the session id as a field in the body of the request when accessing your agent via the /chat route.

const response = await fetch(`https://api.magmadeploy.com/v1/chat`, {
    method: 'POST',
    headers: {
        'x-api-key': <public-api-key>,
        'Content-Type': 'application/json',
        Accept: 'application/json',
    },
    body: JSON.stringify({
        sessionId, // optional, but required if you'd like to access a specific session
        messages, // required, the messages array to generate a completion for
    })
});

WebSocket Connection

When using the websocket, you can specify the session id using a query parameter.

wss://api.magmadeploy.com/v1?agent_id=<agent_id>&api_key=<agent_public_api_key>&sessionId=<session_id>

If you are triggering a connection from a service that does not allow you to add query parameters, you can convert them to key=value path parameters

wss://api.magmadeploy.com/v1/agentId=<agent_id>/apiKey=<agent_public_api_key>/sessionId=<session_id>


Hooks

When using hooks, you can specify which session should handle the hook. This is done by specifying where in the hook request the session id is located.

@hook('user-update', { session: (req: Request) => req.body.userId} )
async updateUser(req: Request, res: Response) {
    const { userId, data } = req.body;
}

In this example, the agent that handles the hook is the agent with a sessionId that matches req.body.userId. See Hook Advanced Usage for more details


Jobs

When you declare a job as non-static, it will be scheduled on every session of the agent that is created.

@job('* * * * *')
async sessionJob() {
    console.log('This job will run for every session of the agent')
}

This can be helpful for tasks that are user-specific, and should be run for each user.