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

Integrar MongoDB con el framework Agno

You can integrate MongoDB with Agno, an open-source Python framework for building multi-modal AI agents. Agno provides two MongoDB integrations:

  • Base de datos vectorial que almacena la base de conocimientos de su agente y la recupera mediante la búsqueda vectorial de MongoDB.

  • Base de datos de sesión y memoria que almacena de forma persistente las sesiones de los agentes, la memoria de los usuarios, las métricas y las ejecuciones de evaluación en sus colecciones de MongoDB.

Puedes usar cualquiera de las integraciones por separado, o puedes usar ambas en el mismo agente.

To complete a tutorial that configures Agno to use MongoDB, see Get Started with the MongoDB Agno Integration.

Agno requiere Python v3.9 o posterior. Para instalar las últimas versiones de Agno y PyMongo, ejecute el siguiente comando:

pip install agno pymongo

Los ejemplos de esta página utilizan modelos de OpenAI, que Agno usa por defecto. Para instalar la biblioteca cliente de OpenAI, ejecute el siguiente comando:

pip install openai

The Custom configuration examples on this page use Voyage AI embeddings. To install the Voyage AI client library, run the following command:

pip install voyageai

Antes de ejecutar los ejemplos de esta página, configure las siguientes variables de entorno:

  • Connection string: Set MONGODB_URI to the connection string for your MongoDB deployment.

  • Model API key: Set OPENAI_API_KEY or VOYAGE_API_KEY to the API key for your model provider.

The MongoVectorDb class implements the Agno vector database interface with MongoDB Vector Search. To give an agent semantic search over your documents, pass an instance of this class to the vector_db parameter of an Agno Knowledge object, then pass that object to the knowledge parameter of your agent.

Importante

Nombres de clases de MongoDB

Agno names both MongoDB classes MongoDb, but imports them from different modules. Import the vector database class from agno.vectordb.mongodb and the database class from agno.db.mongo. To avoid a name collision, Agno also exports the vector database class as MongoVectorDb. The examples on this page use that alias.

Select the Basic initialization tab to view a minimal configuration example, or select the Custom configuration tab to see how to configure the integration with custom settings.

Para inicializar la base de datos vectorial, especifique la colección que almacena sus incrustaciones y su cadena de conexión a MongoDB. El siguiente ejemplo crea una base de conocimiento, agrega un documento y otorga a un agente acceso a los datos:

import os
from agno.agent import Agent
from agno.knowledge.knowledge import Knowledge
from agno.vectordb.mongodb import MongoVectorDb
vector_db = MongoVectorDb(
collection_name="agent_knowledge",
db_url=os.environ["MONGODB_URI"],
database="agno",
)
knowledge = Knowledge(vector_db=vector_db)
knowledge.insert(
name="Recipes",
url="https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf",
)
agent = Agent(knowledge=knowledge, search_knowledge=True)

El siguiente ejemplo habilita la búsqueda híbrida, utiliza Voyage AI para generar incrustaciones en lugar de la opción predeterminada de OpenAI y especifica un nombre de índice de MongoDB Vector Search:

import os
from agno.agent import Agent
from agno.knowledge.embedder.voyageai import VoyageAIEmbedder
from agno.knowledge.knowledge import Knowledge
from agno.vectordb.mongodb import MongoVectorDb
from agno.vectordb.search import SearchType
embedder = VoyageAIEmbedder(
id="voyage-4-large",
dimensions=1024,
api_key=os.environ["VOYAGE_API_KEY"],
request_params={"output_dimension": 1024},
)
vector_db = MongoVectorDb(
collection_name="agent_knowledge",
db_url=os.environ["MONGODB_URI"],
database="agno",
embedder=embedder,
search_type=SearchType.hybrid,
hybrid_vector_weight=0.7,
hybrid_keyword_weight=0.3,
search_index_name="agno_vector_index",
)
knowledge = Knowledge(vector_db=vector_db)
agent = Agent(knowledge=knowledge, search_knowledge=True)

If you specify an embedder, Agno uses the number of dimensions that the embedder produces when it creates the MongoDB Vector Search index. The request_params dictionary passes provider-specific keyword arguments to the embedding call. For Voyage AI, output_dimension controls the size of the returned vector for models that support variable dimensions.

When you create a Knowledge object, Agno verifies whether the collection already exists. If it doesn't, Agno creates the collection and the MongoDB Vector Search index. If the collection exists, Agno doesn't check whether the index exists, even if you deleted it separately.

