### Start Simple MCP Server Source: https://github.com/helixdb/helix-py/blob/main/README.md Provides a basic example of starting an MCP server using Helix client, MCPServer, and OpenAIEmbedder. The server runs on http://127.0.0.1:8000/mcp/. ```python # examples/mcp_server.py from helix.client import Client from helix.mcp import MCPServer, ToolConfig from helix.embedding.openai_client import OpenAIEmbedder helix_client = Client(local=True) openai_embedder = OpenAIEmbedder() # needs OPENAI_API_API_KEY mcp_server = MCPServer("helix-mcp", helix_client, tool_config=tool_config, embedder=openai_embedder) mcp_server.run() # streamable-http on http://127.0.0.1:8000/mcp/ ``` -------------------------------- ### Install Helix CLI Source: https://github.com/helixdb/helix-py/blob/main/README.md Install the Helix CLI tool by downloading and executing the installation script, followed by the install command. ```bash curl -sSL "https://install.helix-db.com" | bash helix install ``` -------------------------------- ### Install helix-py Core Source: https://github.com/helixdb/helix-py/blob/main/README.md Install the core helix-py library for client and query functionalities using uv or pip. ```bash uv add helix-py ``` ```bash pip install helix-py ``` -------------------------------- ### Start MCP Server with Custom Host/Port Source: https://github.com/helixdb/helix-py/blob/main/README.md An alternative application entry point for starting an MCP server, allowing explicit configuration of the host and port for the server to run on. ```python # apps/mcp_server.py from helix.client import Client from helix.mcp import MCPServer from helix.embedding.openai_client import OpenAIEmbedder client = Client(local=True, port=6969) openai_embedder = OpenAIEmbedder() mcp_server = MCPServer("helix-mcp", client, embedder=openai_embedder) if __name__ == "__main__": mcp_server.run(transport="streamable-http", host="127.0.0.1", port=8000) ``` -------------------------------- ### Run MCPServer (Blocking) Source: https://context7.com/helixdb/helix-py/llms.txt Start the MCPServer and make it accessible via HTTP. This call is blocking. ```python # Run server (blocking) mcp_server.run(transport="streamable-http", host="127.0.0.1", port=8000) # Server available at http://127.0.0.1:8000/mcp/ ``` -------------------------------- ### Install Rust using rustup Source: https://github.com/helixdb/helix-py/blob/main/examples/rag-demo/rag_rust_demo.ipynb Installs the latest stable version of Rust using the rustup tool. This command is for Linux and macOS users. ```bash curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh ``` -------------------------------- ### Initialize Helix Instance Source: https://github.com/helixdb/helix-py/blob/main/README.md Set up a HelixDB instance that automatically starts and stops with the program's lifecycle. Specify the configuration directory and port. ```python from helix.instance import Instance helix_instance = Instance("helixdb-cfg", 6969, verbose=True) ``` -------------------------------- ### Install helix-py with Optional Features Source: https://github.com/helixdb/helix-py/blob/main/README.md Install helix-py with specific optional features like data loading, text chunking, PDF parsing, or embedders by appending the feature name in brackets. ```bash pip install "helix-py[loader]" ``` ```bash pip install "helix-py[chunking]" ``` ```bash pip install "helix-py[pdf]" ``` ```bash pip install "helix-py[mcp]" ``` ```bash pip install "helix-py[embed-openai]" ``` ```bash pip install "helix-py[provider-openai]" ``` ```bash pip install "helix-py[embedders]" ``` ```bash pip install "helix-py[providers]" ``` ```bash pip install "helix-py[all]" ``` -------------------------------- ### MCP Server Setup and Configuration Source: https://github.com/helixdb/helix-py/blob/main/README.md Instructions on setting up and running the Helix MCP (Model Communication Protocol) server, including configuration options for tools and integration with clients. ```APIDOC ## MCP Server ### Description The Helix MCP server provides a ready-to-run service that exposes graph traversal and search tools from your Helix instance. It can be configured with various embedding providers and toolsets. ### Key Classes - `MCPServer(name, client, tool_config=ToolConfig(), embedder=None, embedder_args={})`: The main class for creating an MCP server. - `ToolConfig`: Used to enable or disable specific tools like vector search, keyword search, and traversal tools. ### Starting a Simple MCP Server ```python # examples/mcp_server.py from helix.client import Client from helix.mcp import MCPServer, ToolConfig from helix.embedding.openai_client import OpenAIEmbedder # Initialize Helix Client helix_client = Client(local=True) # Initialize an embedder (e.g., OpenAIEmbedder, requires OPENAI_API_KEY) openai_embedder = OpenAIEmbedder() # Define tool configuration (optional, defaults to a standard set) tool_config = ToolConfig() # Create and run the MCP server mcp_server = MCPServer("helix-mcp", helix_client, tool_config=tool_config, embedder=openai_embedder) mcp_server.run() # Runs on http://127.0.0.1:8000/mcp/ by default ``` ### Starting an MCP Server with Explicit Host/Port ```python # apps/mcp_server.py from helix.client import Client from helix.mcp import MCPServer from helix.embedding.openai_client import OpenAIEmbedder # Initialize Helix Client with specific port client = Client(local=True, port=6969) openai_embedder = OpenAIEmbedder() # Create MCP server instance mcp_server = MCPServer("helix-mcp", client, embedder=openai_embedder) if __name__ == "__main__": # Run the server with specified transport, host, and port mcp_server.run(transport="streamable-http", host="127.0.0.1", port=8000) ``` ### Configuring Claude Desktop to Use Local MCP Server ```json { "mcpServers": { "helix-mcp": { "command": "uv", "args": [ "--directory", "/absolute/path/to/your/app/folder", "run", "mcp_server.py" ] } } } ``` ### MCP Tools Overview - **Traversal Tools**: `n_from_type`, `e_from_type`, `out_step`, `out_e_step`, `in_step`, `in_e_step`, `filter_items`. - **Search Tools**: `search_vector` (requires an `embedder`), `search_vector_text` (server-side embedding), `search_keyword`. ### Environment Variables Ensure the following environment variables are set as needed: - `OPENAI_API_KEY` - `GEMINI_API_KEY` - `VOYAGEAI_API_KEY` - `ANTHROPIC_API_KEY` ``` -------------------------------- ### Install C Compiler on macOS Source: https://github.com/helixdb/helix-py/blob/main/examples/rag-demo/rag_rust_demo.ipynb Installs a C compiler on macOS, which is often required for Rust development and may include a linker. ```bash xcode-select --install ``` -------------------------------- ### Install helix-py and Dependencies Source: https://github.com/helixdb/helix-py/blob/main/examples/rag-demo/rag_rust_demo.ipynb Install the helix-py library and its required dependencies using pip. This command ensures all necessary packages are available for the project. ```bash !pip install -q chonkie docling model2vec rich torch transformers tqdm requests helix-py ``` -------------------------------- ### Run MCPServer Asynchronously Source: https://context7.com/helixdb/helix-py/llms.txt Start the MCPServer using asyncio for asynchronous execution. ```python import asyncio asyncio.run(mcp_server.run_async(transport="streamable-http", port=8000)) ``` -------------------------------- ### Load CodeBERT Tokenizer and Model Source: https://github.com/helixdb/helix-py/blob/main/examples/rag-demo/rag_rust_demo.ipynb Loads the tokenizer and model for the 'microsoft/codebert-base' pre-trained model. Ensure the 'transformers' library is installed. ```python from transformers import AutoTokenizer, AutoModel tokenizer = AutoTokenizer.from_pretrained("microsoft/codebert-base") model = AutoModel.from_pretrained("microsoft/codebert-base") ``` -------------------------------- ### Process and Vectorize Chunks Source: https://github.com/helixdb/helix-py/blob/main/examples/rag-demo/rag_rust_demo.ipynb Example of processing a list of chunks and generating embeddings for each chunk. ```python items = [(ch, [(sch, content, [(chunk.text, vectorize_text(chunk.text)) for chunk in clist])]) for ch, sch, content, clist in tqdm(list_of_chunks)] print(f"length of items: {len(items)}") ``` -------------------------------- ### Run MCPServer in Background Thread Source: https://context7.com/helixdb/helix-py/llms.txt Start the MCPServer in a separate background thread, allowing the main program to continue execution. ```python thread = mcp_server.run_bg(transport="streamable-http", host="127.0.0.1", port=8000) ``` -------------------------------- ### Run Minigrep With IGNORE_CASE Environment Variable (Bash/Zsh) Source: https://github.com/helixdb/helix-py/blob/main/examples/rag-demo/rag_rust_demo.ipynb Shows how to enable case-insensitive search in minigrep by setting the IGNORE_CASE environment variable before running the command. This example uses Bash or Zsh syntax. ```bash $ IGNORE_CASE=1 cargo run -- to poem.txt ``` -------------------------------- ### Initialize and Use OpenAI LLM Provider Source: https://github.com/helixdb/helix-py/blob/main/README.md Demonstrates initializing the OpenAI LLM provider with specific configurations and making a simple text generation call. Also shows how to generate structured output using a Pydantic BaseModel. ```python from pydantic import BaseModel # OpenAI from helix.providers.openai_client import OpenAIProvider openai_llm = OpenAIProvider( name="openai-llm", instructions="You are a helpful assistant.", model="gpt-5-nano", history=True ) print(openai_llm.generate("Hello!")) class Person(BaseModel): name: str age: int occupation: str print(openai_llm.generate([{"role": "user", "content": "Who am I?"}], Person)) ``` -------------------------------- ### Initialize Basic MCPServer Source: https://context7.com/helixdb/helix-py/llms.txt Set up an MCPServer to expose HelixDB graph traversal and search capabilities. Requires a HelixDB client. ```python from helix import Client from helix.mcp import MCPServer helix_client = Client(local=True, port=6969) mcp_server = MCPServer("helix-mcp", helix_client) ``` -------------------------------- ### Initialize Gemini LLM Provider Source: https://context7.com/helixdb/helix-py/llms.txt Set up the GeminiProvider with a name, instructions, and model for data analysis tasks. ```python from helix.providers.gemini_client import GeminiProvider gemini_llm = GeminiProvider( name="gemini-assistant", instructions="You are an expert data analyst.", model="gemini-2.5-pro" ) response = gemini_llm.generate("Analyze this data pattern") ``` -------------------------------- ### Create Project Directory (Windows CMD) Source: https://github.com/helixdb/helix-py/blob/main/examples/rag-demo/rag_rust_demo.ipynb Use these commands in Windows Command Prompt to create a projects directory and a hello_world subdirectory for your Rust projects. ```batch > mkdir "%USERPROFILE%\projects" > cd /d "%USERPROFILE%\projects" > mkdir hello_world > cd hello_world ``` -------------------------------- ### Connect to HelixDB with Client Source: https://context7.com/helixdb/helix-py/llms.txt Demonstrates various ways to instantiate the Client class for connecting to HelixDB, including local and cloud instances, custom ports, and API authentication. Also shows basic query execution and batching. ```python from helix import Client # Connect to a local HelixDB instance on default port 6969 db = Client(local=True, verbose=True) # Connect to a local instance on a custom port db = Client(local=True, port=7070, verbose=True) # Connect to a cloud instance with API authentication db = Client( local=False, api_endpoint="https://your-helix-cloud.com", api_key="your-api-key" ) # Execute queries with string endpoint and payload result = db.query('add_user', {"name": "John", "age": 20}) # Output: [{'user': {'id': '...', 'name': 'John', 'age': 20}}] # Batch multiple payloads in a single query users = db.query("create_user", [ {"name": "Alice", "age": 28, "email": "alice@example.com"}, {"name": "Bob", "age": 32, "email": "bob@example.com"} ]) # Enable concurrent requests with max_workers db = Client(local=True, max_workers=4) results = db.query("process_items", [{"id": i} for i in range(100)]) ``` -------------------------------- ### Create Project Directory (Linux/macOS/PowerShell) Source: https://github.com/helixdb/helix-py/blob/main/examples/rag-demo/rag_rust_demo.ipynb Use these commands to create a projects directory and a hello_world subdirectory for your Rust projects. ```bash $ mkdir ~/projects $ cd ~/projects $ mkdir hello_world $ cd hello_world ``` -------------------------------- ### Initialize OpenAI LLM Provider Source: https://context7.com/helixdb/helix-py/llms.txt Set up the OpenAIProvider with a name, instructions, model, and option to enable conversation history. ```python from helix.providers.openai_client import OpenAIProvider openai_llm = OpenAIProvider( name="assistant", instructions="You are a helpful assistant that answers questions concisely.", model="gpt-5-nano", history=True # Enable conversation history ) ``` -------------------------------- ### Initialize Anthropic LLM Provider Source: https://context7.com/helixdb/helix-py/llms.txt Set up the AnthropicProvider with a name, instructions, and model for creative writing tasks. ```python from helix.providers.anthropic_client import AnthropicProvider anthropic_llm = AnthropicProvider( name="claude-assistant", instructions="You are a creative writing assistant.", model="claude-sonnet-4-20250514" ) response = anthropic_llm.generate("Write a short poem about databases") ``` -------------------------------- ### Print Hello, World! in Rust Source: https://github.com/helixdb/helix-py/blob/main/examples/rag-demo/rag_rust_demo.ipynb A basic 'Hello, World!' program in Rust. This is a traditional first program for learning a new language. ```rust fn main() { println!("Hello, world!"); } ``` -------------------------------- ### Initialize Helix Client Source: https://github.com/helixdb/helix-py/blob/main/README.md Set up a helix client to interface with a running Helix-DB instance. The 'local=True' option is for local instances, and 'verbose=True' enables detailed logging. ```python import helix db = helix.Client(local=True, verbose=True) db.query('add_user', {"name": "John", "age": 20}) ``` -------------------------------- ### Update User Node Type Source: https://github.com/helixdb/helix-py/blob/main/examples/cookbook/schema_demo.ipynb Modifies an existing 'User' node type by adding or changing properties. This example adds an 'email' field to the User schema. ```python schema.update_node( "User", { "name": "String", "age": "U32", "email": "String", "created_at": "I32", "updated_at": "I32" } ) print("Current schema:\n\n" + str(schema)) ``` -------------------------------- ### Python Code for Ollama Response Source: https://github.com/helixdb/helix-py/blob/main/examples/rag-demo/rag_rust_demo.ipynb This Python snippet demonstrates how to get a response from an Ollama model and print it. It includes error handling for timeouts and keyboard interrupts. ```python response = get_ollama_response(create_prompt(res, user_prompt)) print(f"reponse: {response}") ``` -------------------------------- ### Initialize MCPServer with Embedder Source: https://context7.com/helixdb/helix-py/llms.txt Configure the MCPServer with an embedder for vector search capabilities. Additional arguments for the embedder can be passed. ```python from helix.embedding.openai_client import OpenAIEmbedder openai_embedder = OpenAIEmbedder() mcp_server = MCPServer( "helix-mcp", helix_client, embedder=openai_embedder, embedder_args={} ) ``` -------------------------------- ### Create Prompt for LLM Source: https://github.com/helixdb/helix-py/blob/main/examples/rag-demo/rag_rust_demo.ipynb Formats a prompt string with context and a query for a language model, using a predefined template. ```python def create_prompt(context: str, query: str) -> str: prompt_template = """ Based on the provided contexts, answer the given question to the best of your ability. {context} {query} """ prompt = prompt_template.format(context=context, query=query) return prompt ``` -------------------------------- ### Initialize and Use Gemini Embedder Source: https://github.com/helixdb/helix-py/blob/main/README.md Initializes the Gemini embedder and demonstrates embedding text for retrieval document tasks. ```python from helix.embedding.gemini_client import GeminiEmbedder gemini_embedder = GeminiEmbedder() vec = gemini_embedder.embed("doc text", task_type="RETRIEVAL_DOCUMENT") ``` -------------------------------- ### Compile and Run Rust Program (Windows) Source: https://github.com/helixdb/helix-py/blob/main/examples/rag-demo/rag_rust_demo.ipynb Compile the main.rs file using rustc and then execute the compiled binary. ```batch > rustc main.rs > .\main ``` -------------------------------- ### Configure Claude Desktop to Use Local MCP Server Source: https://github.com/helixdb/helix-py/blob/main/README.md A JSON configuration snippet for Claude Desktop, specifying how to launch the local MCP server using 'uv' and a Python script. ```json { "mcpServers": { "helix-mcp": { "command": "uv", "args": [ "--directory", "/absolute/path/to/your/app/folder", "run", "mcp_server.py" ] } } } ``` -------------------------------- ### Compile and Run Rust Program (Linux/macOS) Source: https://github.com/helixdb/helix-py/blob/main/examples/rag-demo/rag_rust_demo.ipynb Compile the main.rs file using rustc and then execute the compiled binary. ```bash $ rustc main.rs $ ./main ``` -------------------------------- ### Initialize and Use VoyageAI Embedder Source: https://github.com/helixdb/helix-py/blob/main/README.md Initializes the VoyageAI embedder and demonstrates embedding text for query input types. ```python from helix.embedding.voyageai_client import VoyageAIEmbedder voyage_embedder = VoyageAIEmbedder() vec = voyage_embedder.embed("query text", input_type="query") ``` -------------------------------- ### Manage HelixDB Instance Lifecycle with Instance Class Source: https://context7.com/helixdb/helix-py/llms.txt Shows how to use the `Instance` class to manage the lifecycle of a HelixDB instance, including deployment from configuration, checking status, stopping, redeploying, and deleting instances. The instance automatically stops when the script exits. ```python from helix import Client, Instance # Create and deploy a new Helix instance from config directory helix_instance = Instance( config_path="helixdb-cfg", # Path to config files (schema.hx, queries.hx, config.hx.json) port=6969, verbose=True ) # Instance automatically deploys on creation # Connect to it via Client db = Client(local=True, port=6969) # Check instance status helix_instance.status() # Output: Instance ID, Short ID, Port, Running status # Manually stop the instance helix_instance.stop() # Redeploy with updated configuration helix_instance = Instance(config_path="helixdb-cfg", port=6969, redeploy=True) # Delete the instance completely helix_instance.delete() # Instance automatically stops when script exits (via atexit) ``` -------------------------------- ### Initialize Gemini Provider and Embedder Source: https://github.com/helixdb/helix-py/blob/main/examples/llm_providers/providers.ipynb Initializes the Gemini LLM provider with specified model and temperature, and the Gemini embedder. These instances are then configured for use with an MCP server, setting the embedder and its arguments. ```python from helix.providers.gemini_client import GeminiProvider from helix.embedding.gemini_client import GeminiEmbedder gemini_llm = GeminiProvider( model="gemini-2.0-flash", temperature=0.1, history=True ) gemini_embedder = GeminiEmbedder() # Set embedder for MCP server mcp_server.embedder = gemini_embedder mcp_server.embedder_args = {"task_type": "RETRIEVAL_QUERY"} ``` -------------------------------- ### Initialize OpenAI Embedder Source: https://context7.com/helixdb/helix-py/llms.txt Instantiate the OpenAIEmbedder with a specific model and dimensions. Requires OPENAI_API_KEY environment variable. ```python openai_embedder = OpenAIEmbedder( model="text-embedding-3-small", dimensions=1536 ) ``` -------------------------------- ### Initialize and Use OpenAI Embedder Source: https://github.com/helixdb/helix-py/blob/main/README.md Initializes the OpenAI embedder, which requires the OPENAI_API_KEY environment variable. Demonstrates embedding a single string and a batch of strings. ```python from helix.embedding.openai_client import OpenAIEmbedder openai_embedder = OpenAIEmbedder() # requires OPENAI_API_KEY vec = openai_embedder.embed("Hello world") batch = openai_embedder.embed_batch(["a", "b", "c"]) ``` -------------------------------- ### Initialize Anthropic LLM and VoyageAI Embedder Source: https://github.com/helixdb/helix-py/blob/main/examples/llm_providers/providers.ipynb Initialize the Anthropic LLM with a specific model and temperature, and set up the VoyageAI embedder. The embedder is then assigned to the MCP server. ```python from helix.providers.anthropic_client import AnthropicProvider from helix.embedding.voyageai_client import VoyageAIEmbedder anthropic_llm = AnthropicProvider( model="claude-3-5-haiku-20241022", temperature=0.1, history=True ) voyageai_embedder = VoyageAIEmbedder() # Set embedder for MCP server mcp_server.embedder = voyageai_embedder mcp_server.embedder_args = {"input_type": "query"} ``` -------------------------------- ### Initialize Schema Source: https://github.com/helixdb/helix-py/blob/main/examples/cookbook/schema_demo.ipynb Initializes a new schema object. This is the first step before performing any schema operations. ```python from schema import Schema schema = Schema() ``` -------------------------------- ### Initialize Gemini Embedder Source: https://context7.com/helixdb/helix-py/llms.txt Instantiate the GeminiEmbedder with a specified model. Requires GEMINI_API_KEY environment variable. ```python gemini_embedder = GeminiEmbedder(model="models/embedding-001") ``` -------------------------------- ### LLM Provider Usage Source: https://github.com/helixdb/helix-py/blob/main/README.md Demonstrates how to initialize and use different LLM providers (OpenAI, Gemini, Anthropic) for text generation, including support for free-form text and structured message lists, as well as Pydantic model validation for outputs. ```APIDOC ## LLM Provider Integration ### Description Helix provides interfaces for popular LLM providers like OpenAI, Gemini, and Anthropic. These providers allow for text generation using both simple string inputs and structured message lists. They also support generating structured outputs by validating responses against Pydantic models. ### Methods - `enable_mcps(name: str, url: str=...) -> bool`: Enables Helix MCP tools for the provider. - `generate(messages, response_model: BaseModel | None=None) -> str | BaseModel`: Generates a response based on the provided messages. Supports free-form text or a list of messages, and can return a Pydantic model. ### Parameters for `generate` - **messages**: `str` or `List[dict | Message]` - The input for the LLM. Can be a single string or a list of message dictionaries/objects. - **response_model**: `BaseModel | None` - An optional Pydantic model to validate and structure the LLM's output. ### Request Example (OpenAI) ```python from pydantic import BaseModel from helix.providers.openai_client import OpenAIProvider # Initialize OpenAI Provider openai_llm = OpenAIProvider( name="openai-llm", instructions="You are a helpful assistant.", model="gpt-5-nano", history=True ) # Generate response with free-form text print(openai_llm.generate("Hello!")) # Define a Pydantic model for structured output class Person(BaseModel): name: str age: int occupation: str # Generate response with message list and structured output print(openai_llm.generate([{"role": "user", "content": "Who am I?"}], Person)) ``` ### Notes - OpenAI GPT-5 models support reasoning; other models use temperature. - Anthropic local streamable MCP is not supported; use a URL-based MCP. ``` -------------------------------- ### Initialize VoyageAI Embedder Source: https://context7.com/helixdb/helix-py/llms.txt Instantiate the VoyageAIEmbedder with a chosen model. Requires VOYAGEAI_API_KEY environment variable. ```python voyage_embedder = VoyageAIEmbedder(model="voyage-2") ``` -------------------------------- ### Enable MCP Tools with OpenAI Source: https://github.com/helixdb/helix-py/blob/main/examples/llm_providers/providers.ipynb Enables MCP tools for the specified toolset and generates a response by querying available tools. Ensure the 'openai_llm' object is properly initialized. ```python openai_llm.enable_mcps("helix-mcp") response = openai_llm.generate([{"role": "user", "content": "What MCP tools do you have?"}]) print(response, ' ' + '-'*100, ' ') ``` -------------------------------- ### Enable MCP Tools with OpenAI Provider Source: https://context7.com/helixdb/helix-py/llms.txt Configure the OpenAI provider to use MCP tools by specifying a name and the URL of the MCP server. ```python openai_llm.enable_mcps("helix-mcp", url="http://localhost:8000/mcp/") response = openai_llm.generate("Find all users in the database") ``` -------------------------------- ### Configure OpenAI LLM and Embedder for MCP Server Source: https://github.com/helixdb/helix-py/blob/main/examples/llm_providers/providers.ipynb Sets up an OpenAI LLM provider with specific instructions and model, and an OpenAI embedder. The embedder is then assigned to the MCP server. ```python from helix.providers.openai_client import OpenAIProvider from helix.embedding.openai_client import OpenAIEmbedder openai_llm = OpenAIProvider( name="openai-llm", instructions="You are a helpful assistant.", model="gpt-5-nano", reasoning={ "effort":"low" }, history=True ) openai_embedder = OpenAIEmbedder() # Set embedder for MCP server mcp_server.embedder = openai_embedder ``` -------------------------------- ### Initialize HelixDB Schema Source: https://github.com/helixdb/helix-py/blob/main/README.md Create a Schema instance to dynamically manage your Helixdb schema. This will create a new schema file if one does not exist. ```python from helix.loader import Schema schema = Schema() ``` -------------------------------- ### Run Minigrep With IGNORE_CASE Environment Variable (PowerShell) Source: https://github.com/helixdb/helix-py/blob/main/examples/rag-demo/rag_rust_demo.ipynb Demonstrates how to set the IGNORE_CASE environment variable and run minigrep for case-insensitive search using PowerShell. The variable persists for the current session. ```powershell PS> $Env:IGNORE_CASE=1; cargo run -- to poem.txt ``` -------------------------------- ### Configure OpenAI Embedder with Custom Base URL Source: https://context7.com/helixdb/helix-py/llms.txt Initialize the OpenAIEmbedder with a custom API key and base URL, useful for proxies or compatible endpoints. ```python custom_embedder = OpenAIEmbedder( api_key="your-key", base_url="https://your-proxy.com/v1" ) ``` -------------------------------- ### Enable MCP Tools for LLM Providers Source: https://github.com/helixdb/helix-py/blob/main/README.md Shows how to enable MCP tools for different LLM providers, specifying a default URL or a custom remote URL for the Helix MCP server. ```python openai_llm.enable_mcps("helix-mcp") # uses default http://localhost:8000/mcp/ gemini_llm.enable_mcps("helix-mcp") # uses default http://localhost:8000/mcp/ anthropic_llm.enable_mcps("helix-mcp", url="https://your-remote-mcp/...") ``` -------------------------------- ### Rust: Configuration Struct and Build Function Source: https://github.com/helixdb/helix-py/blob/main/examples/rag-demo/rag_rust_demo.ipynb Defines the `Config` struct to hold search parameters, including a new `ignore_case` field. The `build` function parses command-line arguments to create a `Config` instance. ```rust use std::error::Error; use std::fs; pub struct Config { pub query: String, pub file_path: String, pub ignore_case: bool, } impl Config { pub fn build(args: &[String]) -> Result { if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); Ok(Config { query, file_path }) } } ``` -------------------------------- ### Define Query for Creating Chunks Source: https://github.com/helixdb/helix-py/blob/main/examples/chunking/chunking.ipynb This C++ query defines how to create and add chunks to a data store. It iterates through provided content strings and adds them as 'Chunk' objects. ```cpp QUERY create_chunk(contents: [String]) => FOR content in contents { AddN({chunk: content}) } RETURN "success" ``` -------------------------------- ### Define Custom Query Objects with Query Class Source: https://context7.com/helixdb/helix-py/llms.txt Illustrates how to create custom query objects by subclassing the `Query` class. This allows for defining specific payload structures and response transformations, enabling type-safe and reusable query components. ```python from helix import Client, Query from helix.types import Payload from typing import Tuple, List class AddUser(Query): """Custom query to add a user to the database.""" def __init__(self, name: str, age: int): super().__init__() # endpoint defaults to class name 'AddUser' self.name = name self.age = age def query(self) -> List[Payload]: # Must return a list of payload dictionaries return [{"name": self.name, "age": self.age}] def response(self, response): # Transform the response as needed return response.get('user', {}) # Execute the custom query db = Client(local=True) user = db.query(AddUser("John", 24)) # Output: {'id': '...', 'name': 'John', 'age': 24} # Query with custom endpoint name class GetUsersByAge(Query): def __init__(self, min_age: int, max_age: int): super().__init__(endpoint="get_users_by_age_range") self.min_age = min_age self.max_age = max_age def query(self) -> List[Payload]: return [{"min_age": self.min_age, "max_age": self.max_age}] def response(self, response): return [user for user in response.get('users', [])] users = db.query(GetUsersByAge(18, 30)) ``` -------------------------------- ### Loading Environment Variables with Dotenv Source: https://github.com/helixdb/helix-py/blob/main/examples/chunking/chunking.ipynb Load environment variables from a .env file using `dotenv.load_dotenv()`. This is often a prerequisite for setting up API keys or configurations. ```python import dotenv dotenv.load_dotenv() ``` -------------------------------- ### Configure Custom Tool Settings for MCPServer Source: https://context7.com/helixdb/helix-py/llms.txt Define custom tool configurations for the MCPServer, enabling specific functionalities like node/edge retrieval, traversal, filtering, and search. ```python from helix.mcp import ToolConfig tool_config = ToolConfig( n_from_type=True, # Enable node retrieval by type e_from_type=True, # Enable edge retrieval by type out_step=True, # Enable outward traversal in_step=True, # Enable inward traversal filter_items=True, # Enable filtering search_vector=True, # Enable vector similarity search (requires embedder) search_keyword=True # Enable BM25 keyword search ) mcp_server = MCPServer("helix-mcp", helix_client, tool_config=tool_config, embedder=openai_embedder) ``` -------------------------------- ### Generate Simple Text Response with OpenAI Source: https://context7.com/helixdb/helix-py/llms.txt Use the OpenAI provider to generate a concise text response to a given prompt. ```python response = openai_llm.generate("What is machine learning?") ``` -------------------------------- ### Generate LLM responses using Helix Client Source: https://github.com/helixdb/helix-py/blob/main/examples/llm_providers/providers.ipynb Demonstrates generating responses from the configured OpenAI LLM. Includes generating a response from a simple string, from a list of messages, and generating a structured response using a Pydantic model. ```python # Generating response from string response = openai_llm.generate("Hello, how are you?") print(response, '\n' + '-'*100, '\n') # Generate response from message response = openai_llm.generate([{"role": "user", "content": "My name is John Berger. I am a software engineer. I am 25 years old."}]) print(response, '\n' + '-'*100, '\n') # Generate structured response response = openai_llm.generate([{"role": "user", "content": "Who am I?"}], Person) print(response, '\n' + '-'*100, '\n') ``` -------------------------------- ### Initialize Helix Client and MCP Server Source: https://github.com/helixdb/helix-py/blob/main/examples/llm_providers/providers.ipynb Initializes a local Helix client and an MCP server named 'helix-mcp'. The server is configured with 'search_vector' enabled and 'search_vector_text' disabled. It runs in a background thread on port 8000. ```python # Helix Client helix_client = Client(local=True) # Helix MCP Server # Enable search_vector tool instead because we will add the embedder later mcp_server = MCPServer("helix-mcp", helix_client, tool_config=ToolConfig(search_vector=True, search_vector_text=False)) # Run mcp server in background thread on port 8000 # To stop the server, restart the notebook mcp_server.run_bg() ``` -------------------------------- ### Enable MCP Tools with Gemini LLM Source: https://github.com/helixdb/helix-py/blob/main/examples/llm_providers/providers.ipynb Enable and interact with MCP tools using the Gemini LLM. This is useful for accessing specific functionalities provided by the MCP. ```python gemini_llm.enable_mcps("helix-mcp") response = gemini_llm.generate([{"role": "user", "parts": [{"text": "What MCP tools do you have?"}]}]) print(response, '\n' + '-'*100, '\n') ``` -------------------------------- ### Rust Documentation Endpoints Source: https://github.com/helixdb/helix-py/blob/main/examples/rag-demo/rag_rust_demo.ipynb A list of tuples containing chapter numbers, titles, and URLs for the official Rust documentation. ```python rust_docs_endpoints = [ (1, "Getting Started", "https://doc.rust-lang.org/book/ch01-00-getting-started.html"), (1, "Installation", "https://doc.rust-lang.org/book/ch01-01-installation.html"), (1, "Hello, World!", "https://doc.rust-lang.org/book/ch01-02-hello-world.html"), (1, "Hello, Cargo!", "https://doc.rust-lang.org/book/ch01-03-hello-cargo.html"), (2, "Guessing Game Tutorial", "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html"), (3, "Common Programming Concepts", "https://doc.rust-lang.org/book/ch03-00-common-programming-concepts.html"), (3, "Variables and Mutability", "https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html"), (3, "Data Types", "https://doc.rust-lang.org/book/ch03-02-data-types.html"), (3, "How Functions Work", "https://doc.rust-lang.org/book/ch03-03-how-functions-work.html"), (3, "Comments", "https://doc.rust-lang.org/book/ch03-04-comments.html"), (3, "Control Flow", "https://doc.rust-lang.org/book/ch03-05-control-flow.html"), (4, "Understanding Ownership", "https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html"), (4, "What is Ownership?", "https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html"), (4, "References and Borrowing", "https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html"), (4, "Slices", "https://doc.rust-lang.org/book/ch04-03-slices.html"), (5, "Structs", "https://doc.rust-lang.org/book/ch05-00-structs.html"), (5, "Defining Structs", "https://doc.rust-lang.org/book/ch05-01-defining-structs.html"), (5, "Example Structs", "https://doc.rust-lang.org/book/ch05-02-example-structs.html"), (5, "Method Syntax", "https://doc.rust-lang.org/book/ch05-03-method-syntax.html"), (6, "Enums", "https://doc.rust-lang.org/book/ch06-00-enums.html"), (6, "Defining an Enum", "https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html"), (6, "Match", "https://doc.rust-lang.org/book/ch06-02-match.html"), (6, "If Let", "https://doc.rust-lang.org/book/ch06-03-if-let.html"), (7, "Managing Growing Projects with Packages, Crates, and Modules", "https://doc.rust-lang.org/book/ch07-00-managing-growing-projects-with-packages-crates-and-modules.html"), (7, "Packages and Crates", "https://doc.rust-lang.org/book/ch07-01-packages-and-crates.html"), (7, "Defining Modules to Control Scope and Privacy", "https://doc.rust-lang.org/book/ch07-02-defining-modules-to-control-scope-and-privacy.html"), (7, "Paths for Referring to an Item in the Module Tree", "https://doc.rust-lang.org/book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html"), (8, "Common Collections", "https://doc.rust-lang.org/book/ch08-00-common-collections.html"), (8, "Vectors", "https://doc.rust-lang.org/book/ch08-01-vectors.html"), (8, "Strings", "https://doc.rust-lang.org/book/ch08-02-strings.html"), (8, "Hash Maps", "https://doc.rust-lang.org/book/ch08-03-hash-maps.html"), (9, "Error Handling", "https://doc.rust-lang.org/book/ch09-00-error-handling.html"), (9, "Unrecoverable Errors with Panic", "https://doc.rust-lang.org/book/ch09-01-unrecoverable-errors-with-panic.html"), (9, "Recoverable Errors with Result", "https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html"), (9, "To Panic or Not to Panic", "https://doc.rust-lang.org/book/ch09-03-to-panic-or-not-to-panic.html"), (10, "Generics", "https://doc.rust-lang.org/book/ch10-00-generics.html"), (10, "Syntax", "https://doc.rust-lang.org/book/ch10-01-syntax.html"), (10, "Traits", "https://doc.rust-lang.org/book/ch10-02-traits.html"), (10, "Lifetime Syntax", "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html"), (11, "Testing", "https://doc.rust-lang.org/book/ch11-00-testing.html"), (11, "Writing Tests", "https://doc.rust-lang.org/book/ch11-01-writing-tests.html"), (11, "Running Tests", "https://doc.rust-lang.org/book/ch11-02-running-tests.html"), (11, "Test Organization", "https://doc.rust-lang.org/book/ch11-03-test-organization.html"), (12, "An I/O Project", "https://doc.rust-lang.org/book/ch12-00-an-io-project.html"), (12, "Accepting Command Line Arguments", "https://doc.rust-lang.org/book/ch12-01-accepting-command-line-arguments.html"), (12, "Reading a File", "https://doc.rust-lang.org/book/ch12-02-reading-a-file.html"), (12, "Improving Error Handling and Modularity", "https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html") ] ``` -------------------------------- ### Display Original Schema Source: https://github.com/helixdb/helix-py/blob/main/examples/cookbook/schema_demo.ipynb Retrieves and prints the current schema definition. Useful for inspecting the initial state of the schema. ```python print("\nOriginal Schema:\n") original_schema = schema.show_schema() ``` -------------------------------- ### Create Temporary Node Type Source: https://github.com/helixdb/helix-py/blob/main/examples/cookbook/schema_demo.ipynb Demonstrates creating a temporary node type 'Temp' with string and 64-bit integer properties. This is useful for testing or intermediate schema definitions. ```python schema.create_node( "Temp", { "prop1": "String", "prop2": "I64" } ) print("Current schema:\n\n" + str(schema)) ``` -------------------------------- ### Import Helix Library Source: https://github.com/helixdb/helix-py/blob/main/examples/chunking/chunking.ipynb Import the Helix library to access its functionalities. ```python import helix ``` -------------------------------- ### Sample Text List for Batch Chunking Source: https://github.com/helixdb/helix-py/blob/main/examples/chunking/chunking.ipynb A Python list containing multiple strings, where each string represents a document to be chunked. This is used for batch processing multiple documents simultaneously. ```python texts = [ "First document to chunk with some content for testing.", "Second document with different content for batch processing." ] ``` -------------------------------- ### Sample Text for Single Text Chunking Source: https://github.com/helixdb/helix-py/blob/main/examples/chunking/chunking.ipynb A large string variable containing sample text to be chunked. This is useful for testing the token chunker with realistic document content. ```python massive_text_blob = """ This is a massive text blob that we want to chunk into smaller pieces for processing. It contains multiple sentences and paragraphs that need to be divided appropriately to maintain context while fitting within token limits. When working with large documents, it is important to ensure that each chunk maintains enough context for downstream tasks, such as retrieval or summarization. Chunking strategies can vary depending on the use case, but the goal is always to balance context preservation with processing efficiency. The chunker should handle overlaps properly to ensure no important information is lost at chunk boundaries. For example, if a sentence is split between two chunks, the overlap ensures that both chunks retain the full meaning of the text. This is especially important in applications like document question answering, where missing a single sentence could lead to incorrect answers. Additionally, chunkers may need to account for different languages, code blocks, or special formatting, which can add complexity to the chunking process. This example demonstrates how the token chunker works with a realistic text sample that would be common in document processing and RAG (Retrieval-Augmented Generation) applications. The chunks will be created with specified token limits and overlap settings to optimize for both comprehension and processing efficiency. Each chunk will contain metadata about its position in the original text and token count for further processing. By using a robust chunking strategy, we can ensure that downstream models receive high-quality, context-rich input, improving the overall performance of NLP pipelines and applications. """ ``` -------------------------------- ### Run Minigrep Without Environment Variable Source: https://github.com/helixdb/helix-py/blob/main/examples/rag-demo/rag_rust_demo.ipynb Demonstrates running the minigrep program with a case-sensitive search. This is the default behavior when the IGNORE_CASE environment variable is not set. ```bash $ cargo run -- to poem.txt Compiling minigrep v0.1.0 (file:///projects/minigrep) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s Running `target/debug/minigrep to poem.txt` Are you nobody, too? How dreary to be somebody! ``` -------------------------------- ### Import necessary classes for Helix and Pydantic Source: https://github.com/helixdb/helix-py/blob/main/examples/llm_providers/providers.ipynb Imports the Client and MCPServer from helix.client and helix.mcp, along with BaseModel from pydantic. Also applies nest_asyncio to handle asyncio events. ```python from helix.client import Client from helix.mcp import MCPServer, ToolConfig from pydantic import BaseModel import nest_asyncio nest_asyncio.apply() ``` -------------------------------- ### Initialize Schema Management Source: https://context7.com/helixdb/helix-py/llms.txt Provides the basic import statement for the `Schema` class, which is used for programmatic creation, loading, and editing of HelixDB schemas, including nodes, edges, and vectors with typed properties and index definitions. ```python from helix import Schema ``` -------------------------------- ### Import Project Libraries Source: https://github.com/helixdb/helix-py/blob/main/examples/rag-demo/rag_rust_demo.ipynb Import all necessary libraries and modules for the helix-py project. This includes data processing tools, NLP models, and the helix client. ```python from chonkie import RecursiveChunker, RecursiveRules, RecursiveLevel from docling.document_converter import DocumentConverter from transformers import AutoTokenizer, AutoModel from rich.console import Console from rich.text import Text from typing import List, Tuple import numpy as np import os import torch from tqdm import tqdm import requests import helix from helix.client import Query from helix.types import Payload ``` -------------------------------- ### Utilize Text Embedding Interfaces Source: https://context7.com/helixdb/helix-py/llms.txt The SDK provides interfaces for OpenAI, Gemini, and VoyageAI embedders, each supporting `embed()` for single texts and `embed_batch()` for multiple texts. ```python from helix.embedding.openai_client import OpenAIEmbedder from helix.embedding.gemini_client import GeminiEmbedder from helix.embedding.voyageai_client import VoyageAIEmbedder ``` -------------------------------- ### Compare Schemas Source: https://github.com/helixdb/helix-py/blob/main/examples/cookbook/schema_demo.ipynb Compares the original schema definition with a recreated schema to ensure they are identical. This is crucial for validating schema operations. ```python print("\nVerify schemas have exact same content:") if original_schema == recreated_schema: print("Schemas have exact same content") else: print("Schemas do not have exact same content") ``` -------------------------------- ### Define and Use HelixDB Data Types Source: https://context7.com/helixdb/helix-py/llms.txt Demonstrates the creation and basic usage of Hnode, Hedge, and Hvector objects. Includes type aliasing for Payload and JSON parsing to Helix types. ```python from helix.types import Payload, Hnode, Hedge, Hvector, EdgeType, json_to_helix # Payload is a type alias for Dict[str, Any] payload: Payload = {"name": "John", "age": 30} # Create node objects user_node = Hnode( label="User", properties=[("name", "John"), ("age", 30)] ) user_node.id = 123 # Set after insertion print(user_node) # Output: Hnode(label=User, id=123, properties=[('name', 'John'), ('age', 30)]) # Create edge objects follows_edge = Hedge( label="Follows", properties=[("since", "2024-01-01")], from_node_label="User", to_node_label="User", edge_type=EdgeType.Node # EdgeType.Node or EdgeType.Vec ) # Create vector objects (extends Hnode) doc_vector = Hvector( label="Document", vector=[0.1, 0.2, 0.3, 0.4], properties=[("text", "Sample document")] ) print(doc_vector) # Output: Hvector(label=Document, id=None, vector=[0.1, 0.2, 0.3, 0.4], properties=[...]) # Parse JSON graph data to Helix types json_graph = ''' { "Nodes": [ {"Label": "Person1"}, {"Label": "Person2"} ], "Edges": [ {"Label": "knows", "Source": "Person1", "Target": "Person2"} ] } ''' nodes, edges = json_to_helix(json_graph) # Output: ([Hnode(label=Person1, ...), Hnode(label=Person2, ...)], # [Hedge(label=knows, from=Person1, to=Person2, ...)]) ```