### Install Lingxi and Set Up Environment Variables Source: https://context7.com/lingxi-agent/lingxi/llms.txt This snippet shows how to install the Lingxi framework and configure environment variables required for its operation. It includes installing dependencies, creating a .env file with LLM provider, model, and API keys, and commands to start the LangGraph Studio. ```bash # Install dependencies pip install -e . # Create .env file cat > .env << EOF LLM_PROVIDER=anthropic LLM_MODEL=claude-3-5-haiku-latest ANTHROPIC_API_KEY=sk-ant-api03-... OPENAI_API_KEY=sk-proj-... GITHUB_TOKEN=github_pat_... EOF # Start LangGraph Studio langgraph dev --no-reload # Or with uv package manager uv run --env-file .env langgraph dev --no-reload ``` -------------------------------- ### Install Project Dependencies (Bash) Source: https://github.com/lingxi-agent/lingxi/blob/master/CLAUDE.md Commands to install project dependencies using pip or uv. Pip is the standard Python package installer, while uv is a faster alternative. Ensure you have the necessary environment file for uv. ```bash # Install dependencies pip install -e . # Or using uv (recommended) uv run --env-file .env [command] ``` -------------------------------- ### Load Runtime Configuration from GitHub Issue URL (Python) Source: https://github.com/lingxi-agent/lingxi/blob/master/src/agent/README.md Handles runtime environment configuration setup by loading settings from a GitHub issue URL. The `RuntimeConfig` class is a singleton that manages configuration, and this method provides a specific entry point for loading from a URL. ```python import os class RuntimeConfig: _instance = None def __init__(self): if RuntimeConfig._instance: raise RuntimeError("Call instance() instead") else: self.config = {} RuntimeConfig._instance = self @classmethod def instance(cls): if cls._instance is None: cls() return cls._instance def load_from_github_issue_url(self, issue_url): """Setup the runtime config based on a given issue URL.""" print(f"Loading runtime configuration from: {issue_url}") # Placeholder for actual logic to fetch and parse issue content # This would typically involve GitHub API calls or web scraping try: # Example: fetch issue content, parse it for config details self.config['source'] = issue_url self.config['setting1'] = 'value1' # Fictional config setting print("Configuration loaded successfully.") except Exception as e: print(f"Failed to load configuration from {issue_url}: {e}") raise # Example usage: # config_manager = RuntimeConfig.instance() # try: # config_manager.load_from_github_issue_url("https://github.com/user/repo/issues/123") # print(config_manager.config) # except Exception as e: # print("Could not initialize runtime config.") ``` -------------------------------- ### Run LangGraph Studio (Bash) Source: https://github.com/lingxi-agent/lingxi/blob/master/CLAUDE.md Commands to launch the LangGraph Studio development server for the Lingxi project. It can be started directly or using uv with an environment file. The `--no-reload` flag prevents automatic server restarts. ```bash # Start LangGraph Studio langgraph dev --no-reload # Or with uv uv run --env-file .env langgraph dev --no-reload ``` -------------------------------- ### Define a Custom Tool (Python) Source: https://github.com/lingxi-agent/lingxi/blob/master/CLAUDE.md Example of how to define a new tool for use within the Lingxi agent framework. Tools are decorated with `@tool` and require comprehensive docstrings detailing their purpose, parameters, and return values. ```python @tool def my_tool(param: str) -> str: """Tool description with parameter and return info.""" return result ``` -------------------------------- ### Use view_file_content Tool to Read File Content Source: https://context7.com/lingxi-agent/lingxi/llms.txt Illustrates how to use the `view_file_content` tool to read the content of a specific file. It shows examples of viewing the entire file and a specific line range. ```python from agent.tool_set.sepl_tools import view_file_content # View entire file result = view_file_content.invoke({ "file_name": "src/auth/oauth.py" }) print(result) # Output: # 1 import requests # 2 from typing import Optional # 3 # 4 class OAuthHandler: # 5 def __init__(self, client_id: str): # 6 self.client_id = client_id # [... full file with line numbers ...] # View specific line range result = view_file_content.invoke({ "file_name": "src/auth/oauth.py", "view_range": [50, 75] }) print(result) # Output: # ``` -------------------------------- ### Define System Prompt for File Relevancy Explanation (Python) Source: https://github.com/lingxi-agent/lingxi/blob/master/src/agent/README.md Defines a system prompt template used in the `search_relevant_files` tool. This prompt instructs the LLM to explain the relevancy of files retrieved from a vector database, guiding the LLM's output format and focus. ```python RELEVANT_FILE_EXPLANATION_SYSTEM_PROMPT = """You are an AI assistant. Your task is to explain the relevancy of the provided files based on the user's query and the content of the files. For each file, provide a concise explanation of why it is relevant to the query. Focus on the specific code snippets or functionalities that address the user's needs. Output your response in JSON format, where each entry contains the 'file_path' and a detailed 'explanation' of its relevancy.""" ``` -------------------------------- ### Create and Invoke ReACT Agent with Tools - Python Source: https://github.com/lingxi-agent/lingxi/blob/master/README.md Illustrates the creation and invocation of a ReACT agent using `create_react_agent` from LangGraph, integrating custom tools. The example shows how to instantiate an LLM (ChatAnthropic), define a list of tools, and pass them along with an optional system prompt to the agent constructor. It then demonstrates invoking the agent with different human messages to solve problems using the provided tools. ```python # graph.py from langchain_anthropic import ChatAnthropic from langchain_core.messages import HumanMessage from langgraph.prebuilt import create_react_agent from tools import multiply, multiply_by_max # Load the example tools above llm = ChatAnthropic(model="claude-3-5-haiku-latest", temperature=0.0) tools = [multiply, multiply_by_max] # Define the tools for the agent using the created tools above problem_solver_agent = create_react_agent( llm, tools=tools, # Required for ReACT agents prompt="You must solve the given problems!" # Optional system prompt ) # Example prompts problem_solver_agent.invoke({"messages": [ HumanMessage(content="What is 2*5") ]}) problem_solver_agent.invoke({"messages": [ HumanMessage(content="What is 2 mutlipled by the max of this list: [5, 10, 15]") ]}) ``` -------------------------------- ### Execute Shell Commands with run_shell_cmd Tool Source: https://context7.com/lingxi-agent/lingxi/llms.txt Shows how to execute shell commands using the run_shell_cmd tool. Examples include running a single command like `pytest`, chaining multiple commands with `&&`, and attempting to run a background process. This tool is useful for integrating with existing command-line tools and scripts. ```python from agent.tool_set.sepl_tools import run_shell_cmd # Run a single command result = run_shell_cmd.invoke({ "command": "pytest tests/test_oauth.py -v" }) print(result) # Run multiple commands with shell operators result = run_shell_cmd.invoke({ "command": "python -m pip install pytest-cov && pytest tests/ --cov=src" }) # Run background process (not recommended for long-running processes) result = run_shell_cmd.invoke({ "command": "python manage.py runserver &" }) ``` -------------------------------- ### Load Runtime Configuration from SWE-Bench Instance Source: https://context7.com/lingxi-agent/lingxi/llms.txt This Python code shows how to load runtime configuration from a SWE-Bench instance ID. It initializes RuntimeConfig, loads the instance into a SWEREx Docker container, and accesses details like instance ID, issue description, and runtime type. It also includes an example of extracting a git diff from the SWEREx container. ```python from agent.runtime_config import RuntimeConfig rc = RuntimeConfig() # Load SWE-Bench instance into SWEREx Docker container instance_id = "django__django-11099" rc.load_from_swe_rex_docker_instance(instance_id) # Configuration is now ready print(f"Instance: {rc.swe_instance['instance_id']}") # django__django-11099 print(f"Issue: {rc.issue_desc}") # Problem statement print(f"Runtime: {rc.runtime_type}") # RuntimeType.SWEREX print(f"Container path: {rc.proj_path}") # /testbed # Extract git diff from SWEREx container patch = rc.extract_git_diff_swerex_wrapper() print(patch) # Git diff output ``` -------------------------------- ### Define Tools with Type Hints - Python Source: https://github.com/lingxi-agent/lingxi/blob/master/README.md Demonstrates how to define custom tools for LangGraph agents using Python's `@tool` decorator and type hints for arguments and return values. This method automatically parses function signatures into tool descriptions usable by the agent. It includes examples for simple multiplication and a more complex function involving list manipulation. ```python # tools.py from langchain_core.tools import tool # Via type hints @tool def multiply(a: int, b: int) -> int: """Multiply two numbers.""" return a * b from typing import Annotated, List # Via annotated type hints @tool def multiply_by_max( a: Annotated[int, "scale factor"], b: Annotated[List[int], "list of ints over which to take maximum"], ) -> int: """Multiply a by the maximum of b.""" return a * max(b) ``` -------------------------------- ### Python: Create and Compile LangGraph StateGraph Source: https://github.com/lingxi-agent/lingxi/blob/master/README.md Defines a multi-agent workflow using LangGraph's StateGraph. It includes setting up agents, defining nodes for agent invocation, constructing the graph edges, and finally compiling the graph for execution. This example utilizes prebuilt agents and custom tools. ```python # 1. Create the graph file: graph.py from langchain_anthropic import ChatAnthropic from langchain_core.messages import HumanMessage from langgraph.prebuilt import create_react_agent from langgraph.graph import MessagesState, StateGraph, END # 2. Define agents from .tools import multiply, multiply_by_max # Load the example tools above llm = ChatAnthropic(model="claude-3-5-haiku-latest", temperature=0.0) tools = [multiply, multiply_by_max] # Define the tools for the agent using the created tools above problem_solver_agent = create_react_agent( llm, tools=problem_decoder_tools, # Required for ReACT agents prompt="You must solve the given problems!" # Optional system prompt ) # 3. Define nodes def problem_solver_node(state: MessagesState): response = problem_solver_agent.invoke(state) # Invoke the problem solver on the messages new_messages = response["messages"][len(state["messages"]):] # Simple processing: only get the new messages from this LLM invocation return new_messages # 4. Build the graph workflow = StateGraph(MessagesState) workflow.add_edge(START, "problem_solver") # Begin the workflow by entering the problem_solver # Add the problem_solver agent node workflow.add_node("problem_solver", problem_solver_node) # Add the END node to terminate the workflow after the problem_solver is done workflow.add_edge("problem_solver", END) # 5. Compile the graph graph = workflow.compile() # Example prompts problem_solver_agent.invoke({"messages": [ HumanMessage(content="What is 2*5") ]}) problem_solver_agent.invoke({"messages": [ HumanMessage(content="What is 2 mutlipled by the max of this list: [5, 10, 15]") ]}) ``` -------------------------------- ### Build and Compile Hierarchical State Graph with LangGraph Source: https://github.com/lingxi-agent/lingxi/blob/master/README.md This Python code defines a hierarchical state graph using LangGraph. It adds nodes for different components like 'issue_resolve_graph', 'mam_node', and 'reviewer_node', sets up edges between them including the start node, and finally compiles the graph. It utilizes `StateGraph` from `langgraph.graph`. ```python from langgraph.graph import END, START, StateGraph from agent.supervisor_graph_demo import issue_resolve_graph # Assuming CustomState, mam_node, and reviewer_node are defined elsewhere # from src.agent.state import CustomState # from src.agent.hierarchy_graph_demo import mam_node, reviewer_node builder = StateGraph(CustomState) builder.add_node( "issue_resolve_graph", issue_resolve_graph, destinations={"mam_node": "mam_node-issue_resolve_graph"}, ) # Creates the issue_resolve_graph node subgraph, and define an edge from mam_node to issue_resolve_graph builder.add_node( "mam_node", mam_node, destinations=( { "reviewer_node": "mam_node-reviewer_node", "issue_resolve_graph": "mam_node-issue_resolve_graph", } ), ) # Create the multi-agent manager node and define edges between mam_node to reviewer_node, and mam_node back to issue_resolve_graph builder.add_node( "reviewer_node", reviewer_node, destinations=("mam_node": "mam_node-reviewer_node"), ) # Create the reviewer node and define an edge from mam_node to reviewer node builder.add_edge(START, "mam_node") # Define start builder.add_edge("issue_resolve_graph", "mam_node") # Finally add the edge from issue_resolve_graph and mam_node hierarchy_graph = builder.compile() # Compile the graph ``` -------------------------------- ### Define Custom LangGraph State in Python Source: https://context7.com/lingxi-agent/lingxi/llms.txt This Python code defines a custom state class for LangGraph workflows by extending the base MessagesState. It includes fields for tracking agent execution, conversation summaries, and human-in-the-loop settings. The example demonstrates how to initialize a StateGraph with this custom state and how nodes can access and modify its fields. ```python from dataclasses import dataclass from typing import Optional from langgraph.graph import MessagesState @dataclass class CustomState(MessagesState): """Extended state for issue resolution workflow""" last_agent: Optional[str] = None # Track which agent ran last next_agent: Optional[str] = None # Next agent to execute summary: Optional[str] = None # Conversation summary for HIL human_in_the_loop: Optional[bool] = True # Enable/disable HIL preset: Optional[str] = None # GitHub issue URL issue_description: Optional[str] = None # Full issue text # Use in workflow from langgraph.graph import StateGraph workflow = StateGraph(CustomState) # Nodes can access and update custom fields def my_node(state: CustomState): print(f"Last agent was: {state['last_agent']}") return { "messages": [...], "last_agent": "my_agent", "next_agent": "supervisor" } ``` -------------------------------- ### Set Up Environment Variables (Bash) Source: https://github.com/lingxi-agent/lingxi/blob/master/CLAUDE.md Instructions for configuring essential environment variables for the Lingxi project. This involves creating a `.env` file in the project root and specifying details for LLM providers, API keys, and GitHub access. ```bash LLM_PROVIDER=anthropic # or "openai", "deepseek" LLM_MODEL=claude-3-5-haiku-latest ANTHROPIC_API_KEY=your_key_here # or OPENAI_API_KEY, DEEPSEEK_API_KEY OPENAI_API_KEY=your_key_here # Required for embeddings GITHUB_TOKEN=your_token_here # For GitHub API access ``` -------------------------------- ### Use view_directory Tool to Explore File System Source: https://context7.com/lingxi-agent/lingxi/llms.txt Shows how to use the `view_directory` tool to explore the file system. It demonstrates viewing the root directory and a specific directory with a depth limit. ```python from agent.tool_set.sepl_tools import view_directory from agent.runtime_config import RuntimeConfig # Initialize runtime (already configured) rc = RuntimeConfig() # Assume rc.load_from_github_issue_url() was called # View root directory with automatic depth reduction result = view_directory.invoke({"dir_path": "./"}) print(result) # Output: # src/ # tests/ # README.md # setup.py # pyproject.toml # View specific directory with depth limit result = view_directory.invoke({ "dir_path": "./src", "depth": 2 }) print(result) # Output: # src/agent/ # src/agent/supervisor_graph_demo.py # src/agent/hierarchy_graph_demo.py # src/agent/state.py # src/agent/prompt/ # src/agent/tool_set/ ``` -------------------------------- ### Load Runtime Configuration from GitHub Issue URL Source: https://context7.com/lingxi-agent/lingxi/llms.txt This Python code demonstrates how to load runtime configuration using a GitHub issue URL. It initializes a singleton RuntimeConfig object, loads configuration by providing the URL, and then accesses project details, issue descriptions, and runtime settings. It automatically clones the repository and extracts issue information. ```python from agent.runtime_config import RuntimeConfig # Initialize singleton runtime config rc = RuntimeConfig() # Load from GitHub issue URL - automatically clones repo and extracts issue details issue_url = "https://github.com/gitpython-developers/GitPython/issues/1977" rc.load_from_github_issue_url(issue_url) # Access configuration print(f"Project: {rc.proj_name}") # gitpython-developers/GitPython print(f"Path: {rc.proj_path}") # /tmp/runtime/gitpython-developers/GitPython print(f"Issue: {rc.issue_desc}") # Full issue description text print(f"Commit: {rc.commit_head}") # Parent commit hash before fix print(f"Runtime: {rc.runtime_type}") # RuntimeType.LOCAL # Pretty print all config rc.pretty_print_runtime() ``` -------------------------------- ### Create ReACT Agent with Tools Source: https://context7.com/lingxi-agent/lingxi/llms.txt This Python code illustrates how to create a ReACT agent with specific tools using LangGraph. It initializes a ChatAnthropic LLM and defines toolkits for agents, including file system operations (view_directory, view_file_content) and search functionality (search_relevant_files). It also includes an editor tool for string replacements. ```python from langchain_anthropic import ChatAnthropic from langgraph.prebuilt import create_react_agent from agent.tool_set.sepl_tools import view_directory, view_file_content from agent.tool_set.context_tools import search_relevant_files from agent.tool_set.edit_tool import str_replace_editor # Initialize LLM llm = ChatAnthropic(model="claude-3-5-haiku-latest", temperature=0.0) # Define tools for problem decoder agent problem_decoder_tools = [ view_directory, search_relevant_files, view_file_content ] ``` -------------------------------- ### Configure Embeddings and Text Splitter for Vector DB (Python) Source: https://github.com/lingxi-agent/lingxi/blob/master/src/agent/README.md Sets up the embedding model and text splitter components for a Vector Database, specifically used by the `search_relevant_files` tool. It requires the `OPENAI_API_KEY` environment variable for `OpenAIEmbeddings`. ```python import os from langchain.embeddings.openai import OpenAIEmbeddings from langchain.text_splitter import RecursiveCharacterTextSplitter # Ensure OPENAI_API_KEY is set in your environment variables or .env file if not os.getenv("OPENAI_API_KEY"): print("Warning: OPENAI_API_KEY not found. OpenAIEmbeddings might not work.") EMBEDDING_FUNCTION = OpenAIEmbeddings() PROJECT_KNOWLEDGE_TEXT_SPLITTER = RecursiveCharacterTextSplitter( chunk_size=2000, chunk_overlap=200, length_function=len, add_start_index=True, ) # Note: The actual creation of the VectorDB using ChromaDB and indexing # is handled by the `create_project_knowledge` function, which is not shown here. # It also depends on RUNTIME_DIR from src/agent/config.py. ``` -------------------------------- ### Define Tools with Type Hints for Lingxi Agents Source: https://github.com/lingxi-agent/lingxi/blob/master/src/agent/README.md Demonstrates defining custom tools using the `@tool` decorator with Python type hints. These tools can accept simple types or annotated types for richer descriptions, which are then parsed and provided as context to the agent. This method simplifies argument parsing and documentation. ```python # tools.py from langchain_core.tools import tool # Via type hints @tool def multiply(a: int, b: int) -> int: """Multiply two numbers.""" return a * b from typing import Annotated, List # Via annotated type hints @tool def multiply_by_max( a: Annotated[int, "scale factor"], b: Annotated[List[int], "list of ints over which to take maximum"], ) -> int: """Multiply a by the maximum of b.""" return a * max(b) ``` -------------------------------- ### Create LLM Instance using Environment Variables (Python) Source: https://github.com/lingxi-agent/lingxi/blob/master/src/agent/README.md Defines and creates a Large Language Model (LLM) instance based on `LLM_PROVIDER` and `LLM_MODEL` environment variables. It requires setting these variables along with the corresponding API token in a `.env` file for proper operation. ```python import os # Assume LLM_PROVIDER and LLM_MODEL are defined elsewhere or loaded from env vars # For example: # LLM_PROVIDER = os.getenv("LLM_PROVIDER") # LLM_MODEL = os.getenv("LLM_MODEL") def create_llm(): """Creates the LLM according to LLM_PROVIDER and LLM_MODEL env vars.""" llm_provider = os.getenv("LLM_PROVIDER") llm_model = os.getenv("LLM_MODEL") if not llm_provider or not llm_model: raise ValueError("LLM_PROVIDER and LLM_MODEL environment variables must be set.") # Placeholder for actual LLM creation logic based on provider and model print(f"Creating LLM with provider: {llm_provider}, model: {llm_model}") # Example: return some_llm_library.create(provider=llm_provider, model=llm_model, api_key=os.getenv("API_TOKEN")) pass # Example usage: # try: # llm = create_llm() # except ValueError as e: # print(e) ``` -------------------------------- ### Create ReACT Agent with Tools in LangGraph Source: https://github.com/lingxi-agent/lingxi/blob/master/src/agent/README.md Illustrates how to create a ReACT agent using `create_react_agent` from LangGraph, integrating custom tools. The `tools` parameter accepts a list of tool objects, and an optional system prompt can be provided. The agent is then invoked with a `MessagesState` object containing the conversation history. ```python # graph.py from langchain_anthropic import ChatAnthropic from langchain_core.messages import HumanMessage from langgraph.prebuilt import create_react_agent from tools import multiply, multiply_by_max # Load the example tools above llm = ChatAnthropic(model="claude-3-5-haiku-latest", temperature=0.0) tools = [multiply, multiply_by_max] # Define the tools for the agent using the created tools above problem_solver_agent = create_react_agent( llm, tools=problem_decoder_tools, # Required for ReACT agents prompt="You must solve the given problems!" # Optional system prompt ) # Example prompts problem_solver_agent.invoke({"messages": [ HumanMessage(content="What is 2*5") ]}) problem_solver_agent.invoke({"messages": [ HumanMessage(content="What is 2 mutlipled by the max of this list: [5, 10, 15]") ]}) ``` -------------------------------- ### Create ReACT Agent with Anthropic LLM and Tools Source: https://github.com/lingxi-agent/lingxi/blob/master/README.md Illustrates the creation of a ReACT agent using ChatAnthropic and Langgraph's create_react_agent function. This agent is designed to use provided tools to solve problems. It requires the LLM, a list of tools, and an optional system prompt. The agent is invoked with a dictionary containing a list of messages. ```python from langchain_anthropic import ChatAnthropic from langgraph.prebuilt import create_react_agent from langchain_core.messages import HumanMessage llm = ChatAnthropic(model="claude-3-5-haiku-latest", temperature=0.0) # Create LLM tools = [math_tool] # Tool example problem_solver_agent = create_react_agent( llm, tools=problem_decoder_tools, # Required for ReACT agents prompt="You must solve the given problems!" # Optional system prompt ) problem_solver_agent.invoke({"messages": [ HumanMessage(content="What is 2+2") ]}) # How to invoke the agent using user prompt "What is 2+2" ``` -------------------------------- ### Create Tool-less Agent with Anthropic LLM Source: https://github.com/lingxi-agent/lingxi/blob/master/README.md Demonstrates how to create a tool-less agent using the ChatAnthropic model. This agent can be invoked with single string inputs or a list of strings representing a conversation history. Dependencies include langchain-anthropic. ```python from langchain_anthropic import ChatAnthropic llm = ChatAnthropic(model="claude-3-5-haiku-latest", temperature=0.0) response = llm.invoke("Tell me a joke") # Single string input response = llm.invoke(["What is 2+2", "What is the previous result times 5"]) # List of string as input ``` -------------------------------- ### Define and Compile LangGraph Stateful Graph Source: https://github.com/lingxi-agent/lingxi/blob/master/src/agent/README.md This snippet shows how to define a stateful graph using `StateGraph` from the `langgraph` library. It demonstrates adding nodes, specifying their destinations, defining edges between nodes, and finally compiling the graph. The `CustomState` is assumed to be defined elsewhere and holds the graph's state. ```python from langgraph.graph import END, START, StateGraph from agent.supervisor_graph_demo import issue_resolve_graph # Assuming CustomState and necessary node functions (issue_resolve_graph, mam_node, reviewer_node) are defined elsewhere. # class CustomState: # ... # def mam_node(...): # ... # def reviewer_node(...): # ... builder = StateGraph(CustomState) builder.add_node( "issue_resolve_graph", issue_resolve_graph, destinations={"mam_node": "mam_node-issue_resolve_graph"}, ) # Creates the issue_resolve_graph node subgraph, and define an edge from mam_node to issue_resolve_graph builder.add_node( "mam_node", mam_node, destinations=( { "reviewer_node": "mam_node-reviewer_node", "issue_resolve_graph": "mam_node-issue_resolve_graph", } ), ) # Create the multi-agent manager node and define edges between mam_node to reviewer_node, and mam_node back to issue_resolve_graph builder.add_node( "reviewer_node", reviewer_node, destinations=("mam_node": "mam_node-reviewer_node"), ) # Create the reviewer node and define an edge from mam_node to reviewer node builder.add_edge(START, "mam_node") # Define start builder.add_edge("issue_resolve_graph", "mam_node") # Finally add the edge from issue_resolve_graph and mam_node hierarchy_graph = builder.compile() # Compile the graph ``` -------------------------------- ### Build Complete LangGraph Workflow Source: https://context7.com/lingxi-agent/lingxi/llms.txt Illustrates the construction of a complete LangGraph workflow for issue resolution. It defines nodes for input handling, supervision, problem decoding, solution mapping, and problem solving, along with their interconnections. ```python from langgraph.graph import StateGraph, START, END from agent.state import CustomState # Assume input_handler_node, supervisor_node, solution_mapper_node, # and problem_solver_node are defined elsewhere # input_handler_node = ... # supervisor_node = ... # solution_mapper_node = ... # problem_solver_node = ... # Create workflow with custom state workflow = StateGraph(CustomState) # Add nodes workflow.add_node("input_handler", input_handler_node) workflow.add_node("supervisor", supervisor_node) workflow.add_node("problem_decoder", problem_decoder_node) workflow.add_node("solution_mapper", solution_mapper_node) workflow.add_node("problem_solver", problem_solver_node) # Define edges workflow.add_edge(START, "input_handler") workflow.add_edge("input_handler", "supervisor") workflow.add_edge("problem_decoder", "supervisor") workflow.add_edge("solution_mapper", "supervisor") workflow.add_edge("problem_solver", "supervisor") # Supervisor uses conditional routing to END or next agent # (handled internally by supervisor_node returning Command with goto) # Compile graph issue_resolve_graph = workflow.compile() # Register in langgraph.json (example comment) # { # "graphs": { # "issue_resolve_graph": "./src/agent/supervisor_graph_demo.py:issue_resolve_graph" # } # } ``` -------------------------------- ### Use search_relevant_files Tool for Code Search Source: https://context7.com/lingxi-agent/lingxi/llms.txt Demonstrates the usage of the `search_relevant_files` tool to find code files related to a specific query, such as an authentication error. ```python from agent.tool_set.context_tools import search_relevant_files from agent.runtime_config import RuntimeConfig rc = RuntimeConfig() # Assume already loaded with issue URL # Search for files related to authentication bug result = search_relevant_files.invoke({ "query": "authentication error when user logs in with OAuth" }) print(result) # Output: # Top 10 most relevant files: # # src/auth/oauth.py: # This file contains the OAuth authentication handler that validates tokens # and manages user sessions. Relevant because it handles OAuth login flow. # # src/auth/session.py: # This file manages user session creation and validation. Relevant because # authentication errors may occur during session initialization. # # tests/test_oauth.py: # Contains test cases for OAuth authentication flow... ``` -------------------------------- ### JSON: Configure LangGraph Project and Graphs Source: https://github.com/lingxi-agent/lingxi/blob/master/README.md Configuration file for a LangGraph project, specifying dependencies, graph definitions, and environment variables. This JSON structure maps graph names to their respective Python files and compiled variables. ```json { "dependencies": [""], "graphs": { "demo_graph": "graph.py:graph", "hierarchy_graph": "./src/agent/hierarchy_graph_demo.py:hierarchy_graph" }, "env": ".env" } ``` -------------------------------- ### Edit File Content with str_replace_editor Tool Source: https://context7.com/lingxi-agent/lingxi/llms.txt Demonstrates how to use the str_replace_editor tool to view, modify, and create files. It shows string replacement with exact matching and inserting text at a specific line. Dependencies include the `requests` library for the original Python code being modified. ```python from agent.tool_set.edit_tool import str_replace_editor # First, view the file to understand context result = str_replace_editor.invoke({ "command": "view", "path": "src/auth/oauth.py", "view_range": [50, 60] }) # Make a string replacement with exact matching result = str_replace_editor.invoke({ "command": "str_replace", "path": "src/auth/oauth.py", "old_str": " def validate_token(self, token: str) -> bool:\n response = requests.post( self.validation_url, data={\"token\": token} ) return response.status_code == 200", "new_str": " def validate_token(self, token: str) -> bool:\n try:\n response = requests.post( self.validation_url, data={\"token\": token}, timeout=10 ) return response.status_code == 200 except requests.RequestException:\n return False" }) print(result) # Create a new file result = str_replace_editor.invoke({ "command": "create", "path": "src/auth/exceptions.py", "file_text": "class AuthenticationError(Exception):\n pass\n\nclass TokenValidationError(AuthenticationError):\n pass\n" }) # Insert text after a specific line result = str_replace_editor.invoke({ "command": "insert", "path": "src/auth/oauth.py", "insert_line": 5, "new_str": "from .exceptions import TokenValidationError" }) ``` -------------------------------- ### Run Project Tests (Bash) Source: https://github.com/lingxi-agent/lingxi/blob/master/CLAUDE.md Command to execute the test suite for the Lingxi project using pytest. This command runs all discovered tests to verify the functionality and stability of the codebase. ```bash pytest ``` -------------------------------- ### Configure Langgraph Graphs in langgraph.json Source: https://github.com/lingxi-agent/lingxi/blob/master/src/agent/README.md This JSON configuration file specifies how graphs are defined and registered within the Langgraph project. It includes dependencies, a mapping of graph names to their file paths and compiled variables, and environment file location. ```json // Step 6: Define the graph in langgraph.json { "dependencies": ["."], "graphs": { "demo_graph": "graph.py:graph", "hierarchy_graph": "./src/agent/hierarchy_graph_demo.py:hierarchy_graph" }, "env": ".env" } ``` -------------------------------- ### Code Quality Checks (Bash) Source: https://github.com/lingxi-agent/lingxi/blob/master/CLAUDE.md Commands for maintaining code quality in the Lingxi project using ruff for linting and formatting, and mypy for static type checking. These tools help ensure code consistency and catch potential errors. ```bash # Linting with ruff ruff check src/ ruff format src/ # Type checking mypy src/ ``` -------------------------------- ### Create and Invoke ReACT Agent for Problem Decoding Source: https://context7.com/lingxi-agent/lingxi/llms.txt Demonstrates the creation of a ReACT agent tasked with problem decoding and bug localization. It uses the create_react_agent function and invokes the agent with a specific human message to identify issues. ```python from langchain_core.messages import HumanMessage # Assume llm and problem_decoder_tools are defined elsewhere # llm = ... # problem_decoder_tools = [...] problem_decoder_agent = create_react_agent( llm, tools=problem_decoder_tools, prompt="""You are the Problem Decoder. Analyze the issue and perform bug localization. Use search_relevant_files to find related code, view_directory to explore structure, and view_file_content to examine specific files.""" ) # Invoke agent with state result = problem_decoder_agent.invoke({ "messages": [ HumanMessage(content="Find the bug causing AttributeError in git.py line 142") ] }) # Result contains messages with tool calls and responses for msg in result["messages"]: print(f"{msg.type}: {msg.content[:100]}...") ``` -------------------------------- ### Create Custom Analysis Tool with Langchain Source: https://context7.com/lingxi-agent/lingxi/llms.txt Demonstrates how to define a custom tool using Langchain's `@tool` decorator. The `analyze_complexity` tool calculates the cyclomatic complexity of a Python file using the `radon` library. It takes a file path as input and returns a formatted report. This custom tool can then be integrated into Langchain agents. ```python from langchain_core.tools import tool from typing import Annotated @tool def analyze_complexity( file_path: Annotated[str, "Path to Python file relative to project root"] ) -> str: """Analyze the cyclomatic complexity of a Python file. Returns a report showing complexity scores for each function. Helps identify code that may need refactoring. """ from radon.complexity import cc_visit from agent.runtime_config import RuntimeConfig import os rc = RuntimeConfig() full_path = os.path.join(rc.proj_path, file_path) with open(full_path, 'r') as f: code = f.read() results = cc_visit(code) report = [] for item in results: report.append( f"{item.name} (line {item.lineno}): " f"complexity={item.complexity}, rank={item.rank}" ) return "\n".join(report) # Use in agent creation from langgraph.prebuilt import create_react_agent from langchain_anthropic import ChatAnthropic llm = ChatAnthropic(model="claude-3-5-haiku-latest") tools = [view_file_content, analyze_complexity] # Assuming view_file_content is defined elsewhere code_reviewer_agent = create_react_agent( llm, tools=tools, prompt="You are a code reviewer. Analyze code quality and suggest improvements." ) ``` -------------------------------- ### Invoke Lingxi Issue Resolution Graph Source: https://context7.com/lingxi-agent/lingxi/llms.txt This Python snippet demonstrates how to invoke the Lingxi issue resolution graph. It sets up a thread for execution tracking, creates initial input containing a GitHub issue URL, and streams the execution process, printing agent outputs. The final result contains all agent outputs and the generated patch. ```python from langchain_core.messages import HumanMessage from agent.supervisor_graph_demo import issue_resolve_graph import uuid # Configure thread for execution tracking thread = { "recursion_limit": 100, "run_id": uuid.uuid4(), "tags": ["issue-resolution"], "configurable": {"thread_id": "1"}, } # Create initial input with GitHub issue URL initial_input = { "messages": [ HumanMessage( content="https://github.com/gitpython-developers/GitPython/issues/1413" ) ], "preset": "https://github.com/gitpython-developers/GitPython/issues/1413", "human_in_the_loop": False, # Disable human feedback } # Stream execution and print messages for chunk in issue_resolve_graph.stream( initial_input, config=thread, stream_mode="values" ): if "messages" in chunk and len(chunk["messages"]) > 0: chunk["messages"][-1].pretty_print() # Final state contains all agent outputs and generated patch # Access with: result = issue_resolve_graph.invoke(initial_input, config=thread) ``` -------------------------------- ### Parse File Explanations from LLM Responses (Python) Source: https://github.com/lingxi-agent/lingxi/blob/master/src/agent/README.md Parses JSON-formatted responses from an LLM to extract file paths and their corresponding explanations. This parser is crucial for interpreting structured output related to file analysis. ```python import json def relevant_file_explanations_parser(llm_response_str): """Parses file paths and explanations from JSON formatted LLM responses.""" try: response_json = json.loads(llm_response_str) # Assuming the JSON structure has a key like 'files' which is a list of objects # each object containing 'file_path' and 'explanation'. Adjust as needed. parsed_data = [] if 'files' in response_json and isinstance(response_json['files'], list): for item in response_json['files']: if 'file_path' in item and 'explanation' in item: parsed_data.append({ "file_path": item['file_path'], "explanation": item['explanation'] }) return parsed_data except json.JSONDecodeError: print("Error: LLM response is not valid JSON.") return [] except Exception as e: print(f"An error occurred during parsing: {e}") return [] # Example usage: # llm_output = '{"files": [{"file_path": "src/main.py", "explanation": "This file contains the main application logic."}]}' # parsed_files = relevant_file_explanations_parser(llm_output) # print(parsed_files) ``` -------------------------------- ### Apply Git Diff from Patch in Python Source: https://context7.com/lingxi-agent/lingxi/llms.txt This Python code demonstrates how to apply a git diff from a patch string using the `apply_git_diff` method of `RuntimeConfig`. The function attempts to apply the patch using various strategies including `git apply` and `patch`. It returns an exit code and a message indicating success or failure. ```python from agent.runtime_config import RuntimeConfig rc = RuntimeConfig() # Runtime already configured # Load patch content patch_content = """ diff --git a/src/auth/oauth.py b/src/auth/oauth.py index abc123..def456 100644 --- a/src/auth/oauth.py +++ b/src/auth/oauth.py @@ -50,5 +50,8 @@ class OAuthHandler: def validate_token(self, token: str) -> bool: - response = requests.post(self.validation_url, data={"token": token}) - return response.status_code == 200 + try: + response = requests.post(self.validation_url, data={"token": token}, timeout=10) + return response.status_code == 200 + except requests.RequestException: + return False """ # Apply patch (tries multiple strategies: git apply, git apply --reject, patch) exit_code, message = rc.apply_git_diff(patch_content) if exit_code == 0: print("Success:", message) # Patch successfully applied else: print("Failed:", message) # Patch failed to apply ``` -------------------------------- ### Execute Git Diff Command Locally (Python) Source: https://github.com/lingxi-agent/lingxi/blob/master/src/agent/README.md Executes the `git diff` command within a local runtime environment and returns the output. This tool is part of the Software Engineering Project Lifecycle (SEPL) tools for managing code changes. ```python import subprocess def extract_git_diff_local(): """Executes and returns the `git diff` command in a local runtime environment.""" try: # Ensure you are in the correct git repository directory when calling this result = subprocess.run(['git', 'diff'], capture_output=True, text=True, check=True) return result.stdout except FileNotFoundError: return "Error: 'git' command not found. Make sure Git is installed and in your PATH." except subprocess.CalledProcessError as e: return f"Error executing git diff: {e.stderr}" except Exception as e: return f"An unexpected error occurred: {e}" # Example usage: # git_diff_output = extract_git_diff_local() # print(git_diff_output) ``` -------------------------------- ### Save Git Diff Output (Python) Source: https://github.com/lingxi-agent/lingxi/blob/master/src/agent/README.md Provides functionality to export the result of the `git diff` command. This utility is part of the SEPL tools, allowing the captured diff information to be saved persistently. ```python import os def save_git_diff(diff_content, file_path="git_diff.patch"): """Exports the result of the `git diff` command to a file.""" try: with open(file_path, 'w') as f: f.write(diff_content) print(f"Git diff saved to {os.path.abspath(file_path)}") return True except IOError as e: print(f"Error saving git diff to {file_path}: {e}") return False except Exception as e: print(f"An unexpected error occurred: {e}") return False # Example usage: # diff_output = "diff --git a/file.txt b/file.txt\nindex ... ...\n---\n+++" # save_git_diff(diff_output, "my_changes.patch") ``` -------------------------------- ### Implement Human-in-the-Loop Feedback in Python Source: https://context7.com/lingxi-agent/lingxi/llms.txt This Python code defines a LangGraph node for handling human-in-the-loop feedback. The `human_feedback_node` function displays a conversation summary to the user, collects their feedback, and routes the workflow based on whether a rerun is requested. It uses the `interrupt` function to pause execution and wait for user input, returning a `Command` object to update the state or navigate to a different node. ```python from langgraph.types import Command, interrupt from typing import Literal from agent.state import CustomState def human_feedback_node(state: CustomState) -> Command[Literal["problem_decoder", "solution_mapper", "problem_solver"]]: """Node that collects human feedback and routes accordingly""" next_agent = state["next_agent"] last_agent = state["last_agent"] summary = state["summary"] # Show summary to human and wait for input show_to_human = f"{summary}\nPlease provide feedback on the last agent: " human_feedback = interrupt(show_to_human) # Human response format: {"feedback": "...", "rerun": 0 or 1} feedback = human_feedback["feedback"] rerun = bool(human_feedback["rerun"]) if rerun: # Rerun the last agent with human feedback return Command( update={ "messages": [ AIMessage(content=summary, name="conversation_summary"), HumanMessage(content=feedback, name="human_feedback") ], "next_agent": None }, goto=last_agent ) # Continue to next agent with feedback return Command( update={ "messages": [ AIMessage(content=summary, name="conversation_summary"), HumanMessage(content=feedback, name="human_feedback") ] }, goto=next_agent ) # Enable HIL in initial input initial_input = { "messages": [HumanMessage(content="https://github.com/...")], "human_in_the_loop": True # Set to False to disable } ``` -------------------------------- ### Extract and Save Git Diff in Python Source: https://context7.com/lingxi-agent/lingxi/llms.txt This Python code snippet demonstrates how to extract and save git diffs to a patch file using the `save_git_diff` function from `agent.tool_set.sepl_tools`. It assumes the runtime is configured and code changes have been made. The diff content is printed, and the patch is automatically saved to a directory based on the project name and timestamp. ```python from agent.tool_set.sepl_tools import save_git_diff from agent.runtime_config import RuntimeConfig import os rc = RuntimeConfig() # Assume runtime is configured and code changes have been made # Save git diff to patch file patch_content = save_git_diff() print(patch_content) # Output: # diff --git a/src/auth/oauth.py b/src/auth/oauth.py # index abc123..def456 100644 # --- a/src/auth/oauth.py # +++ b/src/auth/oauth.py # @@ -50,8 +50,11 @@ class OAuthHandler: # def validate_token(self, token: str) -> bool: # - response = requests.post( # - self.validation_url, # - data={"token": token} # - ) # - return response.status_code == 200 # + try: # + response = requests.post( # + self.validation_url, # + data={"token": token}, # + timeout=10 # + ) # + return response.status_code == 200 # + except requests.RequestException: # + return False # Patch is automatically saved to: # {PATCH_RESULT_DIR}/{project_name}@{timestamp}.patch # e.g., /tmp/patches/gitpython-developers+GitPython@1234567890.patch ```