Tras crear el índice, Agno espera hasta que este aparezca en la colección. Sin embargo, no verifica el estado del índice, por lo que una consulta que se ejecute inmediatamente después puede no devolver ningún resultado mientras se termina de crear el índice.

Utilice estos parámetros para configurar la base de datos de vectores.

The MongoVectorDb class accepts the following parameters:

Parameter
Necesidad
Descripción

collection_name

Requerido

El nombre de la colección que almacena sus documentos y sus elementos incrustados.

db_url

Opcional

La cadena de conexión para la implementación de MongoDB. Se establece en mongodb://localhost:27017/ por defecto. Para obtener más información sobre cómo encontrar su cadena de conexión, consulte Conéctese a un clúster a través de las librerías de cliente.

client

Opcional

An existing MongoClient instance. If you specify this parameter, Agno ignores db_url.

database

Opcional

The name of the database that holds the collection. Defaults to agno.

embedder

Opcional

The embedding model that Agno uses to embed your documents and queries. Defaults to OpenAIEmbedder().

distance_metric

Opcional

The similarity function that the MongoDB Vector Search index uses. Only the default value, Distance.cosine, is currently supported.

search_type

Opcional

The retrieval strategy. Accepts SearchType.vector or SearchType.hybrid. Defaults to SearchType.vector.

hybrid_vector_weight

Opcional

The weight that hybrid search applies to semantic results. Defaults to 0.5.

hybrid_keyword_weight

Opcional

The weight that hybrid search applies to keyword results. Defaults to 0.5.

hybrid_rank_constant

Opcional

The constant that hybrid search adds to each rank before it computes the reciprocal rank fusion score. Defaults to 60.

search_index_name

Opcional

The name of the MongoDB Vector Search index on your collection. Defaults to vector_index_1.

wait_until_index_ready_in_seconds

Opcional

Whether Agno waits, after creating the MongoDB Vector Search index, for the index name to appear in the collection's search indexes. Set this parameter to a positive number to wait, or to None to skip the wait. Asynchronous methods use the value as a timeout, in seconds. Defaults to 3.

wait_after_insert_in_seconds

Opcional

The time, in seconds, that Agno waits after it inserts documents. Defaults to 3.

max_pool_size

Opcional

The maximum number of connections in the driver connection pool. Defaults to 100.

retry_writes

Opcional

Whether the driver retries supported write operations. Defaults to True.

cosmos_compatibility

Opcional

Whether Agno creates indexes in the Azure Cosmos DB for MongoDB vCore format instead of the MongoDB Vector Search format. Defaults to False.

name, description, id

Opcional

The identifying metadata for the vector database instance. If you don't specify id, Agno derives it from the connection string, database name, and collection name.

The Knowledge class calls the following methods when you add content to a knowledge base or when an agent searches it. Call these methods directly only if you manage documents outside of a Knowledge object.

To limit a write or search operation to one user's documents, pass a user_id value to the operation method.

Método
Descripción

search(query, limit, filters, min_score, user_id)

Embeds query and returns up to limit matching documents. If you set search_type to SearchType.hybrid, Agno also runs a keyword search and merges the two result sets. The filters parameter accepts a dictionary of metadata filters. If you pass a list of Agno filter expressions instead, Agno logs a warning and applies no filters because the MongoDB integration doesn't support them.

insert(content_hash, documents, filters, user_id)

Embeds each document in documents and inserts the documents into your collection. Agno derives each document's _id value from a hash of the document content.

upsert(content_hash, documents, filters, user_id)

Replaces the documents that share content_hash, then inserts the documents in documents. Use this method to update a document whose content changed.

delete()

Elimina todos los documentos de tu colección, pero conserva la colección y su índice de búsqueda vectorial de MongoDB.

delete_by_id(id)

Deletes the document with the specified _id value.

delete_by_name(name)

Deletes the documents with the specified name value.

delete_by_metadata(metadata)

Deletes the documents whose meta_data field matches the specified key-value pairs.

drop()

Descarga tu colección y su índice de búsqueda vectorial de MongoDB.

exists()

Returns True if your collection exists.

get_count()

Devuelve el número de documentos en tu colección.

Tip

Métodos asíncronos

Los siguientes métodos descritos en la tabla anterior tienen cada uno un método asíncrono correspondiente:

  • search(): Usar async_search()

  • insert(): Use async_insert()

  • upsert(): Use async_upsert()

  • drop(): Use async_drop()

  • exists(): Use async_exists()

