Para agentes de IA: hay un índice de documentación disponible en https://www.mongodb.com/es/docs/llms.txt — versiones en markdown de todas las páginas están disponibles agregando .md a cualquier ruta URL.
Docs Menu

Comience con la integración de MongoDB Agno

Puedes integrar MongoDB con Agno para configurar una base de conocimiento con capacidad de búsqueda y un historial de conversaciones persistente para tus agentes de IA. Este tutorial muestra cómo configurar un agente de Agno para usar MongoDB para la recuperación de conocimiento y el almacenamiento de sesiones, y luego usar esa configuración para crear un asistente de cocina. Específicamente, realizarás las siguientes tareas:

  1. Configura tu entorno.

  2. Configurar MongoDB como base de conocimientos de Agno.

  3. Crea un asistente que responda preguntas a partir de tus documentos y recuerde los turnos anteriores en la conversación.

  4. Ejecuta el archivo y revisa el resultado.

Agno is an open-source Python framework for building multi-modal AI agents. An Agno agent is composed of modular components, including an optional knowledge base and an optional database, that you configure independently and pass to the same Agent object.

MongoDB proporciona dos de estos componentes, que puede utilizar importando las siguientes clases:

  1. MongoVectorDb Clase: Implementa la interfaz de base de datos vectorial de Agno con MongoDB Vector Search, lo que permite a un agente recuperar documentos relevantes de una colección de MongoDB.

  2. MongoDb Clase: Implementa la interfaz de base de datos de Agno, persistiendo las sesiones de los agentes, la memoria y las métricas como documentos en colecciones de MongoDB.

Tip

Agno names both MongoDB classes MongoDb, so it exports the vector database class as MongoVectorDb to avoid a collision. To learn more, see Integrate MongoDB with the Agno Framework.

Este tutorial utiliza ambos componentes y almacena sus datos en la misma implementación de MongoDB.

Para completar este tutorial, debes tener los siguientes recursos:

  • Uno de los siguientes tipos de clúster de MongoDB:

    • Un clúster de Atlas que ejecuta la versión 6.0.11, 7.0.2 o posterior de MongoDB. Es necesario garantizar que la dirección IP esté incluida en la lista de acceso del proyecto Atlas.

    • A local Atlas deployment created using Python and Docker. Install atlas-local-lib-py (pip install atlas-local-lib-py) to programmatically create and manage local deployments. To learn more, see the atlas-local-lib-py repository.

    • A MongoDB Community cluster with Search and Vector Search installed.

  • Una llave de API de OpenAI. Debes tener una cuenta de OpenAI con créditos disponibles para las solicitudes de API. Para obtener más información sobre cómo registrar una cuenta de OpenAI, consulta el sitio web de la API de OpenAI.

  • Python v3.9 o posterior.

1

Ejecuta los siguientes comandos en tu terminal para crear un nuevo directorio llamado agno-mongodb-project e instalar las dependencias necesarias:

mkdir agno-mongodb-project
cd agno-mongodb-project
pip install agno pymongo openai python-dotenv pypdf
2

En tu directorio agno-mongodb-project, crea un archivo .env y añade el siguiente código:

OPENAI_API_KEY="<openai-api-key>"
MONGODB_URI="<connection-string>"

Se debe sustituir <connection-string> por la cadena de conexión del clúster Atlas o de la implementación local de Atlas.

Su cadena de conexión debe usar el siguiente formato:

mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

Para obtener más información, consulta Conectar a un clúster a través de bibliotecas de clientes.

Su cadena de conexión debe usar el siguiente formato:

mongodb://localhost:<port-number>/?directConnection=true

Para obtener más información, consulta Cadenas de conexión.

3

En su directorio agno-mongodb-project, cree un archivo llamado main.py. Añada el siguiente código a este archivo para cargar las variables de entorno:

import os
from dotenv import load_dotenv
from agno.agent import Agent
from agno.db.mongo import MongoDb
from agno.knowledge.knowledge import Knowledge
from agno.models.openai import OpenAIChat
from agno.vectordb.mongodb import MongoVectorDb
load_dotenv()

En los siguientes pasos, añadirás código a este archivo para construir tu base de conocimientos y tu asistente.

En esta sección, configurará MongoDB como almacén vectorial para una base de conocimiento de Agno, almacenará datos en él y ejecutará una consulta de búsqueda semántica sobre dicha base de datos.

1

Agregue el siguiente código para configurar un almacén de vectores respaldado por MongoDB para su base de conocimientos:

vector_db = MongoVectorDb(
collection_name="agent_knowledge",
db_url=os.environ["MONGODB_URI"],
database="agno",
)
knowledge = Knowledge(vector_db=vector_db)

The preceding code creates a MongoVectorDb instance and passes it to the vector_db parameter of a Knowledge object. Because this is the first time you're using the agent_knowledge collection, Agno creates it along with an MongoDB Vector Search index named vector_index_1.

