# Create Api Key Source: https://docs.mielto.com/api-reference/api-keys/create-api-key api-reference/openapi.json post /api/v1/api-keys Create new API key. # Delete Api Key Source: https://docs.mielto.com/api-reference/api-keys/delete-api-key api-reference/openapi.json delete /api/v1/api-keys/{api_key_id} Delete API key. # Get Api Key Source: https://docs.mielto.com/api-reference/api-keys/get-api-key api-reference/openapi.json get /api/v1/api-keys/{api_key_id} Get API key by ID. # List Api Keys Source: https://docs.mielto.com/api-reference/api-keys/list-api-keys api-reference/openapi.json get /api/v1/api-keys Retrieve API keys. # Update Api Key Source: https://docs.mielto.com/api-reference/api-keys/update-api-key api-reference/openapi.json put /api/v1/api-keys/{api_key_id} Update API key. # Create Chunks Source: https://docs.mielto.com/api-reference/chunks/create-chunks api-reference/openapi.json post /api/v1/chunks/create Create chunks/embeddings from existing content. This endpoint processes uploaded content that was stored without ingestion (ingest=False) and creates vector embeddings for it. Args: request: CreateChunksRequest containing: - content_id: Content ID to process - reader: Reader to use ("native", "langchain", "markitdown", etc.) - force_rechunk: Whether to force re-chunking existing chunks Returns: CreateChunksResponse with processing results Examples: Create chunks for uploaded content: POST /chunks/create { "content_id": "content_123", "reader": "markitdown", "force_rechunk": false } Force re-chunk with different reader: POST /chunks/create { "content_id": "content_123", "reader": "langchain_pdfplumber", "force_rechunk": true } # Delete Chunk Source: https://docs.mielto.com/api-reference/chunks/delete-chunk api-reference/openapi.json delete /api/v1/chunks/{chunk_id} Delete a specific chunk. Args: chunk_id: ID of the chunk to delete Returns: Success message Examples: Delete a chunk: DELETE /chunks/chunk_123 # Delete Chunks Batch Source: https://docs.mielto.com/api-reference/chunks/delete-chunks-batch api-reference/openapi.json post /api/v1/chunks/delete Delete multiple chunks in a single request. Args: request: DeleteChunksRequest with chunk IDs to delete Returns: DeleteChunksResponse with deletion results Examples: Delete multiple chunks: POST /chunks/delete { "chunk_ids": ["chunk_123", "chunk_456", "chunk_789"] } # Delete Chunks By Content Source: https://docs.mielto.com/api-reference/chunks/delete-chunks-by-content api-reference/openapi.json delete /api/v1/chunks/content/{content_id} Delete all chunks associated with a specific content item. Args: content_id: ID of the content whose chunks should be deleted Returns: DeleteChunksResponse with deletion results Examples: Delete all chunks for a content: DELETE /chunks/content/content_123 # Get Chunk Source: https://docs.mielto.com/api-reference/chunks/get-chunk api-reference/openapi.json get /api/v1/chunks/{chunk_id} Get a specific chunk by ID. Args: chunk_id: ID of the chunk to retrieve include_embedding: If True, includes the embedding vector in response Returns: ChunkResponse with chunk details Examples: Get chunk without embedding: GET /chunks/chunk_123 Get chunk with embedding: GET /chunks/chunk_123?include_embedding=true # List Chunks Source: https://docs.mielto.com/api-reference/chunks/list-chunks api-reference/openapi.json get /api/v1/chunks List chunks with cursor-based pagination. Cursor-based pagination is more efficient than offset-based for large datasets: - Consistent results even when data changes - Better performance (no offset scanning) - No "missed items" when new chunks are added Args: collection_id: Optional filter by collection content_id: Optional filter by parent content cursor: Cursor from previous response for next page (None for first page) limit: Number of items to return (default: 50, max: 500) include_embedding: Include embedding vectors in response Returns: ChunksListResponse with chunks, next_cursor, and has_more flag Examples: First page of all chunks: GET /chunks?limit=50 Next page (using cursor from previous response): GET /chunks?cursor=chunk_xyz123&limit=50 List chunks for a specific collection: GET /chunks?collection_id=col_123&limit=50 Continue pagination for collection: GET /chunks?collection_id=col_123&cursor=chunk_abc456&limit=50 List chunks for specific content: GET /chunks?content_id=content_456&limit=20 List with embeddings: GET /chunks?collection_id=col_123&include_embedding=true&limit=10 # Update Chunk Source: https://docs.mielto.com/api-reference/chunks/update-chunk api-reference/openapi.json patch /api/v1/chunks/{chunk_id} Update a chunk's content or metadata. Args: chunk_id: ID of the chunk to update request: UpdateChunkRequest with fields to update Returns: ChunkResponse with updated chunk Examples: Update chunk content: PATCH /chunks/chunk_123 { "content": "Updated chunk text" } Update chunk metadata: PATCH /chunks/chunk_123 { "metadata": { "category": "important", "tags": ["updated"] } } Update both content and metadata: PATCH /chunks/chunk_123 { "content": "Updated text", "metadata": {"status": "reviewed"} } Note: Updating chunk content will regenerate the embedding vector. # Archive Collection Source: https://docs.mielto.com/api-reference/collections/archive-collection api-reference/openapi.json post /api/v1/collections/{collection_id}/archive Archive a collection. # Create Collection Source: https://docs.mielto.com/api-reference/collections/create-collection api-reference/openapi.json post /api/v1/collections Create new collection. # Delete Collection Source: https://docs.mielto.com/api-reference/collections/delete-collection api-reference/openapi.json delete /api/v1/collections/{collection_id} Delete collection. # Read Collection Source: https://docs.mielto.com/api-reference/collections/read-collection api-reference/openapi.json get /api/v1/collections/{collection_id} Get collection by ID. # Read Collections Source: https://docs.mielto.com/api-reference/collections/read-collections api-reference/openapi.json get /api/v1/collections Retrieve collections with pagination. Returns a paginated list of collections with filtering options. Args: skip: Number of records to skip (for pagination) limit: Maximum number of records to return status: Filter by collection status (e.g., 'active', 'archived') visibility: Filter by visibility ('public' or 'private') search: Search term for name or description tags: Comma-separated list of tags to filter by Returns: PaginatedResponse with collections and total count Examples: Get first page: GET /collections?skip=0&limit=20 Get second page: GET /collections?skip=20&limit=20 Filter by status: GET /collections?status=active&limit=50 Search collections: GET /collections?search=documents&limit=20 Filter by tags: GET /collections?tags=important,work&limit=50 # Search Collection Source: https://docs.mielto.com/api-reference/collections/search-collection api-reference/openapi.json post /api/v1/collections/search Search within a collection using knowledge search. Supports different search types: - fulltext: Traditional text-based search - semantic: Vector similarity search - hybrid: Combination of fulltext and semantic search # Update Collection Source: https://docs.mielto.com/api-reference/collections/update-collection api-reference/openapi.json put /api/v1/collections/{collection_id} Update collection. # Update Collection Stats Source: https://docs.mielto.com/api-reference/collections/update-collection-stats api-reference/openapi.json put /api/v1/collections/{collection_id}/stats Update collection statistics. # Compress Context Source: https://docs.mielto.com/api-reference/compression/compress-context api-reference/openapi.json post /api/v1/compress # Create Connection Source: https://docs.mielto.com/api-reference/connections/create-connection api-reference/openapi.json post /api/v1/connections Create a new connection with validation. This endpoint validates the provided credentials and configuration against the integration's requirements before creating the connection. **Validation includes:** - Required fields are present - Field types match expected types (email, url, etc.) - Values match validation patterns (regex) - Length constraints are met - OAuth credentials are valid (if applicable) **Example:** ```json { "label": "My Gmail Connection", "integration": "gmail", "integration_type": "connectors", "auth_method_id": "oauth2", "credentials": { "access_token": "ya29.a0...", "refresh_token": "1//0g...", "token_type": "Bearer", "expires_at": "2025-10-19T12:00:00Z" }, "config": {} } ``` **Error Response (validation failure):** ```json { "detail": { "message": "Connection validation failed", "errors": [ "Field 'API Key' is required", "Field 'Email' must be a valid email address" ] } } ``` # Delete Connection Source: https://docs.mielto.com/api-reference/connections/delete-connection api-reference/openapi.json delete /api/v1/connections/{connection_id} Delete a connection. # Get Connection Source: https://docs.mielto.com/api-reference/connections/get-connection api-reference/openapi.json get /api/v1/connections/{connection_id} Get a connection by ID. # Get Connection Stats Source: https://docs.mielto.com/api-reference/connections/get-connection-stats api-reference/openapi.json get /api/v1/connections/stats Get connection statistics. # Get Connections By Integration Source: https://docs.mielto.com/api-reference/connections/get-connections-by-integration api-reference/openapi.json get /api/v1/connections/integrations/{integration_type} Get connections by integration type. # Get Integration Requirements Source: https://docs.mielto.com/api-reference/connections/get-integration-requirements api-reference/openapi.json get /api/v1/connections/integrations/{integration_id}/requirements Get required fields and validation rules for an integration. This endpoint returns the fields required to create a connection for a specific integration, including field types, validation rules, and authentication method information. **Use this endpoint to:** - Understand what credentials are needed before creating a connection - Build dynamic forms for connection creation - Display helpful information to users about authentication requirements **Example:** ```bash GET /connections/integrations/gmail/requirements GET /connections/integrations/slack/requirements?auth_method_id=oauth2 ``` **Response:** ```json { "integration_id": "gmail", "auth_method": { "id": "oauth2", "name": "OAuth 2.0", "type": "oauth2", "description": "Secure authentication with Google account" }, "required_fields": [ { "key": "access_token", "label": "Access Token", "type": "password", "required": true, "secure": true, "validation": { "minLength": 20 } } ] } ``` # Get User Connections Source: https://docs.mielto.com/api-reference/connections/get-user-connections api-reference/openapi.json get /api/v1/connections/users/{user_id} Get connections owned by a specific user. # List Connections Source: https://docs.mielto.com/api-reference/connections/list-connections api-reference/openapi.json get /api/v1/connections List connections with optional filters. # Update Connection Source: https://docs.mielto.com/api-reference/connections/update-connection api-reference/openapi.json put /api/v1/connections/{connection_id} Update a connection. # Update Connection Status Source: https://docs.mielto.com/api-reference/connections/update-connection-status api-reference/openapi.json patch /api/v1/connections/{connection_id}/status Update connection status. # Validate Connection Requirements Source: https://docs.mielto.com/api-reference/connections/validate-connection-requirements api-reference/openapi.json post /api/v1/connections/validate Validate connection credentials without creating a connection. This endpoint allows you to validate credentials and configuration before attempting to create a connection. Useful for providing real-time validation feedback in forms. **Example:** ```bash POST /connections/validate?integration_id=gmail ``` **Request Body:** ```json { "credentials": { "api_key": "abc123", "email": "user@example.com" }, "config": {} } ``` **Success Response:** ```json { "valid": true, "errors": [] } ``` **Validation Error Response:** ```json { "valid": false, "errors": [ "Field 'API Key' must be at least 20 characters", "Field 'Email' must be a valid email address" ] } ``` # Upload Source: https://docs.mielto.com/api-reference/content-upload/upload api-reference/openapi.json post /api/v1/upload Upload content (files, URLs, or text) to a collection. Args: collection_id (str): Required. ID of the collection to upload to. file (UploadFile, optional): Single file to upload. files (List[UploadFile], optional): Multiple files to upload. content (str, optional): Direct text content to upload. urls (List[str], optional): List of URLs to download and upload. content_type (str, optional): Type of content - 'file', 'url', or 'text'. Default: 'file'. metadata (Dict[str, Any], optional): Additional metadata to attach to uploaded content. label (str, optional): Custom label for the content. description (str, optional): Description of the content. crawl (bool, optional): Whether to crawl linked content from URLs. Default: False. ingest (bool, optional): Whether to ingest content into vector database. Default: True. If False, only file metadata is stored. Use POST /v1/chunks/create to ingest later. reader (str, optional): Reader to use for processing files. Default: 'native'. Reader Parameter: Controls how uploaded files are processed. Supported formats: Provider Format: - 'native': Use native implementation (default, fastest) - 'langchain': Use LangChain readers for all files - 'markitdown': Use MarkItDown for universal conversion to markdown Provider + Type Format: - 'langchain_pdfplumber': LangChain with PDFPlumber (better OCR, tables) - 'langchain_pypdf': LangChain with PyPDF (faster for text-based PDFs) Specific Reader: - 'pdf', 'csv', 'docx', 'json', 'markdown', 'text' Returns: UploadResponse: Contains upload status, successful uploads, and any errors. - collection_id: ID of the collection - content_type: Type of content uploaded - uploads: List of successfully uploaded content - errors: List of failed uploads with error details - total_uploads: Total number attempted - successful_uploads: Number successful - failed_uploads: Number failed Examples: Upload a single file with native reader: POST /upload Form data: - file: document.pdf - collection_id: "my_docs" - reader: "native" Upload PowerPoint with MarkItDown (converts to markdown): POST /upload Form data: - file: presentation.pptx - collection_id: "presentations" - reader: "markitdown" Upload scanned PDF with better OCR: POST /upload Form data: - file: scanned.pdf - collection_id: "scans" - reader: "langchain_pdfplumber" Upload from URLs: POST /upload Form data: - urls: ["https://example.com/doc1.pdf", "https://example.com/doc2.pdf"] - collection_id: "web_docs" - content_type: "url" Upload direct text content: POST /upload Form data: - content: "This is my text content" - collection_id: "notes" - content_type: "text" - label: "Quick Note" Upload file without ingesting (metadata only): POST /upload Form data: - file: document.pdf - collection_id: "pending_docs" - ingest: false Note: Use POST /v1/chunks/create later to ingest content Raises: HTTPException: 403 if collection not accessible HTTPException: 400 if invalid parameters HTTPException: 500 if upload processing fails # Bulk Delete Contents Source: https://docs.mielto.com/api-reference/contents/bulk-delete-contents api-reference/openapi.json post /api/v1/contents/bulk/delete Delete multiple contents at once. Bulk deletion operation for removing multiple content items. Returns details about successful and failed deletions. Args: content_ids: List of content IDs to delete Returns: Summary of deletion results Example: POST /contents/bulk/delete Body: { "content_ids": ["con_123", "con_456", "con_789"] } Response: { "deleted": 2, "failed": 1, "deleted_ids": ["con_123", "con_456"], "failed_ids": ["con_789"], "errors": { "con_789": "Content not found" } } # Bulk Update Status Source: https://docs.mielto.com/api-reference/contents/bulk-update-status api-reference/openapi.json patch /api/v1/contents/bulk/update-status Update status for multiple contents at once. Bulk status update operation useful for batch processing workflows. Args: content_ids: List of content IDs to update new_status: New status value (new, processing, completed, failed) status_message: Optional status message Returns: Summary of update results Example: PATCH /contents/bulk/update-status Body: { "content_ids": ["con_123", "con_456"], "new_status": "completed", "status_message": "Processing finished successfully" } # Delete Content Source: https://docs.mielto.com/api-reference/contents/delete-content api-reference/openapi.json delete /api/v1/contents/{content_id} Delete content by ID. Permanently removes a content item from the knowledge base. This action cannot be undone. Associated vectors and chunks may also be removed depending on the storage configuration. Args: content_id: The unique identifier for the content Returns: No content (204) on success Example: DELETE /contents/con_abc123xyz Raises: 404: If content not found 403: If not authorized to delete # Get Content Source: https://docs.mielto.com/api-reference/contents/get-content api-reference/openapi.json get /api/v1/contents/{content_id} Get a single content by ID. Returns detailed information about a specific content item including metadata, file information, and processing status. Args: content_id: The unique identifier for the content Returns: Content details Example: GET /contents/con_abc123xyz Raises: 404: If content not found or not accessible # Get Content Chunks Source: https://docs.mielto.com/api-reference/contents/get-content-chunks api-reference/openapi.json get /api/v1/contents/{content_id}/chunks Get all chunks/vectors for a specific content in a collection. Returns all the chunks (text segments with embeddings) that were created when processing this content in the specified collection. This is useful for: - Debugging vector search results - Analyzing how content was chunked - Inspecting chunk metadata - Retrieving embeddings for analysis **Important:** The same content can have different chunks in different collections (due to different chunking strategies, embedding models, etc.), so `collection_id` is required to ensure you get the correct set of chunks. Args: content_id: The unique identifier for the content collection_id: The collection ID (ensures correct chunks are retrieved) include_embeddings: Whether to include embedding vectors (default: false to save bandwidth) Returns: ContentChunksResponse with list of chunks and metadata Example: GET /contents/con_abc123/chunks?collection_id=col_xyz789&include_embeddings=false Response: { "content_id": "con_abc123", "collection_id": "col_xyz789", "chunks": [ { "id": "vec_chunk1", "content_id": "con_abc123", "content": "First chunk text...", "embedding": null, // or array if include_embeddings=true "meta_data": {"page": 1, "section": "intro"}, "collection_id": "col_xyz789", "workspace_id": "wsp_123" }, ... ], "total_chunks": 42, "includes_embeddings": false } Raises: 404: If content not found or collection not accessible 500: If error retrieving chunks # List Contents Source: https://docs.mielto.com/api-reference/contents/list-contents api-reference/openapi.json get /api/v1/contents List contents with pagination and filtering. Returns a paginated list of contents from the workspace's knowledge base. Args: collection_id: Filter by specific collection status: Filter by processing status skip: Number of records to skip (for pagination) limit: Maximum number of records to return sort_by: Field to sort by (created_at, updated_at, name, size) sort_order: Order direction (asc or desc) Returns: PaginatedResponse with contents and total count Examples: Get first page: GET /contents?skip=0&limit=20 Get second page: GET /contents?skip=20&limit=20 Filter by collection: GET /contents?collection_id=col_123&limit=50 Filter by status: GET /contents?status=completed&limit=50 Sort by size: GET /contents?sort_by=size&sort_order=desc&limit=20 Combined filters: GET /contents?collection_id=col_123&status=completed&skip=0&limit=20 # Update Content Source: https://docs.mielto.com/api-reference/contents/update-content api-reference/openapi.json put /api/v1/contents/{content_id} Update content metadata and status. Allows updating content fields such as name, description, metadata, and processing status. The content data itself cannot be modified. Args: content_id: The unique identifier for the content content_update: Fields to update Returns: Updated content Example: PATCH /contents/con_abc123xyz Body: { "name": "Updated Document Name", "description": "New description", "metadata": {"category": "important"}, "status": "completed" } Raises: 404: If content not found 400: If validation fails # Update Content Source: https://docs.mielto.com/api-reference/contents/update-content-1 api-reference/openapi.json patch /api/v1/contents/{content_id} Update content metadata and status. Allows updating content fields such as name, description, metadata, and processing status. The content data itself cannot be modified. Args: content_id: The unique identifier for the content content_update: Fields to update Returns: Updated content Example: PATCH /contents/con_abc123xyz Body: { "name": "Updated Document Name", "description": "New description", "metadata": {"category": "important"}, "status": "completed" } Raises: 404: If content not found 400: If validation fails # Archive Conversation Source: https://docs.mielto.com/api-reference/conversations/archive-conversation api-reference/openapi.json patch /api/v1/conversations/{conversation_id}/archive Archive a conversation. # Create Conversation Source: https://docs.mielto.com/api-reference/conversations/create-conversation api-reference/openapi.json post /api/v1/conversations Create a new conversation. The workspace_id will be automatically set from the current session context. # Delete Conversation Source: https://docs.mielto.com/api-reference/conversations/delete-conversation api-reference/openapi.json delete /api/v1/conversations/{conversation_id} Delete a conversation. # End Conversation Source: https://docs.mielto.com/api-reference/conversations/end-conversation api-reference/openapi.json patch /api/v1/conversations/{conversation_id}/end End a conversation. # Get Conversation Source: https://docs.mielto.com/api-reference/conversations/get-conversation api-reference/openapi.json get /api/v1/conversations/{conversation_id} Get a specific conversation by ID. # List Conversations Source: https://docs.mielto.com/api-reference/conversations/list-conversations api-reference/openapi.json get /api/v1/conversations List conversations in the current workspace with cursor-based pagination. Cursor-based pagination is more efficient for large datasets and handles data changes better than offset-based pagination. Args: cursor: Cursor from previous response for next page (None for first page) limit: Number of items per page (default: 50, max: 100) sort_by: Field to sort by (default: 'updated_at') sort_order: Sort order - 'asc' or 'desc' (default: 'desc') status: Optional status filter search: Optional search term for title user_id: Optional user_id filter collection_id: Optional collection_id filter Returns: ConversationListResponse with conversations, next_cursor, and has_more flag Examples: First page: GET /conversations?limit=50 Next page (using cursor from previous response): GET /conversations?cursor=conv_xyz123&limit=50 Sort by created_at ascending: GET /conversations?sort_by=created_at&sort_order=asc Filter by status with sorting: GET /conversations?status=active&sort_by=updated_at&sort_order=desc # Update Conversation Source: https://docs.mielto.com/api-reference/conversations/update-conversation api-reference/openapi.json put /api/v1/conversations/{conversation_id} Update a conversation. # Create Credential Source: https://docs.mielto.com/api-reference/credentials/create-credential api-reference/openapi.json post /api/v1/credentials Create a new credential. # Delete Credential Source: https://docs.mielto.com/api-reference/credentials/delete-credential api-reference/openapi.json delete /api/v1/credentials/{credential_id} Delete a credential. # Get Credential Source: https://docs.mielto.com/api-reference/credentials/get-credential api-reference/openapi.json get /api/v1/credentials/{credential_id} Get a credential by ID. # List Credentials Source: https://docs.mielto.com/api-reference/credentials/list-credentials api-reference/openapi.json get /api/v1/credentials List credentials with optional filters. # Update Credential Source: https://docs.mielto.com/api-reference/credentials/update-credential api-reference/openapi.json put /api/v1/credentials/{credential_id} Update a credential. # Get All Resources Source: https://docs.mielto.com/api-reference/integrations/get-all-resources api-reference/openapi.json get /api/v1/integrations/all Get all available resources (integrations, models, vector stores). This endpoint returns everything in one response. Optionally filter by resource type. **Examples:** ``` GET /integrations/all GET /integrations/all?resource_type=model GET /integrations/all?resource_type=vector_store ``` **Response (all types):** ```json { "integrations": [...], "models": [...], "vector_stores": [...], "summary": { "total_integrations": 11, "total_models": 33, "total_vector_stores": 17 } } ``` # Get Auth Methods Source: https://docs.mielto.com/api-reference/integrations/get-auth-methods api-reference/openapi.json get /api/v1/integrations/{integration_id}/auth-methods Get available authentication methods for an integration. Returns simplified authentication configuration without sensitive details. Useful for building authentication UI flows. **Example:** ``` GET /integrations/gmail/auth-methods GET /integrations/slack/auth-methods ``` # Get Integration Source: https://docs.mielto.com/api-reference/integrations/get-integration api-reference/openapi.json get /api/v1/integrations/{integration_id} Get detailed information about a specific integration. Returns the complete integration definition including: - Authentication methods and OAuth configuration - Available actions and triggers - Webhook configuration - Rate limits and retry policies **Example:** ``` GET /integrations/gmail GET /integrations/github ``` # Get Integration Actions Source: https://docs.mielto.com/api-reference/integrations/get-integration-actions api-reference/openapi.json get /api/v1/integrations/{integration_id}/actions Get available actions for an integration. Actions represent operations that can be performed with the integration, such as sending an email, creating an issue, or uploading a file. **Example:** ``` GET /integrations/gmail/actions GET /integrations/jira/actions ``` # Get Integration Triggers Source: https://docs.mielto.com/api-reference/integrations/get-integration-triggers api-reference/openapi.json get /api/v1/integrations/{integration_id}/triggers Get available triggers for an integration. Triggers are events that can initiate workflows, such as receiving a new email, creating an issue, or completing a task. **Example:** ``` GET /integrations/gmail/triggers GET /integrations/github/triggers ``` # Get Model Source: https://docs.mielto.com/api-reference/integrations/get-model api-reference/openapi.json get /api/v1/integrations/providers/{provider_id}/models/{model_id} Get detailed information about a specific model. Returns complete model specifications including capabilities, pricing, context window, and parameter options. **Example:** ``` GET /integrations/providers/openai/models/gpt-4o GET /integrations/providers/anthropic/models/claude-3-5-sonnet-20241022 ``` # Get Model Provider Source: https://docs.mielto.com/api-reference/integrations/get-model-provider api-reference/openapi.json get /api/v1/integrations/providers/{provider_id} Get detailed information about a specific model provider. Returns the complete provider definition including available models, authentication methods, and compatibility information. **Example:** ``` GET /integrations/providers/openai GET /integrations/providers/anthropic ``` # Get Provider Models Source: https://docs.mielto.com/api-reference/integrations/get-provider-models api-reference/openapi.json get /api/v1/integrations/providers/{provider_id}/models Get available models for a specific provider. Returns a list of models with their specifications, pricing, and capability information. **Example:** ``` GET /integrations/providers/openai/models GET /integrations/providers/google/models?model_type=chat GET /integrations/providers/openai/models?model_type=embedding ``` # List All Model Providers Source: https://docs.mielto.com/api-reference/integrations/list-all-model-providers api-reference/openapi.json get /api/v1/integrations/models List all available model providers from the codebase. This endpoint scans the mielto/models directory and returns all available LLM providers that can be used in the system. **Example:** ``` GET /integrations/models ``` **Response:** ```json { "models": [ { "id": "openai", "name": "OpenAI", "type": "llm", "path": "mielto.models.openai" }, { "id": "anthropic", "name": "Anthropic", "type": "llm", "path": "mielto.models.anthropic" } ], "total": 33 } ``` # List All Vector Stores Source: https://docs.mielto.com/api-reference/integrations/list-all-vector-stores api-reference/openapi.json get /api/v1/integrations/vector-stores List all available vector stores from the codebase. This endpoint scans the mielto/vectordb directory and returns all available vector store implementations that can be used in the system. **Example:** ``` GET /integrations/vector-stores ``` **Response:** ```json { "vector_stores": [ { "id": "pgvector", "name": "PostgreSQL (pgvector)", "type": "vector_store", "path": "mielto.vectordb.pgvector" }, { "id": "pineconedb", "name": "Pinecone", "type": "vector_store", "path": "mielto.vectordb.pineconedb" } ], "total": 17 } ``` # List Integrations Source: https://docs.mielto.com/api-reference/integrations/list-integrations api-reference/openapi.json get /api/v1/integrations List available integrations with optional filtering. Returns a list of integration definitions including their capabilities, authentication methods, and configuration options. Can optionally filter by type with the `type` parameter. **Examples:** ``` GET /integrations?category=communication&status=active GET /integrations?tags=messaging,email GET /integrations?type=integration GET /integrations?type=model GET /integrations?type=vector_store GET /integrations?type=all ``` # List Model Providers Source: https://docs.mielto.com/api-reference/integrations/list-model-providers api-reference/openapi.json get /api/v1/integrations/providers List available model providers. Returns a list of LLM and embedding model providers with their capabilities, models, and authentication requirements. **Example:** ``` GET /integrations/providers GET /integrations/providers?has_embedding=true ``` # API Reference Source: https://docs.mielto.com/api-reference/introduction Complete API documentation for Mielto - Context Layer for AI ## Welcome to Mielto API Mielto provides a comprehensive API for building AI-powered applications with advanced context management, knowledge collections, and conversation handling. Our REST API enables you to integrate intelligent context layers into your applications. ## Base URL All API requests should be made to: ``` https://api.mielto.com/api/v1 ``` ## Key Features Enterprise API key authentication with role-based access control Personal context storage with AI-powered semantic search Knowledge base management with search capabilities AI conversation management and context handling ## Authentication Mielto uses API key authentication for secure, scalable access to all endpoints. API keys provide persistent authentication without the need for login sessions. ```bash theme={null} Authorization: Bearer YOUR_API_KEY ``` ### Getting Started 1. **Create** an API key via `/api/v1/api-keys` 2. **Include** the API key in the Authorization header as a Bearer token 3. **Secure** your API key - treat it like a password 4. **Manage** keys programmatically with create, update, and delete endpoints # Create Memory Source: https://docs.mielto.com/api-reference/memory/create-memory api-reference/openapi.json post /api/v1/memories Create a new memory for the current user. This endpoint allows users to create personal memories that can be used for context in future conversations and interactions. # Delete Memory Source: https://docs.mielto.com/api-reference/memory/delete-memory api-reference/openapi.json delete /api/v1/memories/{memory_id} Delete a memory. Only the memory owner can delete their memories. This action cannot be undone. # Get Memory Source: https://docs.mielto.com/api-reference/memory/get-memory api-reference/openapi.json get /api/v1/memories/{memory_id} Get a specific memory by ID. Returns the memory details if it belongs to the current user. # List Memories Source: https://docs.mielto.com/api-reference/memory/list-memories api-reference/openapi.json get /api/v1/memories List memories with cursor-based pagination. Cursor-based pagination is more efficient for large datasets and handles data changes better than offset-based pagination. Args: user_id: Optional user ID to filter memories cursor: Cursor from previous response for next page (None for first page) limit: Number of items per page (default: 50, max: 100) sort_by: Field to sort by (default: 'updated_at') sort_order: Sort order - 'asc' or 'desc' (default: 'desc') Returns: MemoryListResponse with memories and next_cursor Examples: First page: GET /memories?user_id=user_123&limit=50 Next page (using cursor from previous response): GET /memories?user_id=user_123&cursor=mem_xyz123&limit=50 Sort by updated_at descending (most recent first): GET /memories?user_id=user_123&sort_by=updated_at&sort_order=desc Sort by memory_id ascending: GET /memories?user_id=user_123&sort_by=memory_id&sort_order=asc # Replace Memory Source: https://docs.mielto.com/api-reference/memory/replace-memory api-reference/openapi.json post /api/v1/memories/{memory_id}/replace Replace an existing memory with new content. This completely replaces the memory content while preserving the memory ID. Unlike update, this requires all fields to be provided and replaces the entire memory. The original creation timestamp is preserved, but updated_at is set to now. Only the memory owner can replace their memories. # Search Memories Source: https://docs.mielto.com/api-reference/memory/search-memories api-reference/openapi.json post /api/v1/memories/search Search memories for the current user. Supports different retrieval methods: - agentic: AI-powered semantic search (default) - last_n: Most recent memories - first_n: Oldest memories # Update Memory Source: https://docs.mielto.com/api-reference/memory/update-memory api-reference/openapi.json put /api/v1/memories/{memory_id} Update an existing memory. Only the memory owner can update their memories. Partial updates are supported - only provided fields will be updated. # Create Message Source: https://docs.mielto.com/api-reference/messages/create-message api-reference/openapi.json post /api/v1/messages Create one or more messages. Accepts either: - Single message object: { message object } - Array of message objects: [ { message object }, ... ] The workspace_id will be automatically set from the current session context. # Delete Message Source: https://docs.mielto.com/api-reference/messages/delete-message api-reference/openapi.json delete /api/v1/messages/{message_id} Delete a message. # Get Conversation Message Stats Source: https://docs.mielto.com/api-reference/messages/get-conversation-message-stats api-reference/openapi.json get /api/v1/conversations/{conversation_id}/stats Get message statistics for a conversation. # Get Message Source: https://docs.mielto.com/api-reference/messages/get-message api-reference/openapi.json get /api/v1/messages/{message_id} Get a specific message by ID. # List Messages Source: https://docs.mielto.com/api-reference/messages/list-messages api-reference/openapi.json get /api/v1/messages List messages in the current workspace. # Update Message Source: https://docs.mielto.com/api-reference/messages/update-message api-reference/openapi.json put /api/v1/messages/{message_id} Update a message. # Initiate Oauth Source: https://docs.mielto.com/api-reference/oauth/initiate-oauth api-reference/openapi.json post /api/v1/oauth/initiate Initiate an OAuth authentication flow. This endpoint generates an authorization URL that the user should visit to grant permissions to the integration. **Flow:** 1. Call this endpoint with the integration ID 2. Redirect the user to the returned `auth_url` 3. User grants permissions on the provider's website 4. Provider redirects back to the callback URL with a code 5. Callback handler exchanges code for tokens and creates connection **Example:** ```json POST /oauth/initiate { "integration_id": "gmail", "auth_method_id": "oauth2", "scopes": [ "https://www.googleapis.com/auth/gmail.readonly", "https://www.googleapis.com/auth/gmail.send" ] } ``` **Response:** ```json { "auth_url": "https://accounts.google.com/o/oauth2/v2/auth?...", "state": "abc123...", "integration_id": "gmail" } ``` # Oauth Success Source: https://docs.mielto.com/api-reference/oauth/oauth-success api-reference/openapi.json get /api/v1/oauth/success OAuth success page. This is a placeholder page shown after successful OAuth authorization. In production, this should redirect to the frontend application. # Refresh Oauth Token Source: https://docs.mielto.com/api-reference/oauth/refresh-oauth-token api-reference/openapi.json post /api/v1/oauth/refresh/{connection_id} Refresh an OAuth access token for a connection. This endpoint refreshes expired OAuth tokens using the refresh token. It updates the credential with the new tokens. **Example:** ``` POST /oauth/refresh/conn_abc123 ``` **Response:** ```json { "status": "success", "connection_id": "conn_abc123", "expires_at": "2025-10-19T12:00:00Z" } ``` # Chat Completions Endpoint Source: https://docs.mielto.com/api-reference/openai-compatible-endpoint/chat-completions-endpoint api-reference/openapi.json post /api/v1/chat/completions OpenAI chat completions endpoint with intelligent context injection. This endpoint provides: - Unlimited context through intelligent memory management - Automatic retrieval of relevant memories and knowledge - Streaming support for real-time responses - Tool calling and function execution - Cost optimization through context optimization - Diagnostic headers for monitoring and debugging Headers: - x-user-id: Unique user identifier for memory retrieval - x-conversation-id: Conversation identifier for context continuity - x-session-id: Session identifier for session-based context - x-workspace-id: Workspace identifier for multi-tenant support - x-collection-ids: JSON array of collection IDs for knowledge retrieval # Responses Endpoint Source: https://docs.mielto.com/api-reference/openai-compatible-endpoint/responses-endpoint api-reference/openapi.json post /api/v1/responses Legacy OpenAI responses endpoint with context injection and memory management. This endpoint provides: - Automatic context injection from memories and knowledge - Memory management and retrieval - Cost optimization through intelligent context management - Zero code changes required for existing OpenAI clients # Mielto - Context Layer for AI Source: https://docs.mielto.com/index Unlimited context through intelligent memory management ## Welcome to Mielto Mielto provides a comprehensive API for building AI-powered applications with advanced context management, knowledge collections, and conversation handling. Explore our comprehensive API documentation and start building. Explore our comprehensive API documentation and start building. ## Core Features Unlock the full potential of AI with intelligent context management. Break through token limits with intelligent memory management and context injection. Store and retrieve personal context with AI-powered semantic search. Organize and search through knowledge bases with advanced retrieval. Drop-in replacement for OpenAI API with enhanced context capabilities. ## API Capabilities Everything you need to build intelligent AI applications. Enterprise-grade API key authentication with granular access control. Manage AI conversations with full context preservation. Upload and process documents, images, and web content. Store and search personal context with AI-powered retrieval. ## Ready to Get Started? Explore all endpoints, authentication, and integration examples. # Quickstart Source: https://docs.mielto.com/quickstart Get started with Mielto - Context Layer for AI in 3 simple steps ## Get started with Mielto API Build AI applications with unlimited context and intelligent memory management in minutes. ### Step 1: Authentication Create your Mielto account to get started: Sign up After registration, create an API key for your applications: 1. Login to get your access token 2. Create an API key via the API Keys dashboard 3. Use this key in your application headers Store your API key securely - it provides full access to your workspace! ### Step 2: Create your first collection Set up a collection for your knowledge base: ```bash theme={null} curl -X POST https://api.mielto.com/api/v1/collections \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Company Knowledge", "description": "Internal company information and procedures" }' ``` Quickly call this endpoint from clients: ```typescript theme={null} // TypeScript/JavaScript async function createCollection() { const response = await fetch('https://api.mielto.com/api/v1/collections', { method: 'POST', headers: { 'Authorization': `Bearer ${process.env.MIELTO_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ name: 'Company Knowledge', description: 'Internal company information and procedures', }), }); if (!response.ok) throw new Error(`Request failed: ${response.status}`); return await response.json(); } ``` ```python theme={null} # Python import os, requests def create_collection(): res = requests.post( 'https://api.mielto.com/api/v1/collections', headers={ 'Authorization': f"Bearer {os.environ.get('MIELTO_API_KEY')}", 'Content-Type': 'application/json', }, json={ 'name': 'Company Knowledge', 'description': 'Internal company information and procedures', }, timeout=30, ) res.raise_for_status() return res.json() ``` ### Step 3: Create your first memory Create a memory to store important context: ```bash theme={null} curl -X POST https://api.mielto.com/api/v1/memories \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "user_id": "your-user-id", "memory": "I prefer concise responses and work in software development", "topics": ["preferences", "work"] }' ``` ### Step 4: Start a conversation with context Now use Mielto's OpenAI-compatible endpoint with automatic context injection: ```bash theme={null} curl -X POST https://api.mielto.com/api/v1/chat/completions \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -H "x-user-id: your-user-id" \ -d '{ "model": "gpt-4", "messages": [ {"role": "user", "content": "Help me write a function"} ] }' ``` SDK examples (set base URL, API key, and headers): ```python theme={null} # Python (openai>=1.0.0) from openai import OpenAI client = OpenAI( api_key="YOUR_API_KEY", base_url="https://api.mielto.com/api/v1", default_headers={ "x-user-id": "your-user-id", }, ) resp = client.chat.completions.create( model="gpt-4", messages=[{"role": "user", "content": "Help me write a function"}], ) print(resp.choices[0].message.content) ``` ```typescript theme={null} // TypeScript/JavaScript (openai@^4) import OpenAI from 'openai'; const client = new OpenAI({ apiKey: process.env.MIELTO_API_KEY!, baseURL: 'https://api.mielto.com/api/v1', defaultHeaders: { 'x-user-id': 'your-user-id', }, }); const resp = await client.chat.completions.create({ model: 'gpt-4', messages: [{ role: 'user', content: 'Help me write a function' }], }); console.log(resp.choices[0].message?.content); ``` Mielto automatically injects relevant memories and knowledge! ## Next steps Now that you've created your first memory and collection, explore these powerful features: Upload files, documents, and web content to your collections. Perform semantic, keyword, or hybrid search across your knowledge. Create and manage AI conversations with full context preservation. Drop-in replacement for OpenAI with unlimited context. Bring existing user conversations and messages into Mielto. **Need help?** Check our [complete API reference](/api-reference/introduction) for detailed endpoint documentation. # Quickstart - BYOM (Bring Your Own Messages) Source: https://docs.mielto.com/quickstart-conversations Get started with Mielto - Bringing your own existing messages and conversations Bring existing user conversations and messages into Mielto. **Need help?** Check our [complete API reference](/api-reference/introduction) for detailed endpoint documentation. **Need help?** Check our [complete API reference](/api-reference/introduction) for detailed endpoint documentation.
## Quickstart - Conversations & Messages ### 1) Create a conversation for a user ```bash theme={null} curl -X POST https://api.mielto.com/api/v1/conversations \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "user_id": "your-user-id", "title": "Onboarding conversation" }' ``` The response includes `id` (e.g., `conv_01234567890abcdef`). Use this as `conversation_id` for messages. ### 2) Upload existing messages You can post messages to `https://api.mielto.com/api/v1/messages`. Include either `Authorization: Bearer {apikey}` or `x-api-key: {apikey}` and a body with messages in the `content` field: ```json theme={null} [ { "role": "user", "created_at": "2025-06-10T10:28:06.658Z", "sender_id": "326166736", "content": "message" }, { "role": "assistant", "created_at": "2025-06-10T10:28:11.64Z", "sender_id": "326166736", "content": "message body" } ] ``` How `conversation_id` works: 1. Required in practice: although optional in some schemas, provide `conversation_id` when creating messages. 2. Flow: * API receives `conversation_id` in the create payload * The handler assigns this `conversation_id` to each created message Example API requests: ```bash theme={null} curl -X POST https://api.mielto.com/api/v1/messages \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "conversation_id": "conv_01234567890abcdef", "content": { "content": "Hello, how are you?", "role": "user", "message_type": "text" }, "enable_memories": false }' ``` Or with multiple messages: ```bash theme={null} curl -X POST https://api.mielto.com/api/v1/messages \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "conversation_id": "conv_01234567890abcdef", "content": [ { "content": "Hello, how are you?", "role": "user", "message_type": "text", "sender_id": "your_applications_id_of_user_who_sent_message" }, { "content": "I\'m doing well, thank you!", "role": "assistant", "message_type": "text", "sender_id": "user_or_agent_id" } ], "enable_memories": true }' ``` `conversation_id` groups messages, supports deduplication, enforces sender consistency within a conversation, and is used when embedding conversation content into collections. ### 3) Call the completions endpoint with a user\_id You can use the OpenAI SDKs by setting the base URL to `https://api.mielto.com/api/v1`, passing your API key from the Mielto dashboard, and including the `x-user-id` header with your internal user ID. ```bash theme={null} curl -X POST https://api.mielto.com/api/v1/chat/completions \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -H "x-user-id: your-user-id" \ -d '{ "model": "gpt-4", "messages": [ {"role": "user", "content": "Summarize this conversation."} ] }' ``` ```python theme={null} # Python (openai>=1.0.0) from openai import OpenAI client = OpenAI( api_key="YOUR_API_KEY", base_url="https://api.mielto.com/api/v1", default_headers={ "x-user-id": "your-user-id", }, ) resp = client.chat.completions.create( model="gpt-4", messages=[{"role": "user", "content": "Summarize this conversation."}], ) print(resp.choices[0].message.content) ``` ```typescript theme={null} // TypeScript/JavaScript (openai@^4) import OpenAI from 'openai'; const client = new OpenAI({ apiKey: process.env.MIELTO_API_KEY!, baseURL: 'https://api.mielto.com/api/v1', defaultHeaders: { 'x-user-id': 'your-user-id', }, }); const resp = await client.chat.completions.create({ model: 'gpt-4', messages: [{ role: 'user', content: 'Summarize this conversation.' }], }); console.log(resp.choices[0].message?.content); ``` # Quickstart - Use Mielto via Tool Calling Source: https://docs.mielto.com/quickstart-memory-context-tool-calling Enable Mielto via tool calling in agents/LLM calls ## Tool Calling with Mielto Enable your AI agents to interact with Mielto's API endpoints directly through tool calling (function calling). This allows LLMs to search collections, manage memories, and access knowledge bases autonomously. ### Architecture Overview When using tool calling with Mielto: * **OpenAI Client**: Handles LLM chat completions and tool call requests * **Mielto Client**: Executes the actual API calls to Mielto endpoints (collections, memories, etc.) when tools are invoked The LLM receives tool definitions and decides when to call them. When a tool is requested, your application executes the corresponding Mielto API call and returns the result to the LLM. ### What is Tool Calling? Tool calling allows LLMs to request execution of specific functions during a conversation. When you define Mielto endpoints as tools, the LLM can: * Search your knowledge collections * Retrieve user memories * Create new memories * List available collections * And more - all without manual intervention ### Step 1: Define Mielto Endpoints as Tools Define your tools using OpenAI's function calling format. Here are common Mielto endpoints as tools: ```python theme={null} # Python - Define Mielto tools MIELTO_TOOLS = [ { "type": "function", "function": { "name": "search_collections", "description": "Search within a knowledge collection using semantic, keyword, or hybrid search. Use this to find relevant information from your knowledge base.", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "The search query string" }, "collection_id": { "type": "string", "description": "ID of the collection to search in" }, "search_type": { "type": "string", "enum": ["vector", "keyword", "hybrid"], "description": "Type of search: vector (semantic), keyword (traditional), or hybrid (recommended)", "default": "hybrid" }, "max_results": { "type": "integer", "description": "Maximum number of results to return (1-100)", "default": 10, "minimum": 1, "maximum": 100 } }, "required": ["query", "collection_id"] } } }, { "type": "function", "function": { "name": "search_memories", "description": "Search through user memories using AI-powered semantic search. Use this to retrieve relevant personal context and preferences.", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "Search query to find relevant memories" }, "user_id": { "type": "string", "description": "User ID to search memories for" }, "max_results": { "type": "integer", "description": "Maximum number of memories to return", "default": 10, "minimum": 1, "maximum": 100 } }, "required": ["query", "user_id"] } } }, { "type": "function", "function": { "name": "create_memory", "description": "Create a new personal memory for a user. Use this to store important context, preferences, or information about the user.", "parameters": { "type": "object", "properties": { "user_id": { "type": "string", "description": "User ID to create the memory for" }, "memory": { "type": "string", "description": "The memory content to store" }, "topics": { "type": "array", "items": {"type": "string"}, "description": "Optional topics/tags for categorizing the memory" } }, "required": ["user_id", "memory"] } } }, { "type": "function", "function": { "name": "list_collections", "description": "List all available knowledge collections. Use this to discover what collections are available before searching.", "parameters": { "type": "object", "properties": { "limit": { "type": "integer", "description": "Maximum number of collections to return", "default": 100, "minimum": 1, "maximum": 1000 }, "status": { "type": "string", "enum": ["active", "archived"], "description": "Filter by collection status" } }, "required": [] } } }, { "type": "function", "function": { "name": "list_memories", "description": "List all memories for a user. Use this to retrieve a user's stored memories.", "parameters": { "type": "object", "properties": { "user_id": { "type": "string", "description": "User ID to list memories for" }, "limit": { "type": "integer", "description": "Maximum number of memories to return", "default": 100, "minimum": 1, "maximum": 1000 } }, "required": ["user_id"] } } } ] ``` ```typescript theme={null} // TypeScript - Define Mielto tools const MIELTO_TOOLS = [ { type: "function" as const, function: { name: "search_collections", description: "Search within a knowledge collection using semantic, keyword, or hybrid search. Use this to find relevant information from your knowledge base.", parameters: { type: "object", properties: { query: { type: "string", description: "The search query string" }, collection_id: { type: "string", description: "ID of the collection to search in" }, search_type: { type: "string", enum: ["vector", "keyword", "hybrid"], description: "Type of search: vector (semantic), keyword (traditional), or hybrid (recommended)", default: "hybrid" }, max_results: { type: "integer", description: "Maximum number of results to return (1-100)", default: 10, minimum: 1, maximum: 100 } }, required: ["query", "collection_id"] } } }, { type: "function" as const, function: { name: "search_memories", description: "Search through user memories using AI-powered semantic search. Use this to retrieve relevant personal context and preferences.", parameters: { type: "object", properties: { query: { type: "string", description: "Search query to find relevant memories" }, user_id: { type: "string", description: "User ID to search memories for" }, max_results: { type: "integer", description: "Maximum number of memories to return", default: 10, minimum: 1, maximum: 100 } }, required: ["query", "user_id"] } } }, { type: "function" as const, function: { name: "create_memory", description: "Create a new personal memory for a user. Use this to store important context, preferences, or information about the user.", parameters: { type: "object", properties: { user_id: { type: "string", description: "User ID to create the memory for" }, memory: { type: "string", description: "The memory content to store" }, topics: { type: "array", items: { type: "string" }, description: "Optional topics/tags for categorizing the memory" } }, required: ["user_id", "memory"] } } }, { type: "function" as const, function: { name: "list_collections", description: "List all available knowledge collections. Use this to discover what collections are available before searching.", parameters: { type: "object", properties: { limit: { type: "integer", description: "Maximum number of collections to return", default: 100, minimum: 1, maximum: 1000 }, status: { type: "string", enum: ["active", "archived"], description: "Filter by collection status" } }, required: [] } } }, { type: "function" as const, function: { name: "list_memories", description: "List all memories for a user. Use this to retrieve a user's stored memories.", parameters: { type: "object", properties: { user_id: { type: "string", description: "User ID to list memories for" }, limit: { type: "integer", description: "Maximum number of memories to return", default: 100, minimum: 1, maximum: 1000 } }, required: ["user_id"] } } } ]; ``` ### Step 2: Implement Tool Execution Functions Create functions that execute the actual API calls when tools are invoked: ```python theme={null} # Python - Tool execution functions import os import requests from typing import Dict, Any MIELTO_API_KEY = os.environ.get("MIELTO_API_KEY") MIELTO_BASE_URL = "https://api.mielto.com/api/v1" def execute_tool(tool_name: str, arguments: Dict[str, Any]) -> Dict[str, Any]: """Execute a Mielto API tool call""" headers = { "Authorization": f"Bearer {MIELTO_API_KEY}", "Content-Type": "application/json" } if tool_name == "search_collections": response = requests.post( f"{MIELTO_BASE_URL}/collections/search", headers=headers, json=arguments ) response.raise_for_status() return response.json() elif tool_name == "search_memories": # Note: Adjust endpoint based on actual API structure response = requests.post( f"{MIELTO_BASE_URL}/memories/search", headers=headers, json=arguments ) response.raise_for_status() return response.json() elif tool_name == "create_memory": response = requests.post( f"{MIELTO_BASE_URL}/memories", headers=headers, json=arguments ) response.raise_for_status() return response.json() elif tool_name == "list_collections": response = requests.get( f"{MIELTO_BASE_URL}/collections", headers=headers, params=arguments ) response.raise_for_status() return response.json() elif tool_name == "list_memories": response = requests.get( f"{MIELTO_BASE_URL}/memories", headers=headers, params=arguments ) response.raise_for_status() return response.json() else: raise ValueError(f"Unknown tool: {tool_name}") ``` ```typescript theme={null} // TypeScript - Tool execution functions const MIELTO_API_KEY = process.env.MIELTO_API_KEY!; const MIELTO_BASE_URL = "https://api.mielto.com/api/v1"; async function executeTool( toolName: string, arguments: Record ): Promise { const headers = { Authorization: `Bearer ${MIELTO_API_KEY}`, "Content-Type": "application/json", }; switch (toolName) { case "search_collections": const searchResponse = await fetch( `${MIELTO_BASE_URL}/collections/search`, { method: "POST", headers, body: JSON.stringify(arguments), } ); if (!searchResponse.ok) throw new Error(`Request failed: ${searchResponse.status}`); return await searchResponse.json(); case "search_memories": const memSearchResponse = await fetch( `${MIELTO_BASE_URL}/memories/search`, { method: "POST", headers, body: JSON.stringify(arguments), } ); if (!memSearchResponse.ok) throw new Error(`Request failed: ${memSearchResponse.status}`); return await memSearchResponse.json(); case "create_memory": const createResponse = await fetch(`${MIELTO_BASE_URL}/memories`, { method: "POST", headers, body: JSON.stringify(arguments), }); if (!createResponse.ok) throw new Error(`Request failed: ${createResponse.status}`); return await createResponse.json(); case "list_collections": const listResponse = await fetch( `${MIELTO_BASE_URL}/collections?${new URLSearchParams(arguments as any).toString()}`, { method: "GET", headers, } ); if (!listResponse.ok) throw new Error(`Request failed: ${listResponse.status}`); return await listResponse.json(); case "list_memories": const memListResponse = await fetch( `${MIELTO_BASE_URL}/memories?${new URLSearchParams(arguments as any).toString()}`, { method: "GET", headers, } ); if (!memListResponse.ok) throw new Error(`Request failed: ${memListResponse.status}`); return await memListResponse.json(); default: throw new Error(`Unknown tool: ${toolName}`); } } ``` ### Step 3: Use Tools in Chat Completions Now integrate tool calling into your chat completions. The OpenAI client handles LLM interactions, while tool execution functions call Mielto's API endpoints: ```python theme={null} # Python - Complete example with tool calling from openai import OpenAI import json import os # Initialize OpenAI client for LLM calls openai_client = OpenAI( api_key=os.environ.get("OPENAI_API_KEY"), # Your OpenAI API key ) # Mielto API configuration for tool execution MIELTO_API_KEY = os.environ.get("MIELTO_API_KEY") MIELTO_BASE_URL = "https://api.mielto.com/api/v1" def chat_with_tools(user_id: str, user_message: str, conversation_history: list = None): """Chat with tool calling enabled""" messages = conversation_history or [] messages.append({"role": "user", "content": user_message}) # Initial request with tools response = openai_client.chat.completions.create( model="gpt-5", messages=messages, tools=MIELTO_TOOLS, tool_choice="auto" # Let the model decide when to use tools ) message = response.choices[0].message messages.append(message) # Handle tool calls while message.tool_calls: for tool_call in message.tool_calls: tool_name = tool_call.function.name tool_args = json.loads(tool_call.function.arguments) # Execute the tool using Mielto API tool_result = execute_tool(tool_name, tool_args) # Add tool result to conversation messages.append({ "role": "tool", "tool_call_id": tool_call.id, "content": json.dumps(tool_result) }) # Get next response with tool results response = openai_client.chat.completions.create( model="gpt-5", messages=messages, tools=MIELTO_TOOLS ) message = response.choices[0].message messages.append(message) return message.content # Example usage result = chat_with_tools( user_id="user_123", user_message="Search my knowledge base for information about API authentication" ) print(result) ``` ```typescript theme={null} // TypeScript - Complete example with tool calling import OpenAI from "openai"; // Initialize OpenAI client for LLM calls const openaiClient = new OpenAI({ apiKey: process.env.OPENAI_API_KEY!, // Your OpenAI API key }); // Mielto API configuration for tool execution const MIELTO_API_KEY = process.env.MIELTO_API_KEY!; const MIELTO_BASE_URL = "https://api.mielto.com/api/v1"; async function chatWithTools( userId: string, userMessage: string, conversationHistory: any[] = [] ): Promise { const messages: any[] = [...conversationHistory]; messages.push({ role: "user", content: userMessage }); // Initial request with tools let response = await openaiClient.chat.completions.create({ model: "gpt-5", messages, tools: MIELTO_TOOLS, tool_choice: "auto", // Let the model decide when to use tools }); let message = response.choices[0].message; messages.push(message); // Handle tool calls while (message.tool_calls && message.tool_calls.length > 0) { for (const toolCall of message.tool_calls) { const toolName = toolCall.function.name; const toolArgs = JSON.parse(toolCall.function.arguments); // Execute the tool using Mielto API const toolResult = await executeTool(toolName, toolArgs); // Add tool result to conversation messages.push({ role: "tool", tool_call_id: toolCall.id, content: JSON.stringify(toolResult), }); } // Get next response with tool results response = await openaiClient.chat.completions.create({ model: "gpt-5", messages, tools: MIELTO_TOOLS, }); message = response.choices[0].message; messages.push(message); } return message.content || ""; } // Example usage const result = await chatWithTools( "user_123", "Search my knowledge base for information about API authentication" ); console.log(result); ``` ### Complete Example: Agent with Memory and Knowledge Search Here's a complete example that combines everything: ```python theme={null} # Python - Complete agent example import os import json import requests from openai import OpenAI # Configuration OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY") # Your OpenAI API key MIELTO_API_KEY = os.environ.get("MIELTO_API_KEY") # Your Mielto API key MIELTO_BASE_URL = "https://api.mielto.com/api/v1" USER_ID = "user_123" # Initialize OpenAI client for LLM calls openai_client = OpenAI(api_key=OPENAI_API_KEY) # Mielto API headers for tool execution mielto_headers = { "Authorization": f"Bearer {MIELTO_API_KEY}", "Content-Type": "application/json" } def execute_mielto_tool(tool_name: str, arguments: dict): """Execute Mielto API calls""" if tool_name == "search_collections": response = requests.post( f"{MIELTO_BASE_URL}/collections/search", headers=mielto_headers, json=arguments ) return response.json() elif tool_name == "search_memories": response = requests.post( f"{MIELTO_BASE_URL}/memories/search", headers=mielto_headers, json=arguments ) return response.json() elif tool_name == "create_memory": response = requests.post( f"{MIELTO_BASE_URL}/memories", headers=mielto_headers, json=arguments ) return response.json() # Add other tools as needed... def agent_chat(user_message: str): """Agent that can use Mielto tools""" messages = [ { "role": "system", "content": "You are a helpful assistant with access to the user's knowledge base and memories. Use the available tools to search for information when needed." }, {"role": "user", "content": user_message} ] max_iterations = 5 iteration = 0 while iteration < max_iterations: # Call OpenAI for LLM completion response = openai_client.chat.completions.create( model="gpt-5", messages=messages, tools=MIELTO_TOOLS, tool_choice="auto" ) message = response.choices[0].message messages.append(message) if not message.tool_calls: break # Execute all tool calls for tool_call in message.tool_calls: tool_name = tool_call.function.name tool_args = json.loads(tool_call.function.arguments) # Ensure user_id is included where needed if "user_id" in tool_args or tool_name in ["search_memories", "create_memory", "list_memories"]: if "user_id" not in tool_args: tool_args["user_id"] = USER_ID tool_result = execute_mielto_tool(tool_name, tool_args) messages.append({ "role": "tool", "tool_call_id": tool_call.id, "content": json.dumps(tool_result) }) iteration += 1 return messages[-1].content # Example usage result = agent_chat("What information do we have about authentication? Also check my memories.") print(result) ``` ### Best Practices **Tool Selection**: Only include tools that are relevant to your use case. Too many tools can confuse the model. **Error Handling**: Always implement proper error handling for tool execution. If a tool fails, include the error message in the tool response so the LLM can handle it appropriately. **API Keys**: Never expose your Mielto API key in client-side code. Always execute tool calls server-side. ### Next Steps * Explore more [API endpoints](/api-reference/introduction) to add as tools * Learn about [collections](/api-reference/collections/search) for knowledge management * Discover [memory management](/api-reference/memories/search) capabilities * Check out [conversation management](/api-reference/conversations/list) for context continuity