Building a Smart AI Coding Assistant: From Design to Real‑World Use

This tutorial walks through the functional planning, project layout, core Python code, context management, FastAPI service, and execution steps needed to create a full‑featured AI coding assistant that can generate, explain, refactor, fix, test, and review code.

Coder Trainee
Coder Trainee
Coder Trainee
Building a Smart AI Coding Assistant: From Design to Real‑World Use

Overview

The article continues a series on AI agents and demonstrates how to build a complete smart coding assistant capable of code generation, explanation, refactoring, bug fixing, unit‑test creation, and code review.

Feature Planning

Code generation – trigger /generate Code explanation – trigger /explain Code refactoring – trigger /refactor Bug fixing – trigger /fix Unit‑test generation – trigger /test Code review – trigger

/review

Project Structure

ai-coding-assistant/
├── src/
│   ├── agent/          # Agent core
│   ├── tools/          # Tool set
│   ├── prompts/        # Prompt templates
│   └── server/         # API service
├── tests/               # Test cases
└── examples/            # Example code

Core Code Implementation

3.1 Code Generation Tools

# tools/code_tools.py
from langchain.tools import tool
from typing import List, Dict, Optional

@tool
def generate_code(description: str, language: str = "python") -> str:
    """根据描述生成代码"""
    prompt = f"""
    根据以下需求生成{language}代码:
    {description}
    要求:
    1. 代码要完整、可运行
    2. 包含必要的注释
    3. 遵循最佳实践
    """
    response = llm.invoke(prompt)
    return response.content

@tool
def explain_code(code: str) -> str:
    """解释代码逻辑"""
    prompt = f"""
    解释以下代码的功能和逻辑:
    ```python
    {code}
    ```
    输出格式:
    1. 代码功能概述
    2. 逐行/逐段解释
    3. 时间复杂度和空间复杂度
    """
    response = llm.invoke(prompt)
    return response.content

@tool
def refactor_code(code: str, requirements: str = "") -> str:
    """重构代码"""
    prompt = f"""
    对以下代码进行重构:
    ```python
    {code}
    ```
    重构要求:{requirements or "提升可读性和可维护性"}
    输出:
    1. 重构后的代码
    2. 重构说明
    """
    response = llm.invoke(prompt)
    return response.content

@tool
def fix_bug(code: str, error_message: str) -> str:
    """修复代码 Bug"""
    prompt = f"""
    以下代码存在错误,请修复:
    ```python
    {code}
    ```
    错误信息:
    {error_message}
    输出:
    1. 问题定位
    2. 修复后的代码
    3. 修复说明
    """
    response = llm.invoke(prompt)
    return response.content

@tool
def generate_unit_test(code: str, framework: str = "pytest") -> str:
    """生成单元测试"""
    prompt = f"""
    为以下代码生成{framework}单元测试:
    ```python
    {code}
    ```
    要求:
    1. 覆盖正常路径和边界情况
    2. 包含必要的断言
    3. 测试用例命名清晰
    """
    response = llm.invoke(prompt)
    return response.content

@tool
def code_review(code: str) -> str:
    """代码审查"""
    prompt = f"""
    对以下代码进行审查:
    ```python
    {code}
    ```
    输出格式:
    1. 优点
    2. 问题与建议
    3. 安全性检查
    4. 性能建议
    """
    response = llm.invoke(prompt)
    return response.content

3.2 Coding Assistant Agent

# agent/coding_agent.py
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_openai import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from tools.code_tools import *

class CodingAssistant:
    """智能编程助手"""
    def __init__(self, model: str = "gpt-4"):
        self.llm = ChatOpenAI(model=model, temperature=0.2)
        self.tools = [
            generate_code,
            explain_code,
            refactor_code,
            fix_bug,
            generate_unit_test,
            code_review,
        ]
        self._setup_agent()

    def _setup_agent(self):
        prompt = ChatPromptTemplate.from_messages([
            ("system", """你是专业的编程助手,擅长各种编程语言。
可用命令:
- /gen <描述> - 生成代码
- /explain <代码> - 解释代码
- /refactor <代码> - 重构代码
- /fix <代码> <错误> - 修复Bug
- /test <代码> - 生成测试
- /review <代码> - 代码审查
请友好、专业地帮助用户解决问题。"""),
            ("human", "{input}"),
            ("placeholder", "{agent_scratchpad}"),
        ])
        self.agent = create_tool_calling_agent(self.llm, self.tools, prompt)
        self.executor = AgentExecutor(agent=self.agent, tools=self.tools, verbose=True)

    def run(self, command: str, content: str, context: str = "") -> str:
        """执行命令"""
        user_input = f"{command}
{content}"
        if context:
            user_input = f"上下文:{context}

{user_input}"
        result = self.executor.invoke({"input": user_input})
        return result["output"]

3.3 Context Manager

# agent/context_manager.py
from typing import Dict, List, Optional
import json

class ContextManager:
    """代码上下文管理"""
    def __init__(self):
        self.current_file: str = ""
        self.files: Dict[str, str] = {}
        self.history: List[Dict] = []

    def set_current_file(self, filename: str, content: str):
        """设置当前文件"""
        self.current_file = filename
        self.files[filename] = content

    def get_context(self) -> str:
        """获取上下文"""
        if not self.current_file:
            return ""
        return f"当前文件:{self.current_file}
```
{self.files[self.current_file]}
```"

    def add_to_history(self, command: str, input_code: str, output_code: str):
        """添加历史记录"""
        self.history.append({
            "command": command,
            "input": input_code[:500],
            "output": output_code[:500]
        })

    def get_history(self, limit: int = 5) -> str:
        """获取历史"""
        recent = self.history[-limit:]
        return json.dumps(recent, ensure_ascii=False, indent=2)

3.4 API Service

# server/app.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from agent.coding_agent import CodingAssistant
from agent.context_manager import ContextManager

app = FastAPI(title="AI Coding Assistant")
assistant = CodingAssistant()
context_mgr = ContextManager()

class CodeRequest(BaseModel):
    command: str
    content: str
    filename: str = ""
    context: str = ""

@app.post("/assistant/chat")
async def chat(request: CodeRequest):
    """编程助手对话"""
    try:
        if request.filename:
            context_mgr.set_current_file(request.filename, request.content)
        full_context = context_mgr.get_context()
        if request.context:
            full_context = f"{full_context}

额外上下文:{request.context}"
        response = assistant.run(
            command=request.command,
            content=request.content,
            context=full_context
        )
        context_mgr.add_to_history(
            request.command,
            request.content[:500],
            response[:500]
        )
        return {"success": True, "response": response}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/assistant/context")
async def get_context():
    """获取当前上下文"""
    return {
        "current_file": context_mgr.current_file,
        "context": context_mgr.get_context()
    }

Running the Assistant

# Install dependencies
pip install fastapi uvicorn langchain langchain-openai

# Start the service
python server/app.py

# Test with curl
curl -X POST http://localhost:8000/assistant/chat \
  -H "Content-Type: application/json" \
  -d '{"command":"/gen","content":"一个计算斐波那契数列的函数"}'

Next Episode Preview

The next article will cover a Data Analysis Agent that can translate natural language to SQL, create visualizations, and generate reports.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonLangChainAI AgentFastAPItool callingcoding assistant
Coder Trainee
Written by

Coder Trainee

Experienced in Java and Python, we share and learn together. For submissions or collaborations, DM us.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.