The MongoDb class in the agno.db.mongo module implements the Agno database interface. To persist an agent's sessions, user memories, metrics, and evaluation runs in MongoDB, pass an instance of this class to the db parameter of an Agent, Team, or Workflow object.

Select the Basic initialization tab to view a minimal configuration example, or select the Custom configuration tab to see how to configure the integration with custom settings.

Para inicializar la base de datos, especifique su cadena de conexión de MongoDB. El siguiente ejemplo crea un agente que almacena su historial de sesión en MongoDB e incluye dicho historial en el contexto del modelo:

import os
from agno.agent import Agent
from agno.db.mongo import MongoDb
db = MongoDb(db_url=os.environ["MONGODB_URI"])
agent = Agent(db=db, add_history_to_context=True)

El siguiente ejemplo especifica el nombre de la base de datos y los nombres de las colecciones que almacenan sesiones, recuerdos y métricas:

import os
from agno.agent import Agent
from agno.db.mongo import MongoDb
db = MongoDb(
db_url=os.environ["MONGODB_URI"],
db_name="agno_prod",
session_collection="agent_sessions",
memory_collection="agent_memories",
metrics_collection="agent_metrics",
)
agent = Agent(db=db, add_history_to_context=True)

Agno crea cada colección que configures la primera vez que escribe en ella.

Utilice estos parámetros para configurar la base de datos.

The MongoDb class accepts the following parameters:

Parameter
Necesidad
Descripción

db_url

Condicional

The connection string for your MongoDB deployment. Required if you don't specify db_client.

db_client

Condicional

An existing MongoClient instance. Required if you don't specify db_url. If you specify both, Agno ignores db_url.

db_name

Opcional

The name of the database that holds the collections. Defaults to agno.

session_collection

Opcional

The name of the collection that stores agent, team, and workflow sessions. Defaults to agno_sessions.

runs_collection

Opcional

The name of the collection that stores runs, with one document per run. Defaults to agno_runs. If you specify session_collection but not this parameter, Agno creates the name from your session collection name, such as agent_sessions_runs.

memory_collection

Opcional

The name of the collection that stores user memories. Defaults to agno_memories.

metrics_collection

Opcional

The name of the collection that stores aggregated usage metrics. Defaults to agno_metrics.

eval_collection

Opcional

The name of the collection that stores evaluation runs. Defaults to agno_eval_runs.

knowledge_collection

Opcional

The name of the collection that stores knowledge content metadata. Defaults to agno_knowledge.

traces_collection, spans_collection

Opcional

The names of the collections that store traces and spans. Default to agno_traces and agno_spans.

schedules_collection, schedule_runs_collection

Opcional

The names of the collections that store schedules and schedule runs. Default to agno_schedules and agno_schedule_runs.

learnings_collection

Opcional

The name of the collection that stores learnings. Defaults to agno_learnings.

id

Opcional

El identificador de la instancia de la base de datos. Si no especifica este parámetro, Agno lo deduce de la cadena de conexión y del nombre de la base de datos.

As your agent runs, Agno automatically reads from and writes to the session, memory, and metrics collections described in this section. Agno creates each collection the first time it's needed. You can also call methods directly on your MongoDb instance, such as the following:

  • upsert_session() and get_sessions() read and write sessions.

  • upsert_user_memory() Escribe en una única memoria de usuario.

  • get_metrics() Lee métricas de uso agregadas.

  • upsert_sessions() and upsert_memories() write many records in a single operation, such as when you migrate existing session history into MongoDB.

  • close() Libera la conexión del cliente. Llama a este método cuando tu aplicación se cierre.

The first time Agno creates your vector collection, it also creates an MongoDB Vector Search index on the collection. The index name is the value of the search_index_name parameter, which defaults to vector_index_1. You can also create or inspect this index manually. To learn more, see Create a MongoDB Vector Search Index.

The index uses the following definition, where numDimensions matches the number of dimensions that your embedder produces and similarity matches your distance_metric value:

{
"fields": [
{
"type": "vector",
"path": "embedding",
"numDimensions": 1536,
"similarity": "cosine"
},
{
"type": "filter",
"path": "user_id"
}
]
}

Agno indexes the user_id field as a filter field so that it can scope searches to a single end user's documents.

Hybrid search doesn't require a MongoDB Search index. Agno runs its keyword search as a regular expression query on the content field, then combines those results with the MongoDB Vector Search results by using reciprocal rank fusion.

Para obtener más información sobre cómo usar Agno con MongoDB, consulte los siguientes recursos: