|
| 1 | +--- |
| 2 | +title: "Building a Code Agent with LangChain" |
| 3 | +sidebarTitle: "Code Agent" |
| 4 | +icon: "robot" |
| 5 | +iconType: "solid" |
| 6 | +--- |
| 7 | + |
| 8 | +This guide demonstrates how to build an intelligent code agent that can analyze and manipulate codebases using Codegen's LangChain integration. |
| 9 | + |
| 10 | +This agent access to powerful code viewing and manipulation tools powered by Codegen, including: |
| 11 | +- `RevealSymbolTool`: reveal all N-th degree dependencies and usages of a function |
| 12 | +- `MoveSymbolTool`: move a symbol between files, updating all imports etc. (guaranteed correctness) |
| 13 | +- `SemanticEditTool`: implementation of Cursor-style smart file editing |
| 14 | +- `SemanticSearchTool`: search over an index of vector embeddings for files |
| 15 | + |
| 16 | +<Info>View the full code in our [examples repository](https://github.com/codegen-sh/codegen-sdk/tree/develop/src/codegen/extensions/langchain)</Info> |
| 17 | + |
| 18 | +## Step 1: Setting Up the Agent |
| 19 | + |
| 20 | +First, let's import the necessary components and create our agent: |
| 21 | + |
| 22 | +```python |
| 23 | +from langchain_openai import ChatOpenAI |
| 24 | +from codegen import Codebase |
| 25 | +from codegen.extensions.langchain import create_codebase_agent |
| 26 | + |
| 27 | +# Initialize codebase |
| 28 | +codebase = Codebase.from_repo("fastapi/fastapi") |
| 29 | + |
| 30 | +# Create the agent with GPT-4 |
| 31 | +agent = create_codebase_agent( |
| 32 | + codebase=codebase, |
| 33 | + model_name="gpt-4", |
| 34 | + temperature=0, |
| 35 | + verbose=True |
| 36 | +) |
| 37 | +``` |
| 38 | + |
| 39 | +The agent is initialized with: |
| 40 | +- A Codebase instance to operate on |
| 41 | +- An LLM (GPT-4 in this case) |
| 42 | +- Tools for code manipulation |
| 43 | +- A conversation memory to maintain context |
| 44 | + |
| 45 | +## Step 2: Available Tools |
| 46 | + |
| 47 | +The agent comes with several built-in tools for code operations: |
| 48 | + |
| 49 | +```python |
| 50 | +tools = [ |
| 51 | + ViewFileTool(codebase), # View file contents |
| 52 | + ListDirectoryTool(codebase), # List directory contents |
| 53 | + SearchTool(codebase), # Search code |
| 54 | + EditFileTool(codebase), # Edit files |
| 55 | + CreateFileTool(codebase), # Create new files |
| 56 | + DeleteFileTool(codebase), # Delete files |
| 57 | + RenameFileTool(codebase), # Rename files |
| 58 | + MoveSymbolTool(codebase), # Move functions/classes |
| 59 | + RevealSymbolTool(codebase), # Analyze symbol relationships |
| 60 | + SemanticEditTool(codebase), # Make semantic edits |
| 61 | + CommitTool(codebase), # Commit changes |
| 62 | +] |
| 63 | +``` |
| 64 | + |
| 65 | +Each tool provides specific capabilities to the agent, allowing it to perform complex code operations. |
| 66 | + |
| 67 | +## Step 3: Interacting with the Agent |
| 68 | + |
| 69 | +Let's see some examples of how to interact with the agent: |
| 70 | + |
| 71 | +```python |
| 72 | +# Analyze dependencies |
| 73 | +result = agent.invoke( |
| 74 | + { |
| 75 | + "input": "What are the dependencies of the FastAPI class?", |
| 76 | + "config": {"configurable": {"session_id": "demo"}} |
| 77 | + } |
| 78 | +) |
| 79 | +print(result["output"]) |
| 80 | + |
| 81 | +# Find usage patterns |
| 82 | +result = agent.invoke( |
| 83 | + { |
| 84 | + "input": "Show me examples of dependency injection in the codebase", |
| 85 | + "config": {"configurable": {"session_id": "demo"}} |
| 86 | + } |
| 87 | +) |
| 88 | +print(result["output"]) |
| 89 | + |
| 90 | +# Perform code analysis |
| 91 | +result = agent.invoke( |
| 92 | + { |
| 93 | + "input": "What's the most complex function in terms of dependencies?", |
| 94 | + "config": {"configurable": {"session_id": "demo"}} |
| 95 | + } |
| 96 | +) |
| 97 | +print(result["output"]) |
| 98 | +``` |
| 99 | + |
| 100 | +The agent maintains conversation history, so it can reference previous queries and build context over time. |
| 101 | + |
| 102 | +## Step 4: Code Manipulation |
| 103 | + |
| 104 | +The agent can also perform code changes: |
| 105 | + |
| 106 | +```python |
| 107 | +# Move a function to a new file |
| 108 | +result = agent.invoke( |
| 109 | + { |
| 110 | + "input": "Move the validate_email function to validation_utils.py", |
| 111 | + "config": {"configurable": {"session_id": "demo"}} |
| 112 | + } |
| 113 | +) |
| 114 | + |
| 115 | +# Rename a class and update all references |
| 116 | +result = agent.invoke( |
| 117 | + { |
| 118 | + "input": "Rename the UserModel class to User and update all imports", |
| 119 | + "config": {"configurable": {"session_id": "demo"}} |
| 120 | + } |
| 121 | +) |
| 122 | + |
| 123 | +# Add error handling |
| 124 | +result = agent.invoke( |
| 125 | + { |
| 126 | + "input": "Add proper error handling to the process_data function", |
| 127 | + "config": {"configurable": {"session_id": "demo"}} |
| 128 | + } |
| 129 | +) |
| 130 | +``` |
| 131 | + |
| 132 | +The agent will: |
| 133 | +1. Analyze the current code state |
| 134 | +2. Plan the necessary changes |
| 135 | +3. Execute the changes while maintaining code correctness |
| 136 | +4. Update all related imports and references |
| 137 | + |
| 138 | +## Advanced Usage |
| 139 | + |
| 140 | +### Adding Custom Tools |
| 141 | + |
| 142 | +You can extend the agent with custom tools: |
| 143 | + |
| 144 | +```python |
| 145 | +from langchain.tools import BaseTool |
| 146 | +from pydantic import BaseModel, Field |
| 147 | + |
| 148 | +class CustomToolInput(BaseModel): |
| 149 | + """Input schema for custom tool.""" |
| 150 | + param: str = Field(..., description="Parameter description") |
| 151 | + |
| 152 | +class CustomCodeTool(BaseTool): |
| 153 | + """A custom tool for the code agent.""" |
| 154 | + name = "custom_tool" |
| 155 | + description = "Description of what the tool does" |
| 156 | + args_schema = CustomToolInput |
| 157 | + |
| 158 | + def _run(self, param: str) -> str: |
| 159 | + # Tool implementation |
| 160 | + return f"Processed {param}" |
| 161 | + |
| 162 | +# Add custom tool to agent |
| 163 | +tools.append(CustomCodeTool()) |
| 164 | +agent = create_codebase_agent( |
| 165 | + codebase=codebase, |
| 166 | + tools=tools, |
| 167 | + model_name="gpt-4" |
| 168 | +) |
| 169 | +``` |
0 commit comments