### Install ML Dependencies and Run Examples Source: https://github.com/apache/hugegraph-ai/blob/main/README.md Install ML-specific dependencies using uv and activate the virtual environment. Then navigate to the hugegraph-ml directory to run example scripts. ```bash # Install ML dependencies (ml module is not in workspace) uv sync --extra ml source .venv/bin/activate # Run ML algorithms cd hugegraph-ml python examples/your_ml_example.py ``` -------------------------------- ### Install Dependencies and Run Tests Source: https://github.com/apache/hugegraph-ai/blob/main/README.md Clone the repository, install all development dependencies using uv, activate the virtual environment, and run tests for workspace members and path dependencies. This setup ensures the development environment is correctly configured. ```bash git clone https://github.com/apache/hugegraph-ai.git cd hugegraph-ai uv sync --all-extras # Install all optional dependency groups source .venv/bin/activate # Activate for easier command usage cd hugegraph-llm && pytest cd ../hugegraph-python-client && pytest cd ../hugegraph-ml && pytest # If tests exist ``` -------------------------------- ### Install HugeGraph AI from Source Source: https://context7.com/apache/hugegraph-ai/llms.txt Instructions for installing HugeGraph AI from source, including starting the HugeGraph Server via Docker and installing Python dependencies using uv. ```bash # Start HugeGraph Server via Docker docker run -itd --name=server -p 8080:8080 hugegraph/hugegraph git clone https://github.com/apache/hugegraph-ai.git cd hugegraph-ai # Install all workspace extras (LLM + optional vector DBs) uv sync --extra llm # For Milvus/Qdrant support: uv sync --extra vectordb source .venv/bin/activate # Launch the Gradio demo (http://127.0.0.1:8001) python -m hugegraph_llm.demo.rag_demo.app # Optional: custom host/port python -m hugegraph_llm.demo.rag_demo.app --host 0.0.0.0 --port 18001 ``` -------------------------------- ### Install hugegraph-python-client from Source Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-python-client/README.md Clone the repository and install dependencies using uv sync. Activate the virtual environment before proceeding. ```bash git clone https://github.com/apache/hugegraph-ai.git cd hugegraph-ai/hugegraph-python-client # Use uv sync to install dependencies (workspace member) uv sync # Automatically creates .venv and installs dependencies source .venv/bin/activate # Activate once - all commands below assume this environment ``` -------------------------------- ### Source Installation and Demo Source: https://github.com/apache/hugegraph-ai/blob/main/README.md Install dependencies using uv, activate the virtual environment, and run the RAG demo. Assumes Python 3.10+ and uv 0.7+ are installed. ```bash # 1. Start HugeGraph Server docker run -itd --name=server -p 8080:8080 hugegraph/hugegraph # 2. Clone and set up the project git clone https://github.com/apache/hugegraph-ai.git cd hugegraph-ai # 3. Install dependencies with workspace management # uv sync automatically creates venv (.venv) and installs base dependencies # NOTE: If download is slow, uncomment mirror lines in pyproject.toml or use: uv config --global index.url https://pypi.tuna.tsinghua.edu.cn/simple # Or create local uv.toml with mirror settings to avoid git diff (see uv.toml example in root) uv sync --extra llm # Install LLM-specific dependencies # Or install all optional dependencies: uv sync --all-extras # 4. Activate virtual environment (recommended for easier commands) source .venv/bin/activate # 5. Start the demo (no uv run prefix needed when venv activated) cd hugegraph-llm python -m hugegraph_llm.demo.rag_demo.app # Visit http://127.0.0.1:8001 ``` -------------------------------- ### Build Examples Index for Text2Gremlin Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-llm/README.md Create an index of example queries and their corresponding Gremlin statements using the 'build_examples_index' flow. This is used by text2gremlin examples. ```python from hugegraph_llm.flows.scheduler import SchedulerSingleton examples = [{"id": "natural language query", "gremlin": "g.V().hasLabel('person').valueMap()"}] res = SchedulerSingleton.get_instance().schedule_flow("build_examples_index", examples) print(res) ``` -------------------------------- ### Install Dependencies and Run RAG Demo Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-llm/AGENTS.md Installs project dependencies using uv, activates the virtual environment, and launches the main RAG demo application. Custom host and port can be specified. ```bash # Install dependencies and create virtual environment (uv already installed) uv sync # Activate virtual environment source .venv/bin/activate # Launch main RAG demo application python -m hugegraph_llm.demo.rag_demo.app # Custom host/port python -m hugegraph_llm.demo.rag_demo.app --host 127.0.0.1 --port 18001 ``` -------------------------------- ### Install dependencies and activate environment Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-llm/README.md Installs project dependencies using UV and activates the virtual environment. This command assumes you are in the project root and have already cloned the repository. ```bash # 4. Install dependencies and activate environment # NOTE: If download is slow, uncomment mirror lines in ../pyproject.toml or use: uv config --global index.url https://pypi.tuna.tsinghua.edu.cn/simple # Or create local uv.toml with mirror settings to avoid git diff (see uv.toml example in root) uv sync --extra llm # Automatically creates .venv and installs dependencies source .venv/bin/activate # Activate once - all commands below assume this environment ``` -------------------------------- ### build_examples_index Source: https://context7.com/apache/hugegraph-ai/llms.txt Vectorizes query/Gremlin example pairs and stores them in the vector index for use as few-shot context by `text2gremlin`. ```APIDOC ## `build_examples_index` — Index Gremlin Example Pairs Vectorizes query/Gremlin example pairs and stores them in the vector index for use as few-shot context by `text2gremlin`. ```python from hugegraph_llm.flows.scheduler import SchedulerSingleton examples = [ {"id": "list all persons", "gremlin": "g.V().hasLabel('Person').valueMap()"}, {"id": "count movies", "gremlin": "g.V().hasLabel('Movie').count()"}, {"id": "find actor by name", "gremlin": "g.V().has('Person','name',{name}).valueMap()"}, ] result = SchedulerSingleton.get_instance().schedule_flow("build_examples_index", examples) print(result) # {"indexed": 3} ``` ``` -------------------------------- ### Install hugegraph-python-client via pip Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-python-client/README.md Install the released package using uv or pip. Note that this might not be the latest version. ```bash # uv is optional, you can use pip directly uv pip install hugegraph-python # Note: may not the latest version, recommend to install from source # WIP: we will use 'hugegraph-python-client' as the package name soon ``` -------------------------------- ### Start HugeGraph Server from source Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-llm/README.md Starts the HugeGraph Server in a detached container, mapping port 8080. This is the first step when building from source. ```bash # 1. Start HugeGraph Server docker run -itd --name=server -p 8080:8080 hugegraph/hugegraph ``` -------------------------------- ### Launch RAG demo with custom host/port Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-llm/README.md Starts the RAG demo application with a specified host and port. Assumes the virtual environment is activated. ```bash # 6. (Optional) Custom host/port python -m hugegraph_llm.demo.rag_demo.app --host 127.0.0.1 --port 18001 ``` -------------------------------- ### Launch RAG demo Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-llm/README.md Starts the RAG demo application using the Python module. Assumes the virtual environment is activated. ```bash # 5. Launch RAG demo python -m hugegraph_llm.demo.rag_demo.app # Access at: http://127.0.0.1:8001 ``` -------------------------------- ### Markdown Task Checklist Example Source: https://github.com/apache/hugegraph-ai/blob/main/rules/plan.md This example demonstrates the required Markdown format for task checklists, including nested tasks, metadata tags for priority, dependencies, and associated requirements. ```markdown # 实现计划: 用户登录时的“记住我”功能 - [ ] 1. **研究与准备** - [ ] 1.1. 在现有代码库中查找用于管理用户会话或持久化 Token 的工具函数。 `(关联需求: S1)` - [ ] 1.2. 确认项目中统一的加密/解密工具,用于安全地存储 Token。 `(关联需求: S1)` `(依赖于: 1.1)` - [ ] 2. **后端实现** `[优先级: 高]` - [ ] 2.1. **TDD**: 编写单元测试,验证`rememberMe`为 true 时,登录 API 会生成持久化 Token。 `(关联需求: E1)` `(依赖于: 1.2)` - [ ] 2.2. 更新登录 API (`/api/auth/login`),实现 Token 生成与存储逻辑。 `(关联需求: E1)` `(依赖于: 2.1)` - [ ] 2.3. **TDD**: 编写集成测试,验证 Token 验证中间件的完整逻辑。 `(关联需求: R1)` `(依赖于: 2.2)` - [ ] 2.4. 实现 Token 验证中间件,处理持久化 Token 的验证和会话刷新。 `(关联需求: R1)` `(依赖于: 2.3)` - [ ] 3. **前端实现** `[优先级: 中]` - [ ] 3.1. 在`LoginForm.vue`组件中增加“记住我”复选框,并将其状态绑定到登录请求。 `(关联需求: U1)` `(依赖于: 2.2)` - [ ] 4. **端到端验证** `[优先级: 低]` - [ ] 4.1. 编写 E2E 测试,模拟用户从登录到关闭浏览器再到自动重连的全过程。 `(关联需求: E1, R1)` `(依赖于: 2.4, 3.1)` ``` -------------------------------- ### Install UV package manager Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-llm/README.md Installs the UV package manager using a curl script. This is a prerequisite for managing Python dependencies when building from source. ```bash # 2. Install UV package manager (if not already installed) curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Sync optional dependencies for vector databases Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-llm/README.md Installs optional dependencies required for using vector database backends like Milvus or Qdrant. Assumes the virtual environment is activated. ```bash # To use vector database backends (e.g., Milvus, Qdrant), sync the optional dependencies: uv sync --extra vectordb ``` -------------------------------- ### Index Gremlin Example Pairs for Few-Shot Learning Source: https://context7.com/apache/hugegraph-ai/llms.txt Vectorizes query/Gremlin example pairs and stores them in the vector index. This is used to provide few-shot context for the `text2gremlin` flow. ```python from hugegraph_llm.flows.scheduler import SchedulerSingleton examples = [ {"id": "list all persons", "gremlin": "g.V().hasLabel('Person').valueMap()"}, {"id": "count movies", "gremlin": "g.V().hasLabel('Movie').count()"}, {"id": "find actor by name", "gremlin": "g.V().has('Person','name',{name}).valueMap()"}, ] result = SchedulerSingleton.get_instance().schedule_flow("build_examples_index", examples) print(result) # {"indexed": 3} ``` -------------------------------- ### Start HugeGraph Server with Docker Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-llm/README.md Runs the HugeGraph Server in a detached container, mapping port 8080 and connecting it to the 'hugegraph-net' network. ```bash # 2. Start HugeGraph Server docker run -itd --name=server -p 8080:8080 --network hugegraph-net hugegraph/hugegraph ``` -------------------------------- ### Creating a Task Source: https://github.com/apache/hugegraph-ai/blob/main/vermeer-python-client/README.md Creates a new task in the Vermeer system. This example demonstrates creating a 'load' task. ```APIDOC ## Creating a Task ### Description Creates a new task in the Vermeer system. This example demonstrates creating a 'load' task. ### Method ```python client.tasks.create_task(create_task: TaskCreateRequest) ``` ### Parameters * **create_task** (TaskCreateRequest) - An object containing the details for the task creation. * **task_type** (str) - The type of task to create (e.g., 'load'). * **graph_name** (str) - The name of the graph to operate on. * **params** (dict) - A dictionary of parameters specific to the task type. ### Request Example ```python from pyvermeer.structure.task_data import TaskCreateRequest create_response = client.tasks.create_task( create_task=TaskCreateRequest( task_type='load', graph_name='DEFAULT-example', params={ "load.hg_pd_peers": "[\"127.0.0.1:8686\"]", "load.hugegraph_name": "DEFAULT/example/g", "load.hugegraph_password": "xxx", "load.hugegraph_username": "xxx", "load.parallel": "10", "load.type": "hugegraph" }, ) ) print(f"Create task response: {create_response.to_dict()}") ``` ### Response #### Success Response (200) Returns a dictionary representing the created task details. ``` -------------------------------- ### Mermaid Sequence Diagram Example Source: https://github.com/apache/hugegraph-ai/blob/main/rules/prompts/project-deep.md An example of a Mermaid sequence diagram illustrating system interactions, useful for visualizing complex business processes. ```mermaid flowchart TD A[Client] --> B(API Gateway) B --> C{Service A} C --> D[Database] ``` -------------------------------- ### Text to Gremlin Conversion Example Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-llm/README.md Use the 'text2gremlin' flow to convert natural language queries into Gremlin statements. Specify the number of examples, schema input, and desired output formats. ```python from hugegraph_llm.flows.scheduler import SchedulerSingleton scheduler = SchedulerSingleton.get_instance() response = scheduler.schedule_flow( "text2gremlin", "find people who worked with Alan Turing", 2, # example_num "hugegraph", # schema_input (graph name or schema) None, # gremlin_prompt_input (optional) ["template_gremlin", "raw_gremlin"], ) print(response.get("template_gremlin")) ``` -------------------------------- ### Pre-commit Hooks Source: https://github.com/apache/hugegraph-ai/blob/main/README.md Install and run pre-commit hooks to enforce code quality standards before committing changes. This includes running all configured hooks across the entire project. ```bash pre-commit install pre-commit run --all-files ``` -------------------------------- ### Start RAG Service with Docker Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-llm/README.md Pulls the latest RAG image and runs it in a detached container. It mounts a local .env file for configuration, maps port 8001, and connects to the 'hugegraph-net' network. ```bash # 3. Start RAG Service # docker pull hugegraph/rag:latest docker run -itd --name rag \ -v /path/to/your/hugegraph-llm/.env:/home/work/hugegraph-llm/.env \ -p 8001:8001 --network hugegraph-net hugegraph/rag ``` -------------------------------- ### Get Application URL with Ingress Source: https://github.com/apache/hugegraph-ai/blob/main/docker/charts/hg-llm/templates/NOTES.txt Use this when Ingress is enabled to construct the application URL. It iterates through configured hosts and paths. ```go-template {{- if .Values.ingress.enabled }} {{- range $host := .Values.ingress.hosts }} {{- range .paths }} http{{ if $.Values.ingress.tls }}s{{ end }}://{{ $host.host }}{{ .path }} {{- end }} {{- end }} {{- end }} ``` -------------------------------- ### HugeGraph AI Configuration Properties Source: https://context7.com/apache/hugegraph-ai/llms.txt Example configuration settings for the HugeGraph AI project, covering LLM providers, API keys, HugeGraph Server connection details, and optional vector database settings. ```properties # ── LLM provider selection ────────────────────────────────────────────────── LANGUAGE=EN # EN | CN (prompt language) CHAT_LLM_TYPE=openai # openai | litellm | ollama/local EXTRACT_LLM_TYPE=openai TEXT2GQL_LLM_TYPE=openai EMBEDDING_TYPE=openai RERANKER_TYPE= # cohere | siliconflow (leave empty to disable) KEYWORD_EXTRACT_TYPE=llm # llm | textrank | hybrid # ── OpenAI ────────────────────────────────────────────────────────────────── OPENAI_CHAT_API_KEY=sk-... OPENAI_CHAT_LANGUAGE_MODEL=gpt-4.1-mini OPENAI_CHAT_TOKENS=8192 OPENAI_EMBEDDING_API_KEY=sk-... OPENAI_EMBEDDING_MODEL=text-embedding-3-small # ── Ollama (local) ─────────────────────────────────────────────────────────── # CHAT_LLM_TYPE=ollama/local # OLLAMA_CHAT_LANGUAGE_MODEL=llama2 # OLLAMA_CHAT_HOST=127.0.0.1 # OLLAMA_CHAT_PORT=11434 # OLLAMA_EMBEDDING_MODEL=nomic-embed-text # ── LiteLLM (multi-provider proxy) ────────────────────────────────────────── # CHAT_LLM_TYPE=litellm # LITELLM_CHAT_API_KEY=sk-... # LITELLM_CHAT_API_BASE=https://your-proxy.example.com # LITELLM_CHAT_LANGUAGE_MODEL=openai/gpt-4.1-mini # ── HugeGraph Server ───────────────────────────────────────────────────────── GRAPH_URL=127.0.0.1:8080 GRAPH_NAME=hugegraph GRAPH_USER=admin GRAPH_PWD=admin GRAPH_SPACE= # leave empty unless graphspaces are enabled MAX_GRAPH_ITEMS=30 MAX_GRAPH_PATH=10 EDGE_LIMIT_PRE_LABEL=8 VECTOR_DIS_THRESHOLD=0.9 TOPK_PER_KEYWORD=1 TOPK_RETURN_RESULTS=20 # ── Vector DB (optional) ───────────────────────────────────────────────────── QDRANT_HOST= # leave empty to use built-in FAISS QDRANT_PORT=6333 MILVUS_HOST= MILVUS_PORT=19530 # ── Admin / Auth ───────────────────────────────────────────────────────────── ENABLE_LOGIN=False ADMIN_TOKEN=xxxx USER_TOKEN=4321 ``` -------------------------------- ### Scheduler Core Data Structure Example Source: https://github.com/apache/hugegraph-ai/blob/main/spec/hugegraph-llm/fixed_flow/design.md Illustrates the internal data structure of the Scheduler, specifically the `pipeline_pool` which manages reusable pipeline instances for different workflow types. ```python # Scheduler核心数据结构 Scheduler.pipeline_pool: Dict[str, Any] = { "build_vector_index": { "manager": GPipelineManager(), "flow": BuildVectorIndexFlow(), }, "graph_extract": { "manager": GPipelineManager(), "flow": GraphExtractFlow(), } } ``` -------------------------------- ### Code Quality Checks Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-llm/README.md Commands to format and check code quality using Ruff, and to install Git hooks via pre-commit. ```bash # Ruff is used for linting and formatting: # ruff format . # ruff check . # Enable Git hooks via pre-commit: # pre-commit install (in the root dir) # pre-commit run --all-files ``` -------------------------------- ### Clone and Deploy HugeGraph AI with Docker Compose Source: https://context7.com/apache/hugegraph-ai/llms.txt Use this command to clone the repository, set up environment variables, and start HugeGraph Server and the RAG Service using Docker Compose. ```bash git clone https://github.com/apache/hugegraph-ai.git cd hugegraph-ai # Copy and edit environment template (set PROJECT_PATH, API keys, etc.) cp docker/env.template docker/.env # Create empty .env for hugegraph-llm if it doesn't exist touch hugegraph-llm/.env # Start services cd docker docker compose -f docker-compose-network.yml up -d # Verify docker compose -f docker-compose-network.yml ps # HugeGraph Server: http://localhost:8080 # RAG Service API: http://localhost:8001 ``` -------------------------------- ### Create a Load Task with Vermeer Client Source: https://github.com/apache/hugegraph-ai/blob/main/vermeer-python-client/README.md Creates a 'load' type task for the Vermeer client. This example requires specifying graph details, authentication credentials, and load parameters. Error handling is included for robustness. ```python from pyvermeer.structure.task_data import TaskCreateRequest # Example for creating a task try: create_response = client.tasks.create_task( create_task=TaskCreateRequest( task_type='load', graph_name='DEFAULT-example', params={ "load.hg_pd_peers": "[\"127.0.0.1:8686\"]", "load.hugegraph_name": "DEFAULT/example/g", "load.hugegraph_password": "xxx", "load.hugegraph_username": "xxx", "load.parallel": "10", "load.type": "hugegraph" }, ) ) print(f"Create task response: {create_response.to_dict()}") except Exception as e: print(f"Error creating task: {e}") ``` -------------------------------- ### build_schema Source: https://context7.com/apache/hugegraph-ai/llms.txt Auto-generates a HugeGraph-compatible JSON schema from raw documents using an LLM, optionally guided by example queries. ```APIDOC ## `build_schema` — Auto-generate Graph Schema from Text Asks an LLM to propose a HugeGraph-compatible JSON schema from raw documents, optionally guided by example queries and a few-shot reference schema. ```python from hugegraph_llm.flows.scheduler import SchedulerSingleton texts = ["This dataset covers movies, actors, directors and their relationships."] query_examples = ["Who directed The Godfather?", "Which actors appeared in Scarface?"] schema_json = SchedulerSingleton.get_instance().schedule_flow( "build_schema", texts=texts, query_examples=query_examples, few_shot_schema=None, ) import json print(json.loads(schema_json)) # {"vertices": [...], "edges": [...]} ``` ``` -------------------------------- ### Auto-generate HugeGraph Schema from Text Source: https://context7.com/apache/hugegraph-ai/llms.txt Uses an LLM to propose a JSON schema for HugeGraph based on provided text documents. Can be guided by example queries and a reference schema. ```python from hugegraph_llm.flows.scheduler import SchedulerSingleton texts = ["This dataset covers movies, actors, directors and their relationships."] query_examples = ["Who directed The Godfather?", "Which actors appeared in Scarface?"] schema_json = SchedulerSingleton.get_instance().schedule_flow( "build_schema", texts=texts, query_examples=query_examples, few_shot_schema=None, ) import json print(json.loads(schema_json)) ``` -------------------------------- ### Clone and set up HugeGraph-LLM project Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-llm/README.md Clones the HugeGraph-AI repository and navigates into the project directory. This is the initial step for building from source. ```bash # 3. Clone and setup project git clone https://github.com/apache/hugegraph-ai.git cd hugegraph-ai # Configure environment (see config.md for detailed options), .env will auto create if not exists ``` -------------------------------- ### Importing and Using Configuration Classes in Python Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-llm/config.md Shows how to directly import and instantiate `LLMConfig` and `HugeGraphConfig` classes in Python to manage and access configuration settings programmatically. ```python from hugegraph_llm.config.llm_config import LLMConfig from hugegraph_llm.config.hugegraph_config import HugeGraphConfig # 创建配置实例 llm_config = LLMConfig() graph_config = HugeGraphConfig() print(f"当前语言: {llm_config.language}") print(f"聊天模型类型: {llm_config.chat_llm_type}") print(f"图数据库地址: {graph_config.graph_url}") print(f"数据库名称: {graph_config.graph_name}") ``` -------------------------------- ### Set up environment with Docker Compose Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-llm/README.md Copies the environment template and creates a .env file for configuration. Ensure PROJECT_PATH is set correctly. This is part of the Docker Compose deployment option. ```bash # 1. Set up environment cp docker/env.template docker/.env # Edit docker/.env and set PROJECT_PATH to your actual project path # See "config.md" for all available configuration options # If there is not a configuration file (named .env) under hugegraph-llm, run the following command cd hugegraph-llm && touch .env && cd .. ``` -------------------------------- ### Clone and Deploy Docker Source: https://github.com/apache/hugegraph-ai/blob/main/README.md Clone the repository and set up the environment using Docker Compose. Ensure to edit the .env file for project path configuration. ```bash git clone https://github.com/apache/hugegraph-ai.git cd hugegraph-ai cp docker/env.template docker/.env # Edit docker/.env to set your PROJECT_PATH cd docker # same as `docker-compose` (Legacy) docker compose -f docker-compose-network.yml up -d # Access services: # - HugeGraph Server: http://localhost:8080 # - RAG Service: http://localhost:8001 ``` -------------------------------- ### Initialize the Client Source: https://github.com/apache/hugegraph-ai/blob/main/vermeer-python-client/README.md Initializes the PyVermeerClient with the specified IP address, port, authentication token, and log level. ```APIDOC ## Initialize the Client ### Description Initializes the PyVermeerClient with the specified IP address, port, authentication token, and log level. ### Method ```python PyVermeerClient(ip: str, port: int, token: str = "", log_level: str = "DEBUG") ``` ### Parameters * **ip** (str) - The IP address of the Vermeer server. * **port** (int) - The port number of the Vermeer server. * **token** (str, optional) - The authentication token. Defaults to "". * **log_level** (str, optional) - The logging level. Defaults to "DEBUG". ### Request Example ```python from pyvermeer.client.client import PyVermeerClient client = PyVermeerClient(ip="127.0.0.1", port=8688, token="", log_level="DEBUG") print("Client initialized successfully.") ``` ``` -------------------------------- ### Basic Configuration with OpenAI Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-llm/config.md This properties file configures basic settings, specifies OpenAI as the LLM provider for chat, extraction, and text2gql, and sets up API keys and model names for OpenAI. It also includes connection details for HugeGraph. ```properties # 基础设置 LANGUAGE=EN CHAT_LLM_TYPE=openai EXTRACT_LLM_TYPE=openai TEXT2GQL_LLM_TYPE=openai EMBEDDING_TYPE=openai # OpenAI 配置 OPENAI_CHAT_API_KEY=your-openai-api-key OPENAI_CHAT_LANGUAGE_MODEL=gpt-4.1-mini OPENAI_EMBEDDING_API_KEY=your-openai-embedding-key OPENAI_EMBEDDING_MODEL=text-embedding-3-small # HugeGraph 配置 GRAPH_URL=127.0.0.1:8080 GRAPH_NAME=hugegraph GRAPH_USER=admin GRAPH_PWD=your-password ``` -------------------------------- ### text2gremlin Source: https://context7.com/apache/hugegraph-ai/llms.txt Converts natural language questions to Gremlin traversals using the graph schema and optional few-shot examples. ```APIDOC ## `text2gremlin` — Natural Language to Gremlin Query Converts a natural-language question to a Gremlin traversal using the graph schema and optional few-shot example pairs retrieved from the vector index. ```python from hugegraph_llm.flows.scheduler import SchedulerSingleton result = SchedulerSingleton.get_instance().schedule_flow( "text2gremlin", "find all movies featuring Al Pacino", 2, # example_num: number of retrieved few-shot examples (0 = zero-shot) "hugegraph", # schema_input: graph name or JSON schema None, # gremlin_prompt_input: custom prompt template (None = default) ["template_gremlin", "raw_gremlin", "template_execution_result"], ) print(result["template_gremlin"]) # "g.V().has('Person','name','Al Pacino').out('ActedIn').valueMap()" print(result["raw_gremlin"]) # "g.V().hasLabel('Person').has('name','Al Pacino').out('ActedIn').values('name')" print(result["template_execution_result"]) # [{"name": ["The Godfather"]}, {"name": ["Scarface"]}, ...] ``` ``` -------------------------------- ### Initialize PyVermeerClient and Create Data-Load Task Source: https://context7.com/apache/hugegraph-ai/llms.txt Initializes the PyVermeerClient and demonstrates creating a data-load task from HugeGraph into Vermeer. Ensure the client is configured with correct connection details and authentication if required. ```python from pyvermeer.client.client import PyVermeerClient from pyvermeer.structure.task_data import TaskCreateRequest # Initialize client client = PyVermeerClient(ip="127.0.0.1", port=8688, token="", log_level="INFO") # Create a data-load task from HugeGraph into Vermeer try: response = client.tasks.create_task( create_task=TaskCreateRequest( task_type="load", graph_name="DEFAULT-example", params={ "load.hg_pd_peers": "[\"127.0.0.1:8686\"]", "load.hugegraph_name": "DEFAULT/example/g", "load.hugegraph_username": "admin", "load.hugegraph_password": "admin", "load.parallel": "10", "load.type": "hugegraph", }, ) ) print(response.to_dict()) except Exception as e: print(f"Task creation failed: {e}") ``` -------------------------------- ### Initialize Vermeer Python Client Source: https://github.com/apache/hugegraph-ai/blob/main/vermeer-python-client/README.md Initializes the PyVermeerClient with specified IP, port, token, and log level. Ensure the client is configured with correct connection details. ```python from pyvermeer.client.client import PyVermeerClient # Initialize the client client = PyVermeerClient(ip="127.0.0.1", port=8688, token="", log_level="DEBUG") print("Client initialized successfully.") ``` -------------------------------- ### RAG (vector-only) Query Example Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-llm/README.md Execute the 'rag_vector_only' flow via the Scheduler API for vector-based RAG queries. Enable vector_search and set vector_only_answer to true. ```python from hugegraph_llm.flows.scheduler import SchedulerSingleton scheduler = SchedulerSingleton.get_instance() res = scheduler.schedule_flow( "rag_vector_only", query="Summarize the career of Ada Lovelace.", vector_only_answer=True, vector_search=True ) print(res.get("vector_only_answer")) ``` -------------------------------- ### RAG (graph-only) Query Example Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-llm/README.md Invoke the 'rag_graph_only' flow using the Scheduler API for graph-based RAG queries. Set graph_only_answer to true for graph-specific results. ```python from hugegraph_llm.flows.scheduler import SchedulerSingleton scheduler = SchedulerSingleton.get_instance() res = scheduler.schedule_flow( "rag_graph_only", query="Tell me about Al Pacino.", graph_only_answer=True, vector_only_answer=False, raw_answer=False, gremlin_tmpl_num=-1, gremlin_prompt=None, ) print(res.get("graph_only_answer")) ``` -------------------------------- ### Define Graph Structures and Initialize Graph Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-python-client/README.md Initialize the client, define schema elements like property keys, vertex labels, and edge labels, then create vertices and edges. Assumes HugeGraph API version >= v3. ```python from pyhugegraph.client import PyHugeClient # Initialize the client # For HugeGraph API version ≥ v3: (Or enable graphspace function) # - The 'graphspace' parameter becomes relevant if graphspaces are enabled.(default name is 'DEFAULT') # - Otherwise, the graphspace parameter is optional and can be ignored. client = PyHugeClient("127.0.0.1", "8080", user="admin", pwd="admin", graph="hugegraph", graphspace="DEFAULT") """ Note: Could refer to the official REST-API doc of your HugeGraph version for accurate details. If some API is not as expected, please submit a issue or contact us. """ schema = client.schema() schema.propertyKey("name").asText().ifNotExist().create() schema.propertyKey("birthDate").asText().ifNotExist().create() schema.vertexLabel("Person").properties("name", "birthDate").usePrimaryKeyId().primaryKeys("name").ifNotExist().create() schema.vertexLabel("Movie").properties("name").usePrimaryKeyId().primaryKeys("name").ifNotExist().create() schema.edgeLabel("ActedIn").sourceLabel("Person").targetLabel("Movie").ifNotExist().create() print(schema.getVertexLabels()) print(schema.getEdgeLabels()) print(schema.getRelations()) # Init Graph g = client.graph() v_al_pacino = g.addVertex("Person", {"name": "Al Pacino", "birthDate": "1940-04-25"}) v_robert = g.addVertex("Person", {"name": "Robert De Niro", "birthDate": "1943-08-17"}) v_godfather = g.addVertex("Movie", {"name": "The Godfather"}) v_godfather2 = g.addVertex("Movie", {"name": "The Godfather Part II"}) v_godfather3 = g.addVertex("Movie", {"name": "The Godfather Coda The Death of Michael Corleone"}) g.addEdge("ActedIn", v_al_pacino.id, v_godfather.id, {}) g.addEdge("ActedIn", v_al_pacino.id, v_godfather2.id, {}) g.addEdge("ActedIn", v_al_pacino.id, v_godfather3.id, {}) g.addEdge("ActedIn", v_robert.id, v_godfather2.id, {}) res = g.getVertexById(v_al_pacino.id).label print(res) g.close() ``` -------------------------------- ### Get Application URL with NodePort Source: https://github.com/apache/hugegraph-ai/blob/main/docker/charts/hg-llm/templates/NOTES.txt This snippet retrieves the NodePort and Node IP to construct the application URL when the service type is NodePort. It requires kubectl to be configured. ```bash export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ include "hg-llm.fullname" . }}) export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath="{.items[0].status.addresses[0].address}") echo http://$NODE_IP:$NODE_PORT ``` -------------------------------- ### Accessing LLM and HugeGraph Settings in Python Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-llm/config.md Demonstrates how to import and use the `llm_settings` and `huge_settings` objects to access configuration values for LLM and HugeGraph within a Python application. ```python from hugegraph_llm.config import llm_settings, huge_settings # 使用 LLM 配置 print(f"当前语言: {llm_settings.language}") print(f"聊天模型类型: {llm_settings.chat_llm_type}") # 使用图数据库配置 print(f"图数据库地址: {huge_settings.graph_url}") print(f"数据库名称: {huge_settings.graph_name}") ``` -------------------------------- ### Get Graph Index Information using Python Source: https://context7.com/apache/hugegraph-ai/llms.txt Retrieves statistics about the current vector and graph indexes, such as chunk count and vertex/edge counts. Requires the SchedulerSingleton from hugegraph_llm.flows.scheduler. ```python from hugegraph_llm.flows.scheduler import SchedulerSingleton info = SchedulerSingleton.get_instance().schedule_flow("get_graph_index_info") print(info) # { # "chunk_index_size": 142, # "vid_index_size": 1482, # "graph_vertex_count": 1482, # "graph_edge_count": 8903 # } ``` -------------------------------- ### Connect to HugeGraph Server using PyHugeClient Source: https://context7.com/apache/hugegraph-ai/llms.txt Establishes a connection to the HugeGraph server using the low-level Python SDK. Requires server address, credentials, and graph name. The `graphspace` parameter is optional and used only when the graphspaces feature is enabled. ```python from pyhugegraph.client import PyHugeClient # Connect (graphspace required only when graphspaces feature is enabled on server) client = PyHugeClient( "127.0.0.1", "8080", user="admin", pwd="admin", graph="hugegraph", graphspace="DEFAULT" # omit if not using graphspaces ) ``` -------------------------------- ### Get Application URL with LoadBalancer Source: https://github.com/apache/hugegraph-ai/blob/main/docker/charts/hg-llm/templates/NOTES.txt This code retrieves the LoadBalancer IP and constructs the application URL. It includes a note about potential delays for the LoadBalancer IP and a command to monitor its status. ```bash export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include "hg-llm.fullname" . }} --template "{{ range (index .status.loadBalancer.ingress 0) }}{{.}}{{ end }}") echo http://$SERVICE_IP:{{ .Values.service.port }} ``` -------------------------------- ### Natural Language to Gremlin Query Conversion Source: https://context7.com/apache/hugegraph-ai/llms.txt Converts natural language questions into Gremlin traversals. It uses the graph schema and optional few-shot examples retrieved from the vector index for context. ```python from hugegraph_llm.flows.scheduler import SchedulerSingleton result = SchedulerSingleton.get_instance().schedule_flow( "text2gremlin", "find all movies featuring Al Pacino", 2, # example_num: number of retrieved few-shot examples (0 = zero-shot) "hugegraph", # schema_input: graph name or JSON schema None, # gremlin_prompt_input: custom prompt template (None = default) ["template_gremlin", "raw_gremlin", "template_execution_result"], ) print(result["template_gremlin"]) # "g.V().has('Person','name','Al Pacino').out('ActedIn').valueMap()" print(result["raw_gremlin"]) # "g.V().hasLabel('Person').has('name','Al Pacino').out('ActedIn').values('name')" print(result["template_execution_result"]) # [{"name": ["The Godfather"]}, {"name": ["Scarface"]}, ...] ``` -------------------------------- ### Update configuration files Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-llm/README.md Updates configuration files using a Python module. Assumes the virtual environment is activated. ```bash # Update configuration files python -m hugegraph_llm.config.generate --update ``` -------------------------------- ### Initialize KgBuilder and Chain Operations Source: https://github.com/apache/hugegraph-ai/wiki/Construct-knowledge-graph-in-hugegraph-by-LLM Initializes the KgBuilder with an LLM and chains operations like importing schema, extracting triples, disambiguating word senses, and committing to HugeGraph. Ensure your HTTP proxy is set if accessing OpenAI API via proxy. ```python from hugegraph_llm.llms.init_llm import LLMs from hugegraph_llm.operators.kg_construction_task import KgBuilder TEXT = "" builder = KgBuilder(LLMs().get_llm()) ( builder .import_schema(from_hugegraph="talent_graph").print_result() .extract_triples(TEXT).print_result() .disambiguate_word_sense().print_result() .commit_to_hugegraph() .run() ) ``` -------------------------------- ### Convert Natural Language to Gremlin via REST API Source: https://context7.com/apache/hugegraph-ai/llms.txt Translates natural language queries into Gremlin statements. Supports multiple output types including template Gremlin, raw Gremlin, and execution results. Specify `example_num` to control the number of examples returned. ```bash curl -X POST http://localhost:8001/text2gremlin \ -H "Content-Type: application/json" \ -d '{ "query": "find people who worked with Alan Turing", "example_num": 2, "output_types": ["template_gremlin", "raw_gremlin", "template_execution_result"] }' # Response: # { # "template_gremlin": "g.V().has('Person','name','Alan Turing').both('WorkedWith').valueMap()", # "raw_gremlin": "...", # "template_execution_result": [...], # "raw_execution_result": [...], # "match_result": [...] # } ``` -------------------------------- ### Ruff Formatting and Checking Source: https://github.com/apache/hugegraph-ai/blob/main/README.md Use Ruff for code formatting and linting. Run 'ruff format' to format the code and 'ruff check' to identify and report linting issues. ```bash ruff format . ruff check . ``` -------------------------------- ### Configuration for Ollama LLM Backend Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-llm/config.md This properties file configures the system to use Ollama as the LLM provider for chat, extraction, and text2gql, specifying local Ollama models. It also includes host and port configurations for Ollama services. ```properties # 使用 Ollama CHAT_LLM_TYPE=ollama/local EXTRACT_LLM_TYPE=ollama/local TEXT2GQL_LLM_TYPE=ollama/local EMBEDDING_TYPE=ollama/local # Ollama 模型配置 OLLAMA_CHAT_LANGUAGE_MODEL=llama2 OLLAMA_EXTRACT_LANGUAGE_MODEL=llama2 OLLAMA_TEXT2GQL_LANGUAGE_MODEL=llama2 OLLAMA_EMBEDDING_MODEL=nomic-embed-text # Ollama 服务配置(如果需要自定义) OLLAMA_CHAT_HOST=127.0.0.1 OLLAMA_CHAT_PORT=11434 OLLAMA_EXTRACT_HOST=127.0.0.1 OLLAMA_EXTRACT_PORT=11434 OLLAMA_TEXT2GQL_HOST=127.0.0.1 OLLAMA_TEXT2GQL_PORT=11434 OLLAMA_EMBEDDING_HOST=127.0.0.1 OLLAMA_EMBEDDING_PORT=11434 ``` -------------------------------- ### Create Vertices and Edges Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-python-client/README.md Creates vertices with properties and then an edge connecting two vertices, also with properties. ```python # Create vertices v1 = client.graph().addVertex('person').property('name', 'John').property('age', 29).create() v2 = client.graph().addVertex('person').property('name', 'Jane').property('age', 25).create() # Create an edge client.graph().addEdge(v1, 'knows', v2).property('since', '2020').create() ``` -------------------------------- ### RAG Index Build Flow Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-llm/quick_start.md Visualizes the process of building a RAG index, including text segmentation, vectorization, and storage in both vector and graph databases. ```mermaid graph TD; A[Raw Text] --> B[Text Segmentation] B --> C[Vectorization] C --> D[Store in Vector Database] A --> F[Text Segmentation] F --> G[LLM extracts graph based on schema and segmented text] G --> H[Store graph in Graph Database, automatically vectorize vertices and store in Vector Database] I[Retrieve vertices from Graph Database] --> J[Vectorize vertices and store in Vector Database Note: Incremental update] ``` -------------------------------- ### Text2Gremlin: Build Vector Template Index (Optional) Source: https://github.com/apache/hugegraph-ai/blob/main/hugegraph-llm/quick_start.md Vectorizes query/Gremlin pairs from sample files and stores them in the vector database. This is an optional step for building a reference for Gremlin query generation. ```mermaid graph TD; A[Gremlin Pairs File] --> C[Vectorize query] C --> D[Store in Vector Database] F[Natural Language Query] --> G[Search for the most similar query in the Vector Database (If no Gremlin pairs exist in the Vector Database, default files will be automatically vectorized) and retrieve the corresponding Gremlin] G --> H[Add the matched pair to the prompt and use LLM to generate the Gremlin corresponding to the Natural Language Query] ```