AI Agent Vertical Application Scenarios
Different domains have different requirements and characteristics for Agents.
Through domain customization, Agents can provide more professional services.
Code Agent
Code Agent is one of the most successful Agent application domains.
Able to understand codebases, write new code, and debug issues.
Core Capabilities
Code Completion: Predict the next segment of code based on context.
Code Generation: Generate code based on natural language descriptions.
Code Review: Discover issues and improvements in code.
Bug Localization: Analyze error messages and locate the root cause of problems.
Code Refactoring: Propose and execute code optimization suggestions.
Representative Systems
| System | Developer Company | Features |
|---|---|---|
| GitHub Copilot | GitHub/OpenAI | Primarily code completion, real-time suggestions |
| Claude Code | Anthropic | Command-line assistant, deep code understanding |
| Devin | Cognition | Autonomous programming, end-to-end task execution |
| Cursor | Cursor | AI code editor, deep IDE integration |
Code Implementation Examples
Text2SQL Agent Implementation
"""
Text2SQL Agent
Convert natural language to SQL queries
"""
def __init__(self, llm, schema):
self.llm = llm
# Database Schema Information
self.schema = schema
def convert(self, question):
"""
Convert natural language problems to SQL
:param question: Natural language question
:return: SQL query statement
"""
prompt = f"""
You are an SQL expert.
Database Schema:
{self.schema}
Rules:
1. Only generate SELECT queries (INSERT/UPDATE/DELETE are not supported)
2. Use sensible table aliases
3. Add necessary JOIN conditions
4. Use clear column aliases
Question: {question}
Please generate the corresponding SQL query.
"""
sql = self.llm.generate(prompt)
# Security check
return self.sanitize(sql)
def sanitize(self, sql):
"""
SQL security check
Ensure no dangerous operations are included
"""
# Lowercase check
sql_lower = sql.lower().strip()
# Check that it contains only SELECT
forbidden_keywords = [
"insert", "update", "delete", "drop",
"create", "alter", "truncate", "exec",
"execute", "grant", "revoke"
]
for keyword in forbidden_keywords:
if keyword in sql_lower:
raise ValueError(f"Forbidden keywords: {keyword}")
return sql
def execute(self, question, db_connection):
"""
Execute Text2SQL query
"""
sql = self.convert(question)
cursor = db_connection.cursor()
cursor.execute(sql)
results = cursor.fetchall()
columns = [desc[0] for desc in cursor.description]
return {"columns": columns, "rows": results}
Data Analysis Agent
The Data Analysis Agent can understand data requirements, execute queries, and generate analysis reports.
Enables non-technical users to perform complex data analysis.
Core Capabilities
Data Understanding: Understand database structure and data meaning.
Query Generation: Text2SQL, converting natural language into queries.
Visualization: Generate chart suggestions and configurations.
Report Generation: Analyze results and generate natural language reports.
Code Implementation
Data Analysis Agent Implementation
"""
Data Analysis Agent
Understand data requirements, execute analysis, generate reports
"""
def __init__(self, llm, db_connection, chart_generator):
self.llm = llm
self.db = db_connection
self.chart_generator = chart_generator
def analyze(self, request):
"""
Handle data analysis requests
"""
# Step 1: Understand the analysis requirements
intent = self.parse_intent(request)
# Step 2: Generate the query
query = self.generate_query(intent)
# Step 3: Execute the query
data = self.execute_query(query)
# Step 4: Analyze the data
analysis = self.perform_analysis(data, intent)
# Step 5: Generate visualization suggestions
charts = self.suggest_charts(analysis)
# Step 6: Generate the report
report = self.generate_report(analysis, charts)
return {
"intent": intent,
"query": query,
"data": data,
"analysis": analysis,
"charts": charts,
"report": report
}
def parse_intent(self, request):
"""Parse user intent"""
prompt = f"""
Analyze the following data request and extract key information:
Request: {request}
Please extract:
1. Analysis goal (comparison, trend, distribution, etc.)
2. Tables and fields involved
3. Time range (if any)
4. Filter conditions (if any)
"""
return self.llm.generate(prompt)
def generate_query(self, intent):
"""Generate SQL query"""
prompt = f"""
Generate an SQL query based on the following intent:
{intent}
Database Schema:
{self.get_schema()}
"""
return self.llm.generate(prompt)
def execute_query(self, query):
"""Execute query"""
cursor = self.db.cursor()
cursor.execute(query)
columns = [desc[0] for desc in cursor.description]
rows = cursor.fetchall()
return {"columns": columns, "rows": rows}
def perform_analysis(self, data, intent):
"""Execute data analysis"""
# Simplified implementation
import statistics
rows = data["rows"]
columns = data["columns"]
analysis = {
"row_count": len(rows),
"summary": {}
}
# Compute statistics for numeric columns
for i, col in enumerate(columns):
if self.is_numeric(rows, i):
values = [row[i] for row in rows if row[i] is not None]
if values:
analysis["summary"][col] = {
"min": min(values),
"max": max(values),
"avg": statistics.mean(values),
"median": statistics.median(values)
}
return analysis
def suggest_charts(self, analysis):
"""Recommend visualization charts"""
suggestions = []
# Recommend charts based on analysis type
if "trend" in str(analysis).lower():
suggestions.append({
"type": "line",
"description": "Line chart, suitable for showing trends"
})
if "comparison" in str(analysis).lower():
suggestions.append({
"type": "bar",
"description": "Bar chart, suitable for comparing categories"
})
suggestions.append({
"type": "table",
"description": "Data table, showing detailed data"
})
return suggestions
def generate_report(self, analysis, charts):
"""Generate analysis report"""
prompt = f"""
Based on the following analysis results, generate a natural language report:
Analysis results:
{analysis}
Recommended chart:
{charts}
Please generate a clear analysis report.
"""
return self.llm.generate(prompt)
Customer Service Agent
Customer Service Agent needs to handle multi-turn conversations, understand user intent, and provide accurate responses.
It is one of the most widely deployed scenarios of AI.
Core Capabilities
Intent Recognition: Understand what the user wants to do.
Slot Filling: Extract key information (time, location, etc.).
Dialogue State Tracking: Manage multi-turn conversation context.
Response Generation: Generate natural and professional responses.
Code Implementation
Customer Service Agent Implementation
"""
Customer Service Agent
Handle user inquiries and provide service support
"""
def __init__(self, llm, knowledge_base, dialogue_manager):
self.llm = llm
# Knowledge base
self.knowledge_base = knowledge_base
# Dialogue manager
self.dialogue_manager = dialogue_manager
def handle(self, user_input, session_id):
"""
Process user messages
"""
# Get conversation history
history = self.dialogue_manager.get_history(session_id)
# Recognize user intent
intent = self.recognize_intent(user_input, history)
# Process based on intent
if intent.type == "greeting":
response = self.handle_greeting()
elif intent.type == "inquiry":
response = self.handle_inquiry(intent)
elif intent.type == "complaint":
response = self.handle_complaint(intent)
elif intent.type == "order_status":
response = self.handle_order_status(intent)
elif intent.type == "refund":
response = self.handle_refund(intent)
else:
response = self.handle_general(user_input)
# Update conversation history
self.dialogue_manager.add_message(
session_id,
{"role": "user", "content": user_input}
)
self.dialogue_manager.add_message(
session_id,
{"role": "assistant", "content": response}
)
return response
def recognize_intent(self, text, history):
"""Recognize user intent"""
prompt = f"""
Analyze user messages and identify intent type.
Current message: {text}
Conversation history:
{history}
Intent types:
- greeting: Greeting
- inquiry: Ask questions
- complaint: Complaint
- order_status: Check order
- refund: Refund
- goodbye: Farewell
Please output the intent type and confidence.
"""
result = self.llm.generate(prompt)
return Intent.parse(result)
def handle_inquiry(self, intent):
"""Handle inquiry"""
# Retrieve relevant content from knowledge base
relevant_docs = self.knowledge_base.search(intent.query)
if relevant_docs:
# If there are relevant documents, answer based on the documents
prompt = f"""
Answer the user's question based on the following document.
Document:
{relevant_docs}
Question: {intent.query}
"""
return self.llm.generate(prompt)
else:
# No relevant documents, transfer to human or record
return "I need to understand this issue further. Please wait while I check for you."
class Intent:
"""User Intent"""
def __init__(self, type, query, confidence):
self.type = type
self.query = query
self.confidence = confidence
@classmethod
def parse(cls, text):
"""Parse Intent Text"""
# Simplified implementation
return cls(type="inquiry", query=text, confidence=0.9)
Research Agent
The Research Agent can autonomously conduct in-depth research, collect and synthesize information.
Simulates the working style of human researchers.
Core Capabilities
Search Planning: Formulate an information gathering plan.
Multi-source Collection: Collect information from multiple sources.
Information Verification: Cross-verify the accuracy of information.
Report Generation: Synthesize information to generate structured reports.
Code Implementation
Research Agent Implementation
"""
Research Agent
Conduct deep research autonomously and generate reports
"""
def __init__(self, search_tools, llm):
# Search tool list
self.search_tools = search_tools
self.llm = llm
def research(self, topic, depth=3):
"""
Execute research task
:param topic: Research topic
:param depth: Research depth (number of search rounds)
"""
# Step 1: Create a research plan
plan = self.create_research_plan(topic, depth)
# Step 2: Execute multiple rounds of search
findings = []
for phase in plan.phases:
# Search multiple directions in parallel
phase_results = self.search_phase(phase)
findings.extend(phase_results)
# Synthesize current findings
synthesis = self.synthesize(findings)
findings.append({
"type": "synthesis",
"content": synthesis,
"phase": phase.number
})
# Step 3: Generate the final report
report = self.generate_report(findings)
return {
"topic": topic,
"plan": plan,
"findings": findings,
"report": report
}
def create_research_plan(self, topic, depth):
"""Create Research Plan"""
prompt = f"""
Create a detailed plan for the following research topic:
Topic: {topic}
Depth: {depth}
Please plan:
1. Key directions that need research (3-5)
2. Core questions that need to be answered for each direction
3. Suggestions for information sources
"""
return ResearchPlan.parse(self.llm.generate(prompt))
def search_phase(self, phase):
"""Execute Single Search Stage"""
results = []
for query in phase.queries:
# Use search tools to search
for tool in self.search_tools:
search_results = tool.search(query)
results.extend(search_results)
return results
def synthesize(self, findings):
"""Synthesize Findings"""
prompt = f"""
Synthesize the following research findings and extract key information:
Findings list:
{findings}
Please extract:
1. Main conclusions
2. Evidence supporting the conclusions
3. Existing controversies or uncertainties
4. Questions that need further research
"""
return self.llm.generate(prompt)
def generate_report(self, findings):
"""Generate Final Report"""
prompt = f"""
Generate a structured report based on the following research findings:
Research findings:
{findings}
Report requirements:
1. Executive summary
2. Background introduction
3. Key Findings (by Sub-topic)
4. Conclusions and Recommendations
5. References
Please generate a complete report.
"""
return self.llm.generate(prompt)
class ResearchPlan:
"""Research Plan"""
@classmethod
def parse(cls, text):
"""Parse Plan Text"""
# Simplified Implementation
return cls(phases=[
ResearchPhase(number=1, queries=["Related Topic 1"], goals=["Understand Basic Concepts"]),
ResearchPhase(number=2, queries=["Related Topic 2"], goals=["In-depth Analysis"]),
])
def __init__(self, phases):
self.phases = phases
class ResearchPhase:
"""Research Phase"""
def __init__(self, number, queries, goals):
self.number = number
self.queries = queries
self.goals = goals
Other Vertical Applications
RPA + Agent
The combination of RPA (Robotic Process Automation) and Agent.
It can enable automation of more complex business processes.
Agent gives RPA intelligent decision-making capabilities.
Game NPC Agent
NPC (Non-Player Character) Agents in games.
They can conduct dynamic dialogue, plot generation, and role-playing.
Create a more realistic game world experience.
Scientific Research Agent
AI for Science is transforming scientific research.
Literature Review: Automatically read and summarize a large number of papers.
Experiment Design: Propose experimental plans and hypotheses.
Data Analysis: Process experimental data and discover patterns.
Paper Writing: Assist in writing research papers.
Chapter Summary
This chapter introduces the applications of Agent in various vertical domains.
Code AgentAssists in programming and improves development efficiency.
Data Analysis AgentEnables non-technical personnel to analyze data as well.
Customer Service AgentProvides intelligent customer service.
Research AgentConduct in-depth research autonomously.
There are also more scenarios such as RPA+Agent, game NPCs, and scientific research Agents.
Agents in vertical domains need to be customized with domain knowledge.
Choosing the right scenarios and entry points is key to successful implementation.
Other Extensions