### Install and Start Moorcheh Client Source: https://docs.moorcheh.ai/on-prem/prerequisites Install the `moorcheh-client` package and then start the Moorcheh server. The `configure` step is optional as `moorcheh up` can handle initial configuration interactively. ```bash pip install moorcheh-client moorcheh configure # optional; first moorcheh up can do this interactively moorcheh up ``` -------------------------------- ### Install Moorcheh Client and Start Server Source: https://docs.moorcheh.ai/on-prem/python-client/getting-started Install the Python client library and start the Moorcheh server. This is the initial setup required before interacting with the API. ```bash pip install moorcheh-client moorcheh up ``` -------------------------------- ### Quick Start Commands Source: https://docs.moorcheh.ai/integrations/chat-boilerplate/overview Commands to create, navigate, install dependencies, and start the development server for the chat boilerplate. ```bash npx moorcheh-chat-boilerplate cd your-project-name npm install npm run dev ``` -------------------------------- ### Install and Start Moorcheh Server Source: https://docs.moorcheh.ai/on-prem/quickstart Install the Moorcheh client and start the server. The first run prompts for an embedding provider. Use `moorcheh status` to check the server status. ```bash pip install moorcheh-client moorcheh up # first run: choose embedding provider (Ollama, OpenAI, or Cohere) moorcheh status ``` -------------------------------- ### Install and Start Moorcheh Edge Source: https://docs.moorcheh.ai/on-edge/prerequisites Installs the Moorcheh Edge CLI and Python SDK, then starts the edge server container. Ensure Python and Docker are installed first. ```bash pip install moorcheh-edge moorcheh-edge up ``` -------------------------------- ### Start Moorcheh On-Prem with Configuration Source: https://docs.moorcheh.ai/on-prem/embedding-providers Start Moorcheh On-Prem. If no configuration file exists, this command will run the interactive setup wizard first. ```bash moorcheh up ``` -------------------------------- ### Install and Run Moorcheh On-Prem Source: https://docs.moorcheh.ai/on-prem/introduction Install the moorcheh-client, configure settings (optional), start the server, and check its status. ```bash pip install moorcheh-client moorcheh configure # optional; first moorcheh up can prompt instead moorcheh up moorcheh status ``` -------------------------------- ### Start MCP Server with npm Source: https://docs.moorcheh.ai/integrations/mcp/setup Start the Moorcheh MCP server using the npm start script after completing the setup. ```bash npm start ``` -------------------------------- ### Install Moorcheh On-Edge CLI and SDK Source: https://docs.moorcheh.ai/on-edge/changelog Install the `moorcheh-edge` package, start the on-edge API server, and check its status. ```bash pip install moorcheh-edge moorcheh-edge up moorcheh-edge status ``` -------------------------------- ### Start Moorcheh with saved config or interactive wizard Source: https://docs.moorcheh.ai/on-prem/cli/runtime/up This command starts the Moorcheh server using existing configuration. If `~/.moorcheh/config.json` is not found, it will launch an interactive setup wizard. ```bash # Use saved config (or interactive wizard) moorcheh up ``` -------------------------------- ### Start Moorcheh with specific cloud provider and no wizard Source: https://docs.moorcheh.ai/on-prem/cli/runtime/up This command starts the Moorcheh server using OpenAI embeddings without launching the interactive setup wizard. It requires specifying the provider, model, API key, and disabling configuration prompts. ```bash # Cloud provider without wizard moorcheh up --embedding-provider openai --embedding-model text-embedding-3-small --embedding-api-key "$OPENAI_API_KEY" --no-configure ``` -------------------------------- ### Install Project Dependencies Source: https://docs.moorcheh.ai/integrations/chat-boilerplate/installation Navigate to your project directory and run this command to install all necessary dependencies. ```bash cd your-project-name npm install ``` -------------------------------- ### Example GET Request for Namespaces (Python) Source: https://docs.moorcheh.ai/api-reference/introduction This Python script shows how to make a GET request to retrieve namespaces using the requests library. Ensure you have the 'requests' library installed. ```python import requests headers = { 'x-api-key': 'your-api-key-here', 'Content-Type': 'application/json' } response = requests.get( 'https://api.moorcheh.ai/v1/namespaces', headers=headers ) ``` -------------------------------- ### End-to-End Jina Query Example Source: https://docs.moorcheh.ai/integrations/jina/overview Demonstrates a complete query process using Jina, including setting parameters and printing results. Ensure Jina is installed and configured. ```python from jina import DocumentArray # Assuming NAMESPACE and query_vec are defined elsewhere # For example: # NAMESPACE = "my_namespace" # query_vec = DocumentArray(...) results = client.query( query=query_vec, top_k=5, kiosk_mode=True, threshold=0.15, ) print(f"namespace={NAMESPACE} total_results={len(results.get('results', []))}") print("=" * 120) for idx, r in enumerate(results.get("results", []), start=1): print_result(idx, r) ``` -------------------------------- ### Example Request to List Namespaces Source: https://docs.moorcheh.ai/api-reference/introduction This example demonstrates how to make a GET request to the /namespaces endpoint to retrieve a list of all namespaces, including the necessary authentication header. ```APIDOC ## GET /v1/namespaces ### Description Retrieves a list of all available namespaces. ### Method GET ### Endpoint /v1/namespaces ### Parameters #### Headers - **x-api-key** (string) - Required - Your API key for authentication. - **Content-Type** (string) - Required - Must be set to `application/json`. ### Request Example ```bash curl -X GET "https://api.moorcheh.ai/v1/namespaces" \ -H "x-api-key: your-api-key-here" \ -H "Content-Type: application/json" ``` ### Response #### Success Response (200) - **namespaces** (array) - A list of namespace objects. - **name** (string) - The name of the namespace. - **type** (string) - The type of the namespace (e.g., 'text', 'vector'). - **created_at** (string) - The timestamp when the namespace was created. #### Response Example ```json { "namespaces": [ { "name": "my-namespace", "type": "text", "created_at": "2023-10-27T10:00:00Z" } ] } ``` ``` -------------------------------- ### Start Development Server Source: https://docs.moorcheh.ai/integrations/chat-boilerplate/installation Run this command to start the local development server. Access your application at http://localhost:3000. ```bash npm run dev ``` -------------------------------- ### Run Interactive Configuration Source: https://docs.moorcheh.ai/on-prem/cli/runtime/configure Initiates the interactive setup wizard for embedding providers, models, and API keys. This is useful for first-time setup or when changing configurations. ```bash moorcheh configure ``` -------------------------------- ### Install Boilerplate Globally Source: https://docs.moorcheh.ai/integrations/chat-boilerplate/installation Install the boilerplate globally to create new projects. After global installation, use the command to initiate a new project. ```bash npm install -g moorcheh-chat-boilerplate ``` ```bash moorcheh-chat-boilerplate ``` -------------------------------- ### List Files Asynchronous Example Source: https://docs.moorcheh.ai/python-sdk/files/list-files This asynchronous example demonstrates how to list files using `AsyncMoorchehClient`. It prints the file count and file details. ```python import asyncio from moorcheh_sdk import AsyncMoorchehClient async def main(): async with AsyncMoorchehClient() as client: status = await client.documents.list_files(namespace_name="my-faq-documents") print(status.get("file_count"), status.get("files")) asyncio.run(main()) ``` -------------------------------- ### Install Dependencies Source: https://docs.moorcheh.ai/integrations/cohere/overview Install the necessary Python libraries for Cohere and Moorcheh integration. ```bash pip install moorcheh-sdk cohere ``` -------------------------------- ### Example GET Request for Namespaces (JavaScript) Source: https://docs.moorcheh.ai/api-reference/introduction This JavaScript snippet demonstrates how to fetch namespaces using the Fetch API. It includes the required API key and content type headers. ```javascript const headers = { 'x-api-key': 'your-api-key-here', 'Content-Type': 'application/json' }; fetch('https://api.moorcheh.ai/v1/namespaces', { method: 'GET', headers: headers }); ``` -------------------------------- ### Configure or Start Moorcheh Server Source: https://docs.moorcheh.ai/on-prem/prerequisites Use these commands to configure Moorcheh or start it with an interactive wizard if configuration is missing. The wizard helps set up embedding providers. ```bash moorcheh configure # or moorcheh up # interactive wizard if config.json is missing ``` -------------------------------- ### Install LlamaIndex and Moorcheh SDK Source: https://docs.moorcheh.ai/integrations/llamaindex/overview Install the necessary Python packages for LlamaIndex and Moorcheh SDK using pip. ```bash pip install llama_index pip install moorcheh_sdk ``` -------------------------------- ### Create Virtual Environment and Install Moorcheh Edge CLI/SDK Source: https://docs.moorcheh.ai/on-edge/guides/arduino-uno-q Installs Python's virtual environment package, creates a new virtual environment named 'moorcheh-venv', activates it, and then installs the 'moorcheh-edge' package. This is necessary to avoid PEP 668 warnings on Debian-based systems like the Arduino UNO Q. ```bash sudo apt-get update && sudo apt-get install -y python3-venv python3 -m venv ~/moorcheh-venv source ~/moorcheh-venv/bin/activate pip install moorcheh-edge ``` -------------------------------- ### No Namespaces Yet Response Example Source: https://docs.moorcheh.ai/on-prem/api-references/namespaces/list Example of a successful response when no namespaces have been created yet. The 'namespaces' field will be an empty array. ```json { "namespaces": [] } ``` -------------------------------- ### Install Moorcheh Python SDK Source: https://docs.moorcheh.ai/ Install the Moorcheh Python SDK using pip. This is the first step to using the SDK for semantic search. ```bash pip install moorcheh-sdk ``` -------------------------------- ### Install Dependencies Source: https://docs.moorcheh.ai/integrations/gemini/overview Install the necessary Python packages for Google Gemini and Moorcheh integration. Ensure you are using Python 3.9+. ```bash pip install google-genai moorcheh-sdk python-dotenv ``` -------------------------------- ### Install moorcheh-edge CLI Source: https://docs.moorcheh.ai/on-edge/cli/introduction Install the moorcheh-edge CLI using pip. This is the first step to using the command-line interface. ```bash pip install moorcheh-edge ``` -------------------------------- ### Complete Vector Upload Example Source: https://docs.moorcheh.ai/python-sdk/data/upload-vector Demonstrates creating a vector namespace with a specified dimension and then uploading generated vectors. This example uses numpy for random vector generation. ```python from moorcheh_sdk import MoorchehClient import numpy as np with MoorchehClient() as client: # Create a vector namespace with dimension 768 client.namespaces.create( namespace_name="product-embeddings", type="vector", vector_dimension=768 ) # Generate or load your vectors (example with random vectors) vectors = [] for i in range(10): # Your actual embedding generation code here vector = np.random.rand(768).tolist() # Example: 768-dimensional vector vectors.append({ "id": f"product_{i}", "vector": vector, "category": "electronics", "price": 99.99 + i * 10 }) # Upload vectors result = client.vectors.upload( namespace_name="product-embeddings", vectors=vectors ) print(f"Uploaded {len(vectors)} vectors") ``` -------------------------------- ### Example Usage of upload-vectors Command Source: https://docs.moorcheh.ai/on-edge/cli/upload-vectors This example demonstrates how to execute the upload-vectors command, specifying the local JSON file containing the vectors to be uploaded. ```bash moorcheh-edge upload-vectors --vectors-file payload.json ``` -------------------------------- ### Namespaces Response Example Source: https://docs.moorcheh.ai/on-prem/api-references/namespaces/list Example of a successful response when namespaces exist. Includes namespace name, type, vector dimension, item count, and creation time. ```json { "namespaces": [ { "namespace_name": "my-documents", "type": "text", "vector_dimension": null, "item_count": 42, "created_at": "2026-05-21T12:00:00.000Z" }, { "namespace_name": "my-embeddings", "type": "vector", "vector_dimension": 768, "item_count": 10, "created_at": "2026-05-21T12:05:00.000Z" } ] } ``` -------------------------------- ### Example CLI Usage Source: https://docs.moorcheh.ai/on-prem/cli/data/upload-vectors Demonstrates how to initiate a vector upload and how to check the job status. ```bash moorcheh upload-vectors --namespace-name my-embeddings --vectors-file vectors.json moorcheh upload-job-status --namespace-name my-embeddings --job-id ``` -------------------------------- ### Basic Moorcheh SDK Workflow Example Source: https://docs.moorcheh.ai/python-sdk/introduction A complete example demonstrating the basic workflow: creating a text namespace, uploading documents, performing a semantic search, generating an AI answer, and cleaning up by deleting the namespace. Uses the context manager for resource management. ```python import time from moorcheh_sdk import MoorchehClient # Use the context manager for automatic cleanup with MoorchehClient() as client: namespace = "sdk-quickstart-ns" # 1. Create a text namespace print(f"Creating namespace: {namespace}") client.namespaces.create(namespace_name=namespace, type="text") # 2. Upload documents docs = [ {"id": "qs-doc-1", "text": "Moorcheh is a semantic search engine designed for speed and accuracy."}, {"id": "qs-doc-2", "text": "The Python SDK allows developers to easily integrate Moorcheh's features."} ] print("Uploading documents...") client.documents.upload(namespace_name=namespace, documents=docs) # Wait briefly for indexing (asynchronous process) time.sleep(5) # 3. Perform a semantic search print("Searching...") search_results = client.similarity_search.query( namespaces=[namespace], query="What is the SDK?" ) for result in search_results.get('results', []): print(f"Found: {result['text']} (Score: {result['score']})") # 4. Generate an AI answer print("Generating answer...") gen_ai_response = client.answer.generate( namespace=namespace, query="In one sentence, what is the purpose of the Python SDK?" ) print(f"AI Answer: {gen_ai_response['answer']}") # 5. Clean up print("Deleting namespace...") client.namespaces.delete(namespace) ``` -------------------------------- ### Copy Environment File Source: https://docs.moorcheh.ai/integrations/mcp/setup Copy the example environment file to create your own .env file for configuration. ```bash cp env.example .env ``` -------------------------------- ### Example Return Value for Upload Source: https://docs.moorcheh.ai/on-prem/python-client/data/upload-vectors Illustrates the structure of a successful response when starting a vector upload job. ```json { "status": "success", "message": "Vectors upload started. Poll job status for progress.", "job_id": "job-d044a3bf6c0e4380bf6ad7e9df7999d0", "namespace_name": "my-embeddings", "total": 1, } ``` -------------------------------- ### Example Configuration File Source: https://docs.moorcheh.ai/on-prem/cli/runtime/configure This JSON file shows the structure and typical values for the ~/.moorcheh/config.json file, including provider, model, API key, and base URL. ```json { "provider": "openai", "model": "text-embedding-3-small", "api_key": "sk-...", "base_url": "https://api.openai.com/v1" } ``` -------------------------------- ### OpenAI/Cohere provider output Source: https://docs.moorcheh.ai/on-prem/cli/runtime/up This output indicates that the Moorcheh server has started using a cloud-based embedding provider (OpenAI or Cohere) and that Ollama is not required for this setup. ```text Moorcheh server started (cloud embedding provider; Ollama not required). ``` -------------------------------- ### Configure Moorcheh with Cloud Embedding Provider Source: https://docs.moorcheh.ai/on-prem/prerequisites Set the embedding provider to OpenAI or Cohere during configuration or when starting Moorcheh. This example shows setting the provider and API key. ```bash moorcheh up --embedding-provider openai --embedding-api-key ... ``` -------------------------------- ### Use MoorchehEdge SDK Source: https://docs.moorcheh.ai/on-edge/python-client/introduction Example of using the MoorchehEdge SDK to interact with a local Docker instance. This approach is suitable when you need to start Docker and call the API from Python. ```python from moorcheh_edge import MoorchehEdge with MoorchehEdge(port=8080) as client: print(client.health()) client.upload([{"id": "a", "vector": [...]}]) # 1024 floats print(client.search(query=[...], top_k=5)) ``` -------------------------------- ### Typical CLI Workflow Source: https://docs.moorcheh.ai/on-edge/cli/introduction Demonstrates a common sequence of commands for managing the moorcheh-edge service, from starting to searching and stopping. ```bash moorcheh-edge up moorcheh-edge status moorcheh-edge upload-vectors --vectors-file payload.json moorcheh-edge search --query-vector-json "[...]" --top-k 5 moorcheh-edge delete --ids-json '["item-1"]' moorcheh-edge down ``` -------------------------------- ### Environment Variables Setup Source: https://docs.moorcheh.ai/integrations/gemini/overview Configure your Moorcheh and Gemini API keys using a .env file. These keys are required for authentication. ```bash MOORCHEH_API_KEY=your_moorcheh_key GEMINI_API_KEY=your_gemini_key ``` -------------------------------- ### Example GET Request for Namespaces (cURL) Source: https://docs.moorcheh.ai/api-reference/introduction This cURL command demonstrates how to fetch a list of namespaces from the Moorcheh API. It includes the necessary API key and content type headers. ```bash curl -X GET "https://api.moorcheh.ai/v1/namespaces" \ -H "x-api-key: your-api-key-here" \ -H "Content-Type: application/json" ``` -------------------------------- ### Example Output for Document Upload Source: https://docs.moorcheh.ai/on-prem/cli/data/upload-documents This JSON output indicates that the document upload job has been successfully started. It includes a job ID for polling and details about the namespace and the number of documents processed. ```json { "status": "success", "message": "Documents upload started. Poll job status for progress.", "job_id": "job-9889a2ea08034064adb584d0afdf45b1", "namespace_name": "my-documents", "total": 1 } ``` -------------------------------- ### Financial Document Analysis Setup Source: https://docs.moorcheh.ai/integrations/llamaindex/overview Loads financial documents, configures chunking settings for LlamaIndex, and initializes a MoorchehVectorStore for financial analysis. ```python # Load financial documents documents = SimpleDirectoryReader("./financial_reports").load_data() # Configure for financial analysis Settings.chunk_size = 1024 Settings.chunk_overlap = 100 # Create vector store vector_store = MoorchehVectorStore( api_key=api_key, namespace="financial_analysis", namespace_type="text", ) # Query financial data response = vector_store.get_generative_answer( query="What were the key financial metrics for Q4 2024?", ai_model="anthropic.claude-sonnet-4-6", ) ``` -------------------------------- ### Install Moorcheh CLI Source: https://docs.moorcheh.ai/on-prem/cli/introduction Install the Moorcheh client package using pip. This command installs the 'moorcheh' CLI tool. ```bash pip install moorcheh-client ``` -------------------------------- ### Install Moorcheh Node via NPM Source: https://docs.moorcheh.ai/integrations/n8n/overview Install the Moorcheh n8n community node package using npm. This is a prerequisite for manual installation on self-hosted n8n instances. ```bash npm i n8n-nodes-moorcheh ``` -------------------------------- ### Full Python Workflow Example Source: https://docs.moorcheh.ai/on-edge/python-client/getting-started Demonstrates a complete workflow using the Moorcheh Edge Python client. It covers checking server health, uploading vectors, performing searches, and deleting items. Ensure vectors match the required dimension (1024 floats). ```python import random from moorcheh_edge import MoorchehEdge, MoorchehEdgeApiError def rand_vec(dim: int = 1024) -> list[float]: return [random.random() for _ in range(dim)] with MoorchehEdge(port=8080, skip_pull=False) as client: health = client.health() print(f"Items: {health['items']} / {health['max_items']}") client.upload([ {"id": "item-1", "vector": rand_vec()}, {"id": "item-2", "vector": rand_vec()}, ]) results = client.search(query=rand_vec(), top_k=3) for r in results: print(r["id"], r["score"], r["label"]) client.delete(["item-1"]) ``` -------------------------------- ### List Namespaces Example Source: https://docs.moorcheh.ai/python-sdk/namespaces/list Fetches all namespaces and prints a summary of their names, types, and item counts. This is useful for a quick overview of available namespaces. ```python from moorcheh_sdk import MoorchehClient with MoorchehClient() as client: all_namespaces = client.namespaces.list() print(f"Found {len(all_namespaces.get('namespaces', []))} namespaces:") for ns in all_namespaces.get('namespaces', []): print(f"- Namespace: {ns['namespace_name']}, Type: {ns['type']}, Items: {ns['item_count']}") ``` -------------------------------- ### Install moorcheh-client v0.1.1 Source: https://docs.moorcheh.ai/on-prem/changelog Install a specific version of the moorcheh-client package or upgrade to the latest version. ```bash pip install moorcheh-client==0.1.1 # or pip install -U moorcheh-client ``` -------------------------------- ### End-to-End NVIDIA Integration Example Source: https://docs.moorcheh.ai/integrations/nvidia/overview This snippet demonstrates a complete workflow for embedding a query, performing a similarity search, and printing the results using NVIDIA services and the Moorcheh client. ```python query_vecs = nvidia_embed([query], input_type="query") query_vec = to_float_vector(query_vecs[0]) results = mc.similarity_search.query( namespaces=[NAMESPACE], query=query_vec, top_k=5, kiosk_mode=True, threshold=0.15, ) print(f"namespace={NAMESPACE} total_results={len(results.get('results', []))}") print("=" * 120) for idx, r in enumerate(results.get("results", []), start=1): print_result(idx, r) ``` -------------------------------- ### Install moorcheh-client v0.1.2 Source: https://docs.moorcheh.ai/on-prem/changelog Install a specific version of the moorcheh-client package or upgrade to the latest version. ```bash pip install moorcheh-client==0.1.2 # or pip install -U moorcheh-client ``` -------------------------------- ### List All Namespaces Source: https://docs.moorcheh.ai/on-prem/api-references/namespaces/list Use this command to fetch all namespaces. No API keys or special headers are required for on-prem deployments. ```bash curl http://localhost:8080/namespaces ``` -------------------------------- ### No Matches Response Example Source: https://docs.moorcheh.ai/on-prem/api-references/search/query Example response when no search results are found. The 'results' array will be empty. ```json { "results": [], "execution_time": 0.040776, "timings": { "parse_validate": 0.0, "prepare_vector": 0.040736, "fetch_data": 0.0, "calculate_distance": 0.000033, "select_candidates": 0.0, "calculate_scores": 0.0, "reorder": 0.0, "format_response": 0.0, "total": 0.040776 } } ``` -------------------------------- ### Complete Similarity Search Workflow Source: https://docs.moorcheh.ai/python-sdk/search/query This example demonstrates a full workflow: creating a namespace, uploading documents, and then performing a similarity search. It includes a delay to ensure documents are processed before searching. ```python from moorcheh_sdk import MoorchehClient import time with MoorchehClient() as client: namespace = "customer-support" # 1. Create namespace and upload support documents client.namespaces.create(namespace, type="text") support_docs = [ { "id": "policy-1", "text": "Our return policy allows returns within 30 days of purchase with original receipt.", "category": "returns" }, { "id": "policy-2", "text": "We offer free shipping on orders over $50. Standard shipping takes 3-5 business days.", "category": "shipping" } ] client.documents.upload(namespace, support_docs) print("Documents uploaded, waiting for processing...") time.sleep(5) # 2. Perform searches print("\n=== SEARCH RESULTS ===") search_results = client.similarity_search.query( namespaces=[namespace], query="return policy", top_k=2 ) for result in search_results['results']: print(f"Score: {result['score']:.3f} | ID: {result['id']}") print(f"Text: {result['text'][:80]}...") print() ``` -------------------------------- ### Install LangChain Moorcheh Package Source: https://docs.moorcheh.ai/integrations/langchain/overview Install the necessary package for LangChain integration. This command should be run in your terminal. ```bash pip install langchain-moorcheh ``` -------------------------------- ### Install Node.js Dependencies Source: https://docs.moorcheh.ai/integrations/mcp/setup Install the necessary Node.js packages for the Moorcheh MCP server after cloning the repository. ```bash npm install ``` -------------------------------- ### Complete Example for Document Retrieval Source: https://docs.moorcheh.ai/python-sdk/data/get-documents This example demonstrates retrieving multiple documents and processing the response, including handling cases where some documents might not be found. It shows how to access document details and metadata. ```python from moorcheh_sdk import MoorchehClient with MoorchehClient() as client: namespace = "my-documents" # Retrieve multiple documents result = client.documents.get( namespace_name=namespace, ids=["doc-1", "doc-2", "doc-3", "doc-4", "doc-5"] ) print(f"Requested: {result.get('requested_ids', 0)}") print(f"Found: {result.get('found_items', 0)}") # Process retrieved documents for item in result.get('items', []): print(f"\nDocument ID: {item['id']}") print(f"Text: {item['text'][:100]}...") # First 100 chars if item.get('metadata'): print(f"Metadata: {item['metadata']}") # Handle partial success if result.get('status') == 'partial': not_found = result.get('not_found_ids', []) if not_found: print(f"\nDocuments not found: {not_found}") ``` -------------------------------- ### Verify Python Installation Source: https://docs.moorcheh.ai/on-edge/prerequisites Checks if the installed Python version is 3.10 or newer. This is a mandatory requirement for Moorcheh Edge. ```bash python --version ``` -------------------------------- ### End-to-end Gemini and Moorcheh Integration Example Source: https://docs.moorcheh.ai/integrations/gemini/overview This comprehensive example demonstrates loading API keys, creating a vector namespace, chunking documents, embedding content using Gemini, and uploading the vectors to Moorcheh. It covers both index-time document embedding and prepares for query-time embedding. ```python import os import textwrap from typing import List from dotenv import load_dotenv from google.genai import Client, types from moorcheh_sdk import MoorchehClient load_dotenv() MOORCHEH_API_KEY = os.getenv("MOORCHEH_API_KEY", "").strip() GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "").strip() if not MOORCHEH_API_KEY or not GEMINI_API_KEY: raise SystemExit("Set MOORCHEH_API_KEY and GEMINI_API_KEY.") os.environ.setdefault("GEMINI_API_KEY", GEMINI_API_KEY) NAMESPACE = "gemini-embed-demo" VECTOR_DIMENSION = 3072 # Match default for gemini-embedding-2-preview; or set output_dimensionality and use that size CHUNK_SIZE = 900 CHUNK_OVERLAP = 180 def to_float_vector(values) -> List[float]: return [float(x) for x in values] def chunk_text(text: str, chunk_size: int = CHUNK_SIZE, overlap: int = CHUNK_OVERLAP) -> List[str]: chunks: List[str] = [] start = 0 while start < len(text): end = min(start + chunk_size, len(text)) chunks.append(text[start:end].strip()) if end == len(text): break start = max(end - overlap, 0) return [c for c in chunks if c] def extract_text(result: dict) -> str: if result.get("text"): return str(result["text"]) metadata = result.get("metadata") or {} if isinstance(metadata, dict): return str(metadata.get("text") or metadata.get("raw_text") or metadata.get("content") or "") return "" def clean_text(text: str) -> str: return " ".join(str(text).split()) def print_result(idx: int, result: dict) -> None: metadata = result.get("metadata") or {} text_value = clean_text(extract_text(result)) wrapped = textwrap.fill(text_value, width=100) print(f"[{idx}] id={result.get('id')}") print(f"score={result.get('score')} label={result.get('label')}") print(f"section={metadata.get('section')} source_doc_id={metadata.get('source_doc_id')}") print("text:") print(wrapped if wrapped else "(no text returned)") print("-" * 120) # 1) Clients gemini_client = Client() mc = MoorchehClient(api_key=MOORCHEH_API_KEY) # 2) Create vector namespace once (ignore if it already exists) try: mc.namespaces.create( namespace_name=NAMESPACE, type="vector", vector_dimension=VECTOR_DIMENSION, ) except Exception: pass # 3) Sample documents and chunking source_documents = [ { "id": "guide-vector-namespaces", "section": "vector-namespace-best-practices", "text": ( "Moorcheh vector namespaces support bring-your-own-embedding workflows. " "When using Gemini gemini-embedding-2-preview, the namespace dimension must match the embedding output size. " "Each vector item should include a stable id and the original chunk text so results can be shown without a second fetch." ), }, { "id": "guide-search-tuning", "section": "semantic-search-tuning", "text": ( "For better relevance, use RETRIEVAL_DOCUMENT for stored chunks and RETRIEVAL_QUERY for queries. " "Keep chunk sizes coherent and use overlap to preserve context across chunk boundaries." ), }, ] documents = [] for doc in source_documents: parts = chunk_text(doc["text"]) for idx, chunk in enumerate(parts): documents.append( { "id": f"{doc['id']}-chunk-{idx}", "text": chunk, "source_doc_id": doc["id"], "section": doc["section"], "chunk_index": idx, "total_chunks": len(parts), } ) texts = [d["text"] for d in documents] # 4) Embed documents (index-time) doc_result = gemini_client.models.embed_content( model="gemini-embedding-2-preview", contents=texts, config=types.EmbedContentConfig(task_type="RETRIEVAL_DOCUMENT"), ) # 5) Upload to Moorcheh mc.vectors.upload( namespace_name=NAMESPACE, vectors=[ { "id": documents[i]["id"], "vector": to_float_vector(doc_result.embeddings[i].values), "text": documents[i]["text"], "source": "gemini-embedding-2-preview", "model": "gemini-embedding-2-preview", "task_type": "RETRIEVAL_DOCUMENT", "section": documents[i]["section"], "source_doc_id": documents[i]["source_doc_id"], "chunk_index": documents[i]["chunk_index"], "total_chunks": documents[i]["total_chunks"], } for i in range(len(documents)) ], ) ``` -------------------------------- ### Complete List Files Workflow Source: https://docs.moorcheh.ai/python-sdk/files/list-files This example shows a complete workflow for listing files, iterating through the results, and printing file details like name, size, and last modified date. ```python from moorcheh_sdk import MoorchehClient with MoorchehClient() as client: listing = client.documents.list_files(namespace_name="my-data") print(f"Namespace: {listing.get('namespace')}") print(f"File count: {listing.get('file_count')}") for f in listing.get("files", []): print(f["file_name"], f["size"], f.get("last_modified")) ``` -------------------------------- ### Start Moorcheh Edge Server Source: https://docs.moorcheh.ai/on-edge/cli/runtime/up Starts the Moorcheh Edge server using the default Docker image and port. ```bash moorcheh-edge up ``` -------------------------------- ### Complete File Upload Workflow Source: https://docs.moorcheh.ai/python-sdk/files/upload-file A comprehensive example showing the creation of a text namespace, uploading a file, and waiting for asynchronous processing before proceeding. ```python from moorcheh_sdk import MoorchehClient import time with MoorchehClient() as client: # 1. Create a namespace (once) client.namespaces.create("my-data", type="text") # 2. Upload a file upload_result = client.documents.upload_file( namespace_name="my-data", file_path="C:/path/to/product-faq.pdf" ) print(f"Upload response: {upload_result}") # 3. Wait for processing before querying/searching print("Waiting for file processing...") time.sleep(5) ``` -------------------------------- ### Verify Docker Installation Source: https://docs.moorcheh.ai/on-edge/prerequisites Checks if Docker is installed and running. Docker is required to run the Moorcheh Edge server container. ```bash docker --version docker info ```