The index should take about one minute to build. While it builds, the index is in an initial sync state. When it finishes building, you can start querying the data in your collection.

2

Add the following code to your main.py file to load a PDF file containing Thai recipes into your knowledge base:

knowledge.insert(
name="Recipes",
url="https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf",
)

Agno descarga el archivo, lo divide en fragmentos, genera una representación vectorial para cada fragmento con el incrustador predeterminado de OpenAI y escribe los resultados en tu colección.

Tip

To inspect the stored documents, browse the agno.agent_knowledge collection in the Atlas UI. Each document has a content field with a chunk of the recipe text and an embedding field that contains the generated vector. To learn more, see View Collections.

3

Add the following code to your main.py file to query your knowledge base's vector database directly, before connecting it to an agent. This example searches for the three chunks most relevant to a question about green curry:

results = vector_db.search(query="How do I make a green curry?", limit=3)
for doc in results:
print(f"[{doc.name}] {doc.content[:80]}")

Los resultados incluyen los fragmentos de la receta que son más relevantes semánticamente para la consulta, ordenados según su puntuación de similitud.

En esta sección, combinarás tu base de conocimientos con una base de datos MongoDB para crear un asistente completo. El agente recupera documentos relevantes de tu base de conocimientos para responder preguntas y guarda su historial de conversaciones en MongoDB para poder consultar conversaciones anteriores.

1

Add the following code to your main.py file to configure a MongoDb instance for session storage, and then create an agent that uses this session store and the knowledge base configured in the previous section:

db = MongoDb(
db_url=os.environ["MONGODB_URI"],
db_name="agno",
)
agent = Agent(
model=OpenAIChat(id="gpt-4o"),
knowledge=knowledge,
db=db,
search_knowledge=True,
add_history_to_context=True,
num_history_runs=5,
instructions=[
"You are a helpful cooking assistant.",
"Answer questions using only the recipes in your knowledge base.",
"If the knowledge base does not contain a relevant answer, say so clearly.",
],
)
2

Add the following code to your main.py file to send two messages to the agent:

SESSION_ID = "cooking-session-001"
# First turn
agent.print_response(
"My favorite Thai dish is massaman curry.",
session_id=SESSION_ID,
)
# Second turn
agent.print_response(
"How do I make my favorite dish?",
session_id=SESSION_ID,
)

The agent retrieves the most relevant recipe chunks from your knowledge base on each turn. Because both calls use the same session_id value, Agno also retrieves data from the prior response. Agno retrieves the session metadata from the agno_sessions collection and the message content from the agno_runs collection. If you omit session_id or pass a different value on the second call, Agno starts a new session and the agent has no record of the first turn.

Para ejecutar el archivo main.py, ejecute el siguiente comando desde su directorio agno-mongodb-project:

python main.py

Si el comando se ejecuta correctamente, el resultado se parecerá al siguiente:

INFO Connected to MongoDB successfully.
INFO Creating collection 'agent_knowledge'.
INFO Creating search index 'vector_index_1'.
INFO Search index 'vector_index_1' is ready.
INFO Search index 'vector_index_1' created successfully.
INFO Adding content from URL https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf
INFO Upserting 14 documents
# Output from the vector_db.search() call
[Recipes] INGREDIENTS (One serving) 150 grams chicken, cut into bite-size pieces 50 grams
[Recipes] Thai SELECT Exotic, Healthy, Delicious Dining-Thai Style Thai food has rapidly g
[Recipes] Directions: 1. Roughly pound the garlic with bird's eye chilies in a mortar. Add
# Output from the agent.print_response() calls
┏━ Message ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ My favorite Thai dish is massaman curry. ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
┏━ Response (gpt-4o) ────────────────────────────────────────────┓
┃ Great choice — I found a recipe in the knowledge base for ┃
┃ Massaman Gai (Massaman Curry with Chicken and Potatoes). ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
┏━ Message ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ How do I make my favorite dish? ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
┏━ Response (gpt-4o) ────────────────────────────────────────────┓
┃ Here's how to make Massaman Gai (Massaman Curry with Chicken ┃
┃ and Potatoes) from the knowledge base: ┃
┃ **Ingredients** ┃
┃ - 300 grams chicken rump ┃
┃ - 80 grams Massaman curry paste ┃
┃ - 100 grams coconut cream ┃
┃ - 300 grams coconut milk ┃
┃ - 250 grams chicken stock ┃
┃ - 50 grams roasted peanuts ┃
┃ - 200 grams potatoes, chopped into large chunks ┃
┃ - 100 grams onion, chopped into large chunks ┃
┃ ... ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

To learn more about the MongoVectorDb and MongoDb classes, including their full parameter and method reference, see Integrate MongoDB with the Agno Framework.

To learn more about the MongoDB Vector Search index that Agno creates on your collection, see Create a MongoDB Vector Search Index.