From RAG to agent
I built an AI agent that writes TikTok scripts with my own examples: it searches my AWS Sin Mapa scripts, reuses the way I explain each topic and ends with my closing line. It runs on Amazon Bedrock AgentCore Runtime, uses Strands Agents and the Amazon Nova Lite model, and remembers the conversation with AgentCore Memory.
It’s the second part of my AI from Zero series. In the first one I built my first RAG on AWS (in Spanish): a Knowledge Base with my scripts that answers questions. Now I reused that same Knowledge Base as a tool for an agent.
This article is for anyone who has already built a RAG (or read mine) and wants to take the next step. The full code is in guionista-aws-sin-mapa. The agent writes scripts in Spanish, so the prompts and code strings below are in Spanish too.
RAG vs. agent: who decides
The key difference is who decides to search. In a RAG, the code always searches and then the model answers. In an agent, the model receives tools and decides on its own when to use them.
| RAG (part 1) | Agent (part 2) | |
|---|---|---|
| What it produces | An answer to a question | Something new: a script ready to record |
| Who decides to search | My code, on every question | The model, depending on the request |
| Calls to Bedrock | retrieve + converse, in a fixed order |
A loop: reason, use a tool, reason, answer |
| Memory | No | Yes, with AgentCore Memory |
| Where it runs | A script in CloudShell | AgentCore Runtime, as a service |
Technically, both use the same Bedrock Converse API. The difference is that the agent sends, along with the message, the list of available tools (toolConfig) and lets the model ask to use them.
Architecture

