Runoob Tutorial ArchiveEnglish

AI Agent vertical application scenarios

AI Agent vertical application scenarios

Different domains have different needs 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 currently.

Capable of understanding codebases, writing new code, and debugging 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: Identify issues and areas for improvement in the code.

Bug Localization: Analyze error messages to pinpoint the root cause of the problem.

Code Refactoring: Propose and implement code optimization suggestions.

Representative System

System Development 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

class

Text2SQLAgent:

   

"""
Text2SQL Agent
Converts 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 questions to SQL
:param question: Natural language question
:return: SQL query statement
"""

prompt

=

f

"""
You are a SQL expert.

Database Schema:
{self.schema}

Rules:

  1. Only generate SELECT queries (INSERT/UPDATE/DELETE not supported)
  2. Use reasonable 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 if it only contains 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 keyword: {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.

Allowing non-technical personnel to perform complex data analysis.

Core capabilities

Data Understanding: Understanding database structure and data meaning.

Query Generation: Text2SQL, converting natural language to queries.

Visualization: Generating chart suggestions and configurations.

Report Generation: Analyzing results and generating natural language reports.

Code Implementation

Data Analysis Agent Implementation

class

DataAnalysisAgent:

   

"""
Data Analysis Agent
Understand data requirements, perform analysis, and 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

)

:

       

"""
Process data analysis requests
"""

       

Step 1: Understand the analysis requirements

intent

=

self

.

parse_intent

(

request

)

       

       

Step 2: Generate query

query

=

self

.

generate_query

(

intent

)

       

       

Step 3: Execute query

data

=

self

.

execute_query

(

query

)

       

       

Step four: Data analysis

analysis

=

self

.

perform_analysis

(

data

,

intent

)

       

       

Step five: Generate visualization suggestions

charts

=

self

.

suggest_charts

(

analysis

)

       

       

Step six: Generate 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

)

:

       

"""Analyze 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. Filtering 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"

:

{

}

       

}

       

       

Calculate statistics for the log-transformed column

       

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

)

:

       

"""Recommended visualization charts"""

suggestions

=

[

]

       

       

Recommend charts based on analysis type

       

if

"trend"

in

str

(

analysis

)

.

lower

(

)

:

suggestions.

append

(

{

               

"type"

:

"line"

,

               

"description"

:

"Line chart, suitable for displaying trend changes"

           

}

)

       

       

if

"comparison"

in

str

(

analysis

)

.

lower

(

)

:

suggestions.

append

(

{

               

"type"

:

"bar"

,

               

"description"

:

"Bar chart, suitable for comparing different categories"

           

}

)

       

suggestions.

append

(

{

           

"type"

:

"table"

,

           

"description"

:

Data table, displaying detailed data

       

}

)

       

       

return

suggestions

   

   

def

generate_report

(

self

,

analysis

,

charts

)

:

       

"""Generate analysis report"""

prompt

=

f

"""
Generate a natural language report based on the following analysis results:

Analysis results:
{analysis}

Recommended charts:
{charts}

Please generate a clear analysis report.
"""

       

return

self

.

llm

.

generate

(

prompt

)


Customer Service Agent

Customer Service Agents need to handle multi-turn conversations, understand user intent, and provide accurate responses.

It is one of the most widespread scenarios for AI implementation.

Core Capabilities

Intent Recognition: Understanding 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 replies.

Code implementation

Customer Service Agent implementation

class

CustomerServiceAgent:

   

"""
Customer Service Agent
Handles user inquiries and provides 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 message
"""

       

Get conversation history

history

=

self

.

dialogue_manager

.

get_history

(

session_id

)

       

       

Identify 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

)

:

       

"""Identify user intent"""

prompt

=

f

"""
Analyze the user message and identify the intent type.

Current message: {text}

Conversation history:
{history}

Intent type:

Please output the intent type and confidence.
"""

result

=

self

.

llm

.

generate

(

prompt

)

       

return

Intent.

parse

(

result

)

   

   

def

handle_inquiry

(

self

,

intent

)

:

       

"""Handle consultation"""

       

Retrieve relevant content from the 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 documents.

Documents:
{relevant_docs}

Question: {intent.query}
"""

           

return

self

.

llm

.

generate

(

prompt

)

       

else

:

           

No relevant documentation, 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

)


Agent research

Researching the ability of Agents to conduct in-depth research, collect, and synthesize information autonomously.

Simulating the workflow of a human researcher.

Core capabilities

Search planning: Formulating an information gathering plan.

Multi-source collection: Gathering information from multiple sources.

Information verification: Cross-validating information accuracy.

Report generation: Synthesizing information to generate structured reports.

Code implementation

Research Agent implementation

class

ResearchAgent:

   

"""
Research Agent
Independently conduct in-depth research 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 one: Formulate research plan

plan

=

self

.

create_research_plan

(

topic

,

depth

)

       

       

Step 2: Execute multi-round search

findings

=

[

]

       

for

phase

in

plan.

phases

:

           

Parallel search in multiple directions

phase_results

=

self

.

search_phase

(

phase

)

findings.

extend

(

phase_results

)

           

           

Comprehensive current findings

synthesis

=

self

.

synthesize

(

findings

)

findings.

append

(

{

               

"type"

:

"synthesis"

,

               

"content"

: synthesis

,

               

"phase"

: phase.

number

           

}

)

       

       

Step 3: Generate 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 topics:

Topic: {topic}
Depth: {depth}

Please plan:

  1. Key research directions (3-5) that need to be investigated
  2. Core questions that each direction needs to answer
  3. Suggested information sources
    """

       

return

ResearchPlan.

parse

(

self

.

llm

.

generate

(

prompt

)

)

   

   

def

search_phase

(

self

,

phase

)

:

       

"Execute a single search stage"

results

=

[

]

       

       

for

query

in

phase.

queries

:

           

Use the search tool to search

           

for

tool

in

self

.

search_tools

:

search_results

=

tool.

search

(

query

)

results.

extend

(

search_results

)

       

       

return

results

   

   

def

synthesize

(

self

,

findings

)

:

       

"Comprehensive Findings"

prompt

=

f

"""
Synthesize the following research findings and extract key information:

List of findings:
{findings}

Please extract:

  1. Main conclusions
  2. Evidence supporting the conclusions
  3. Existing controversies or uncertainties
  4. Questions requiring 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 Topic)
  4. Conclusions and Recommendations
  5. References

Please generate the full 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 Topics 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

Combining RPA (Robotic Process Automation) with Agents.

Capable of achieving more complex business process automation.

Agents endow RPA with intelligent decision-making capabilities.

Game NPC Agent

NPC (Non-Player Character) Agent in games.

Capable of dynamic dialogue, plot generation, and role-playing.

Create a more realistic game world experience.

Research Agent

AI for Science is changing scientific research.

Literature Review: Automatically reading and summarizing large amounts of papers.

Experimental Design: Proposing experimental plans and hypotheses.

Data Analysis: Processing experimental data and discovering patterns.

Paper Writing: Assisting in writing scientific papers.


Chapter Summary

This chapter introduces the application of Agents in various vertical domains.

Code Agents assist in programming to improve development efficiency.

Data Analysis Agents allow non-technical personnel to analyze data.

Customer Service Agents provide intelligent customer service.

Research Agents autonomously conduct in-depth research.

There are also more scenarios such as RPA+Agent, game NPCs, and scientific research Agents.

Agents in vertical domains require customization combined with domain knowledge.

Choosing the right scenario and entry point is the key to successful implementation.