> ## Documentation Index
> Fetch the complete documentation index at: https://autonomy.computer/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Coding Agents: How to use memory, conversation, and scope in Autonomy agents

> Enable persistent, contextual conversations with memory management, multi-turn interactions, and user isolation using scope and conversation IDs in Autonomy agents.

# A guide for coding agents to use memory, conversation, and scope in Autonomy agents

Enable persistent, contextual conversations that remember previous interactions and maintain separate contexts for different users and conversation threads.

> **Key Terms**: See the [definitions section of the main guide](https://autonomy.computer/docs/_for-coding-agents.md#definitions).

*Keywords: memory, conversation, scope, multi-user, user isolation*

This guide shows how to configure agents with memory, manage separate conversation threads, and implement user isolation using scope.

## Memory, Conversation, and Scope

Autonomy agents automatically maintain memory within conversations, allowing natural, contextual interactions.

> **IMPORTANT**: Memory is **conversation-local**. Each conversation thread maintains its own context. Memory does NOT persist across different conversations, even for the same user/scope.
>
> * ✅ Same scope + same conversation = shared memory within that thread
> * ❌ Same scope + different conversation = no shared memory (fresh start)
> * ❌ Different scope = completely isolated (as expected)

### Memory with Multiple Conversations

This example demonstrates memory persistence, multiple conversation threads, and user isolation with scope:

#### Agent with Memory

Create `images/main/main.py`:

```python theme={null}
from autonomy import Agent, Model, Node

async def main(node):
    await Agent.start(
        node=node,
        name="memory-assistant",
        instructions="""
        You are a helpful assistant with memory. Remember context within
        each conversation and provide personalized responses based on what
        each user has shared.
        """,
        model=Model("claude-sonnet-4-v1")
    )

Node.start(main)
```

#### Testing Memory and Conversations

Deploy your zone, then test memory persistence:

```bash theme={null}
# First message - establish context
timeout 15s curl --silent --request POST \
--header "Content-Type: application/json" \
--data '{"message":"My name is Alice and I work as a software engineer."}' \
"https://${CLUSTER}-${ZONE}.cluster.autonomy.computer/agents/memory-assistant"

# Follow-up - agent remembers context
timeout 15s curl --silent --request POST \
--header "Content-Type: application/json" \
--data '{"message":"What do you remember about me?"}' \
"https://${CLUSTER}-${ZONE}.cluster.autonomy.computer/agents/memory-assistant"
```

Test multiple independent conversations:

```bash theme={null}
# Conversation 1 - cooking topic
timeout 15s curl --silent --request POST \
--header "Content-Type: application/json" \
--data '{"message":"I love cooking Italian food, especially pasta.", "conversation":"cooking-chat"}' \
"https://${CLUSTER}-${ZONE}.cluster.autonomy.computer/agents/memory-assistant"

# Conversation 2 - travel topic
timeout 15s curl --silent --request POST \
--header "Content-Type: application/json" \
--data '{"message":"I am planning a trip to Japan next month.", "conversation":"travel-chat"}' \
"https://${CLUSTER}-${ZONE}.cluster.autonomy.computer/agents/memory-assistant"

# Follow up in conversation 1 - remembers cooking context
timeout 15s curl --silent --request POST \
--header "Content-Type: application/json" \
--data '{"message":"What ingredients do I need for carbonara?", "conversation":"cooking-chat"}' \
"https://${CLUSTER}-${ZONE}.cluster.autonomy.computer/agents/memory-assistant"

# Follow up in conversation 2 - remembers travel context
timeout 15s curl --silent --request POST \
--header "Content-Type: application/json" \
--data '{"message":"What should I pack for the weather?", "conversation":"travel-chat"}' \
"https://${CLUSTER}-${ZONE}.cluster.autonomy.computer/agents/memory-assistant"
```

Test user isolation with scope:

```bash theme={null}
# User Alice - shares preferences
timeout 15s curl --silent --request POST \
--header "Content-Type: application/json" \
--data '{"message":"I am Alice, a vegetarian who loves hiking.", "scope":"user-alice", "conversation":"profile"}' \
"https://${CLUSTER}-${ZONE}.cluster.autonomy.computer/agents/memory-assistant"

# User Bob - shares different preferences
timeout 15s curl --silent --request POST \
--header "Content-Type: application/json" \
--data '{"message":"I am Bob, I eat meat and prefer indoor activities.", "scope":"user-bob", "conversation":"profile"}' \
"https://${CLUSTER}-${ZONE}.cluster.autonomy.computer/agents/memory-assistant"

# Alice asks for meal suggestions - gets vegetarian options
timeout 15s curl --silent --request POST \
--header "Content-Type: application/json" \
--data '{"message":"What should I have for dinner?", "scope":"user-alice", "conversation":"meal-planning"}' \
"https://${CLUSTER}-${ZONE}.cluster.autonomy.computer/agents/memory-assistant"

# Bob asks for meal suggestions - gets meat options
timeout 15s curl --silent --request POST \
--header "Content-Type: application/json" \
--data '{"message":"What should I have for dinner?", "scope":"user-bob", "conversation":"meal-planning"}' \
"https://${CLUSTER}-${ZONE}.cluster.autonomy.computer/agents/memory-assistant"
```

Each conversation maintains its own memory thread, and scope ensures complete user isolation.

### Memory in Custom FastAPI Applications

Integrate memory management into custom API endpoints:

#### Custom API with Memory

Create `images/main/main.py`:

```python theme={null}
from autonomy import Agent, HttpServer, Model, Node, NodeDep
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional
import uuid

app = FastAPI()

class ChatMessage(BaseModel):
    message: str
    user_id: Optional[str] = None
    conversation_id: Optional[str] = None

class UserProfile(BaseModel):
    name: str
    preferences: dict
    user_id: str

# Store user profiles (in production, use a proper database)
user_profiles = {}

@app.post("/chat")
async def chat_with_memory(request: ChatMessage, node: NodeDep):
    """Chat endpoint with automatic memory management"""
    conversation_id = request.conversation_id or str(uuid.uuid4())
    agent_name = f"chat_agent_{conversation_id}"

    try:
        # Get user context if available
        user_context = ""
        if request.user_id and request.user_id in user_profiles:
            profile = user_profiles[request.user_id]
            user_context = f"User profile: {profile['name']}, Preferences: {profile['preferences']}"

        agent = await Agent.start(
            node=node,
            name=agent_name,
            instructions=f"""
            You are a helpful assistant with memory. Remember everything from
            this conversation and provide contextual responses.

            {user_context}
            """,
            model=Model("claude-sonnet-4-v1")
        )

        response = await agent.send(
            request.message,
            scope=request.user_id,
            conversation=conversation_id
        )

        return {
            "response": response[-1].content.text,
            "conversation_id": conversation_id,
            "user_id": request.user_id
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/users")
async def create_user_profile(profile: UserProfile):
    """Create or update user profile for personalized interactions"""
    user_profiles[profile.user_id] = {
        "name": profile.name,
        "preferences": profile.preferences
    }
    return {"message": "Profile created", "user_id": profile.user_id}

Node.start(http_server=HttpServer(app=app))
```

#### Testing Custom API

```bash theme={null}
# Create user profiles
timeout 15s curl --silent --request POST \
--header "Content-Type: application/json" \
--data '{
  "user_id": "alice123",
  "name": "Alice",
  "preferences": {"diet": "vegetarian", "hobbies": ["hiking", "reading"]}
}' \
"https://${CLUSTER}-${ZONE}.cluster.autonomy.computer/users"

# Start conversation with Alice
timeout 15s curl --silent --request POST \
--header "Content-Type: application/json" \
--data '{
  "message": "I want to plan a healthy meal for this week",
  "user_id": "alice123",
  "conversation_id": "meal-planning-alice"
}' \
"https://${CLUSTER}-${ZONE}.cluster.autonomy.computer/chat"

# Continue Alice's conversation - agent remembers context
timeout 15s curl --silent --request POST \
--header "Content-Type: application/json" \
--data '{
  "message": "What did I mention about my dietary preferences?",
  "user_id": "alice123",
  "conversation_id": "meal-planning-alice"
}' \
"https://${CLUSTER}-${ZONE}.cluster.autonomy.computer/chat"
```

## Agent Lifecycle

Agents keep running after they are started, until they are stopped. Handle this correctly when using custom FastAPI endpoints:

```python theme={null}
# ❌ This will cause "AlreadyExists" errors on subsequent requests
agent = await Agent.start(node=node, name="my-agent", ...)

# ✅ Better: Use a global reference and initialize once
global_agent = None

if global_agent is None:
    try:
        global_agent = await Agent.start(node=node, name="my-agent", ...)
    except Exception as e:
        if "AlreadyExists" in str(e):
            # Agent already exists, continue using it
            pass
        else:
            raise e
```

## Related Guides

* [How to create custom APIs](https://autonomy.computer/docs/_for-coding-agents/create-custom-apis.md)
* [How to give agents tools](https://autonomy.computer/docs/_for-coding-agents/tools.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.