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.
Empezar
To complete a tutorial that configures Agno to use MongoDB, see Get Started with the MongoDB Agno Integration.
Instalación
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
Variables de entorno
Antes de ejecutar los ejemplos de esta página, configure las siguientes variables de entorno:
Connection string: Set
MONGODB_URIto the connection string for your MongoDB deployment.Model API key: Set
OPENAI_API_KEYorVOYAGE_API_KEYto the API key for your model provider.
Base de datos de vectores
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.
The MongoVectorDb class accepts the following parameters:
Parameter | Necesidad | Descripción |
|---|---|---|
| Requerido | El nombre de la colección que almacena sus documentos y sus elementos incrustados. |
| Opcional | La cadena de conexión para la implementación de MongoDB. Se establece en |
| Opcional | An existing |
| Opcional | The name of the database that holds the collection. Defaults to |
| Opcional | The embedding model that Agno uses to embed your documents and queries. Defaults to |
| Opcional | The similarity function that the MongoDB Vector Search index uses. Only the default value, |
| Opcional | The retrieval strategy. Accepts |
| Opcional | The weight that hybrid search applies to semantic results. Defaults to |
| Opcional | The weight that hybrid search applies to keyword results. Defaults to |
| Opcional | The constant that hybrid search adds to each rank before it computes the reciprocal rank fusion score. Defaults to |
| Opcional | The name of the MongoDB Vector Search index on your collection. Defaults to |
| 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 |
| Opcional | The time, in seconds, that Agno waits after it inserts documents. Defaults to |
| Opcional | The maximum number of connections in the driver connection pool. Defaults to |
| Opcional | Whether the driver retries supported write operations. Defaults to |
| Opcional | Whether Agno creates indexes in the Azure Cosmos DB for MongoDB vCore format instead of the MongoDB Vector Search format. Defaults to |
| Opcional | The identifying metadata for the vector database instance. If you don't specify |
Métodos de bases de datos vectoriales
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 |
|---|---|
| Embeds |
| Embeds each document in |
| Replaces the documents that share |
| Elimina todos los documentos de tu colección, pero conserva la colección y su índice de búsqueda vectorial de MongoDB. |
| Deletes the document with the specified |
| Deletes the documents with the specified |
| Deletes the documents whose |
| Descarga tu colección y su índice de búsqueda vectorial de MongoDB. |
| Returns |
| 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(): Usarasync_search()insert(): Useasync_insert()upsert(): Useasync_upsert()drop(): Useasync_drop()exists(): Useasync_exists()
Base de datos de sesión y memoria
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.
The MongoDb class accepts the following parameters:
Parameter | Necesidad | Descripción |
|---|---|---|
| Condicional | The connection string for your MongoDB deployment. Required if you don't specify |
| Condicional | An existing |
| Opcional | The name of the database that holds the collections. Defaults to |
| Opcional | The name of the collection that stores agent, team, and workflow sessions. Defaults to |
| Opcional | The name of the collection that stores runs, with one document per run. Defaults to |
| Opcional | The name of the collection that stores user memories. Defaults to |
| Opcional | The name of the collection that stores aggregated usage metrics. Defaults to |
| Opcional | The name of the collection that stores evaluation runs. Defaults to |
| Opcional | The name of the collection that stores knowledge content metadata. Defaults to |
| Opcional | The names of the collections that store traces and spans. Default to |
| Opcional | The names of the collections that store schedules and schedule runs. Default to |
| Opcional | The name of the collection that stores learnings. Defaults to |
| 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()andget_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()andupsert_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.
índice de búsqueda
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.
Recursos adicionales
Para obtener más información sobre cómo usar Agno con MongoDB, consulte los siguientes recursos:
Agno MongoDB Vector Store reference
Agno MongoDB Database reference
Agno Knowledge documentation
Agno GitHub repository