The agent lives inside AgentCore Runtime. It reasons with Nova Lite and, when it decides to, searches the Knowledge Base from my first RAG. Memory stores the conversation and CloudWatch logs every step.
| Component | Service or library | Role |
|---|---|---|
| Runtime | Amazon Bedrock AgentCore Runtime | Runs the agent in the cloud, serverless and pay per use |
| Framework | Strands Agents | The agent loop: reason, use tools and answer with streaming |
| Model | Amazon Nova Lite (us.amazon.nova-lite-v1:0) |
Decides which tool to use and writes the script |
| Tool | buscar_en_aws_sin_mapa → retrieve |
Brings back fragments of my scripts, with their source |
| Memory | AgentCore Memory | Stores the conversation and extracts memories per user |
| Observability | Amazon CloudWatch | Traces of every invocation and every tool call |
How it works inside: the agent loop
Strands Agents implements the agent loop on top of the Converse API. In one invocation, this happens:
- Strands describes the tool. From the
@tooldecorator it takes the function name, the description from the docstring and a JSON Schema of the parameters based on the type hints. - First call to the model. It sends the system prompt, the message and the tool in
toolConfig. - The model decides. If it wants to search, it answers with
stopReason: "tool_use"and atoolUseblock with the tool name and its input, for example{"tema": "grupos IAM"}(tema means topic). - Strands runs the
buscar_en_aws_sin_mapafunction (“search in AWS Sin Mapa”), which callsretrieveon the Knowledge Base. - It returns the result to the model as a
toolResultblock with the fragments and their sources. - Second call to the model. With that context it writes the script and ends with
stopReason: "end_turn". If it needed more information, it would go back to step 3.
This is the specification the model receives for my tool:
{
"toolSpec": {
"name": "buscar_en_aws_sin_mapa",
"description": "Busca en los guiones de AWS Sin Mapa lo que Oshin ya explico sobre un tema de AWS. Usala SIEMPRE antes de escribir un guion...",
"inputSchema": {
"json": {
"type": "object",
"properties": {
"tema": {
"type": "string",
"description": "el tema a buscar, por ejemplo \"grupos IAM\" o \"cloud computing\"."
}
},
"required": ["tema"]
}
}
}
}
That’s why the docstring is part of the design, not a comment: it’s the only thing the model knows about the tool when deciding whether to use it and with what input. Writing “use it ALWAYS before writing a script” there, and repeating it in the system prompt, is what made the agent search consistently.
The runtime entrypoint
main.py exposes an invoke function with the @app.entrypoint decorator from BedrockAgentCoreApp. AgentCore Runtime calls it on every invocation:
@app.entrypoint
async def invoke(payload, context):
session_id = getattr(context, "session_id", None) or "default-session"
prompt, actor_id = parse_payload(payload)
agent = _get_agent(session_id, actor_id)
async for event in agent.stream_async(prompt):
yield event
- Session: the
session_idarrives in theX-Amzn-Bedrock-AgentCore-Runtime-Session-Idheader; theactorId(user) arrives in the payload. - One agent per session:
_get_agentis wrapped in anlru_cache, so each session-user pair reuses its agent and its memory manager. - Streaming:
stream_asyncemits events while the model generates; the runtime sends them to the client as they arrive.
Memory
AgentCore Memory stores two levels: the conversation events (short-term memory, with a 30-day expiration in my configuration) and the memories it extracts from them using strategies (long-term memory). I configured four strategies in agentcore/agentcore.json:
| Strategy | What it extracts | Namespace |
|---|---|---|
SEMANTIC |
Facts | /users/{actorId}/facts |
USER_PREFERENCE |
User preferences | /users/{actorId}/preferences |
SUMMARIZATION |
Summary of each session | /summaries/{actorId}/{sessionId} |
EPISODIC |
Episodes of each session | /episodes/{actorId}/{sessionId} |
Namespaces separate memories by user and by session. Memory also has a design cost: it remembers errors. I explain it in the errors section.
Security and permissions
The point this project taught me the most is who runs each call:
| Where it runs | Identity boto3 uses | Can it read the Knowledge Base? |
|---|---|---|
agentcore dev in CloudShell |
My IAM Identity Center credentials (AdministratorAccess) |
Yes |
| AgentCore Runtime | The execution role created by agentcore deploy |
Only after adding the policy |
boto3 looks for credentials along a chain: in CloudShell it finds my session’s; inside the runtime, the agent role’s. The same code behaves differently depending on where it runs.
That’s why the policy in step 8 is minimal:
- One action:
bedrock:Retrieve. The agent can’t create, modify or sync the Knowledge Base. - One resource: the ARN of a single Knowledge Base, not
*. - Inline policy (
put-role-policy) just for this role: it’s deleted along with the role.
In addition, the repository doesn’t include account data: agentcore/aws-targets.json and .env.local are kept out of version control, and the Knowledge Base ID is read from the KB_ID variable.
Step by step
I did everything in AWS CloudShell, in the us-east-1 Region. You need a Knowledge Base with documents (the one from my first RAG) and access to Amazon Nova Lite.
1. Install the tools
pip3 install uv
sudo npm install -g @aws/agentcore
CloudShell wipes globally installed packages between sessions, so I repeat this step every time I come back.
2. Create the project
agentcore create --template agent-python-strands
The template generates the runtime entrypoint, the connection to AgentCore Memory and the configuration in agentcore/agentcore.json. I only modified three files: main.py, kb_tool.py and model/load.py.
3. Turn the RAG’s retrieve into a tool
It’s the same retrieve call from my first RAG, with the Strands @tool decorator. The docstring matters: it’s what the model reads to decide when to use the tool.
@tool
def buscar_en_aws_sin_mapa(tema: str) -> str:
"""Busca en los guiones de AWS Sin Mapa lo que Oshin ya explico sobre un tema de AWS.
Usala SIEMPRE antes de escribir un guion, para usar sus ejemplos y su forma de explicar.
Args:
tema: el tema a buscar, por ejemplo "grupos IAM" o "cloud computing".
"""
resultados = kb.retrieve(knowledgeBaseId=KB_ID, retrievalQuery={"text": tema})
pedazos = []
for r in resultados["retrievalResults"]:
fuente = r["location"].get("s3Location", {}).get("uri", "desconocida")
pedazos.append(f"[Fuente: {fuente}]\n{r['content']['text']}")
if not pedazos:
return "No encontre nada sobre ese tema en los guiones de AWS Sin Mapa."
return "\n\n".join(pedazos)
4. Give it personality and rules (system prompt)
In main.py I defined who the agent is and what it must always do:
- Role: AWS Sin Mapa Scriptwriter; 30- to 60-second scripts, in Spanish and with everyday examples.
- Use the tool before writing and reuse my examples.
- If it finds nothing, say so and warn that the script is generic.
- Structure: hook, explanation with an example and closing.
- Always end with: “Aprende AWS desde 0 conmigo y no te pierdas la próxima clase de AWS Sin Mapa.” (“Learn AWS from zero with me and don’t miss the next AWS Sin Mapa lesson.”)
Then I registered the tool in the tools list that the Strands Agent receives.
5. Change the model
from strands.models.bedrock import BedrockModel
def load_model() -> BedrockModel:
return BedrockModel(model_id="us.amazon.nova-lite-v1:0")
The us. prefix is a cross-Region inference profile: Bedrock distributes the calls across US Regions.
6. Test locally
agentcore dev
In another tab:
curl -X POST http://localhost:8080/invocations \
-H "Content-Type: application/json" \
-d '{"prompt": "Escribe un guion de TikTok sobre los grupos IAM"}'
7. Deploy to AgentCore Runtime
agentcore deploy
The deployment creates the runtime, the memory and a dedicated IAM role for the agent.
8. Grant the minimum permission
In the cloud, the agent uses its own role, not my user. That role can’t read the Knowledge Base until I allow it. I gave it just one action, on a single resource:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "bedrock:Retrieve",
"Resource": "arn:aws:bedrock:us-east-1:<ACCOUNT_ID>:knowledge-base/<KB_ID>"
}
]
}
ROL=$(aws iam list-roles \
--query "Roles[?contains(RoleName,'Guionista') && contains(RoleName,'Runtime')].RoleName" \
--output text)
aws iam put-role-policy \
--role-name "$ROL" \
--policy-name LeerKnowledgeBaseAwsSinMapa \
--policy-document file://iam-policy.json
9. Ask for a script
agentcore invoke --runtime agent \
--payload '{"prompt": "Escribe un guion de TikTok sobre los grupos IAM"}'
To read only the script, without the streaming events, I use the repository’s pedir_guion.sh script (“request script”): ./pedir_guion.sh los grupos IAM.
Results: the agent decides on its own
When I asked for a script about IAM groups, the agent called its tool without me telling it to in the request and reused the example from my original script.
| Test | What happened |
|---|---|
| “Write a script about IAM groups” | It called buscar_en_aws_sin_mapa, found my script from video 23 and used my example: the “Desarrolladores” (Developers) group with María, Pedro, Ana and Juan |
| “Write a script about shared responsibility” | It used my distinction “security OF the cloud / security IN the cloud” |
| Same request in the cloud, before granting the IAM permission | The tool failed and the agent warned that the script didn’t come from AWS Sin Mapa |
| One invocation in the cloud | 911 input tokens, 416 output tokens, 2.5 s latency |
Every script ended with my closing line, just as the system prompt asks.
Real errors and how I fixed them
1. The template’s model wasn’t available. The first agentcore dev answered with AccessDeniedException. The template uses a model my account didn’t have enabled. I switched it to Amazon Nova Lite in model/load.py.
2. It worked in CloudShell; in the cloud, it didn’t. Locally, the agent used my credentials. In AgentCore Runtime it uses its own role, which didn’t have permission for bedrock:Retrieve. The fix was the least-privilege policy from step 8. Lesson: testing locally doesn’t test your cloud permissions.
3. The memory remembered the error. After granting the permission, the agent still didn’t use the tool in the same session: AgentCore Memory had stored that the tool was failing. It worked when I asked for it explicitly. To test changes, I now use a new session.
4. Nova Lite shows its reasoning. Sometimes it answers with <thinking> tags even though the prompt forbids it. For now I strip them on the client with pedir_guion.sh; the right thing is to do it on the server (it’s on the roadmap).
5. CloudShell forgets what you installed. uv and the AgentCore CLI disappear between sessions. I reinstall them with the command from step 1.
Design decisions and limitations
| Decision | Why | Cost or risk |
|---|---|---|
| Agent instead of a fixed RAG | The model decides when and what to search, and can search more than once | Less predictable: the model can skip the tool; I mitigate it with the system prompt and the docstring |
| Reusing the RAG’s Knowledge Base | A single data source and a single retrieve |
Both projects depend on the same Knowledge Base |
| Amazon Nova Lite | Low cost and enough for short texts | Shows <thinking> and follows prompt rules less precisely |
us. inference profile |
More capacity, spread across US Regions | Calls may be processed in another US Region |
| Honest answer on failures | If the tool fails, the agent warns that the script doesn’t come from my scripts | Depends on the model following the instruction |
Known limitations:
- The tool returns every fragment from
retrieve, with noscorefilter; on a topic that isn’t in my scripts, the agent may receive barely relevant fragments. - Memory can keep a failure and change the session’s behavior.
- The evaluation was manual, with few requests. To measure it properly I would build a set of prompts and check three things in each answer: whether it called the tool (in the CloudWatch traces), whether it respects the hook-explanation-closing structure and whether it ends with the exact phrase.
Costs, cleanup and next steps
Everything is billed per use and the runtime scales to zero when there are no invocations:
- AgentCore Runtime: per use.
- AgentCore Memory: for events and memories stored and queried.
- Nova Lite: per token.
- Managed Knowledge Base: for indexed data and searches.
- CloudWatch: for logs and traces.
Check the Amazon Bedrock pricing page and create a budget with alerts in AWS Budgets.
To delete the runtime, the memory and the deployment’s resources:
agentcore remove all --yes
agentcore deploy --yes
The Knowledge Base is deleted separately, from its own project.
Next steps:
- Infrastructure as code with AWS CDK for the Knowledge Base and the role permission.
- Pass
KB_IDas a runtime environment variable. - Strip the
<thinking>tags on the server. - Evaluate the scripts automatically: tool usage, structure and closing line.
What I take away
Going from a RAG to an agent didn’t mean rewriting everything: I reused the same Knowledge Base and the same retrieve call, now as a tool. What was new was giving the model the decision, giving it memory and, above all, taking care of its permissions.
- Code: github.com/OshinVillegas/guionista-aws-sin-mapa
- Part 1, the RAG: I taught AI who I am: my first RAG on AWS (in Spanish)
- RAG repository: github.com/OshinVillegas/mi-primer-rag-aws
- TikTok: @awssinmapa
Learn AWS from zero with me and don’t miss the next AWS Unmapped lesson.
Keep learning:
- Part 1, the RAG: I taught AI who I am: my first RAG on AWS (in Spanish)
- Code on GitHub: guionista-aws-sin-mapa
- RAG repository: mi-primer-rag-aws
If this article helped you, share it with someone who is just getting started with the cloud. See you in the next AWS Unmapped article.
