Real-World Use Cases
1. Customer Support Agent
An agent that handles customer inquiries by searching knowledge bases, checking order status, and escalating when needed:
from langchain.agents import AgentExecutor, create_openai_tools_agent
from langchain_openai import ChatOpenAI
from langchain.tools import tool
@tool
def search_knowledge_base(query: str) -> str:
"""Search the company FAQ and documentation."""
# Vector similarity search against company docs
results = vectorstore.similarity_search(query, k=3)
return "\n".join([doc.page_content for doc in results])
@tool
def check_order_status(order_id: str) -> str:
"""Check the status of a customer order."""
order = db.query(f"SELECT * FROM orders WHERE id = '{order_id}'")
return f"Order {order_id}: {order['status']}, ETA: {order['delivery_date']}"
@tool
def create_support_ticket(issue: str, priority: str) -> str:
"""Create a support ticket for issues requiring human review."""
ticket_id = ticketing_system.create(issue=issue, priority=priority)
return f"Ticket {ticket_id} created. A human agent will follow up within 24 hours."
@tool
def process_refund(order_id: str, reason: str) -> str:
"""Process a refund for an order (max $100 without approval)."""
order = db.query(f"SELECT amount FROM orders WHERE id = '{order_id}'")
if order["amount"] <= 100:
payment_system.refund(order_id)
return f"Refund of ${order['amount']} processed for order {order_id}"
return "Refund exceeds $100 limit. Escalating to supervisor."
# System prompt defines agent behavior
system_prompt = """You are a helpful customer support agent for TechStore.
Rules:
- Always greet the customer warmly
- Search the knowledge base before saying "I don't know"
- Process refunds under $100 automatically
- Escalate complex issues by creating tickets
- Never share internal system details with customers
- Always confirm actions before executing them"""
2. Data Analysis Agent
An agent that can query databases, create visualizations, and generate reports:
@tool
def query_sql(question: str) -> str:
"""Convert a natural language question to SQL and execute it."""
# LLM generates SQL from the question
sql = llm.invoke(
f"Given tables: sales(date, product, revenue, region), "
f"customers(id, name, segment, lifetime_value)\n"
f"Write SQL for: {question}"
).content
result = db.execute(sql)
return f"Query: {sql}\nResult: {result}"
@tool
def create_chart(data: str, chart_type: str, title: str) -> str:
"""Create a chart from data and save as image."""
import matplotlib.pyplot as plt
import json
parsed = json.loads(data)
fig, ax = plt.subplots()
if chart_type == "bar":
ax.bar(parsed["labels"], parsed["values"])
elif chart_type == "line":
ax.plot(parsed["labels"], parsed["values"])
ax.set_title(title)
filename = f"charts/{title.replace(' ', '_')}.png"
plt.savefig(filename)
return f"Chart saved to {filename}"
@tool
def generate_report(findings: str, format: str) -> str:
"""Generate a formatted report from analysis findings."""
report = llm.invoke(
f"Create a professional {format} report from these findings:\n{findings}"
).content
with open(f"reports/analysis_report.{format}", "w") as f:
f.write(report)
return "Report generated successfully"
# Usage: "Analyze Q4 sales trends by region, create a bar chart,
# and generate a PDF report with recommendations"
3. DevOps Automation Agent
An agent that monitors systems, diagnoses issues, and applies fixes:
@tool
def check_service_health(service_name: str) -> str:
"""Check health status of a microservice."""
response = requests.get(f"http://{service_name}/health")
metrics = cloudwatch.get_metrics(service_name, period=300)
return f"Status: {response.status_code}, CPU: {metrics['cpu']}%, Memory: {metrics['memory']}%"
@tool
def get_logs(service_name: str, minutes: int) -> str:
"""Retrieve recent logs from CloudWatch."""
logs = cloudwatch_logs.filter(
log_group=f"/ecs/{service_name}",
start_time=datetime.now() - timedelta(minutes=minutes)
)
return "\n".join([log["message"] for log in logs[:50]])
@tool
def scale_service(service_name: str, desired_count: int) -> str:
"""Scale an ECS service to the desired number of tasks."""
ecs.update_service(
cluster="production",
service=service_name,
desiredCount=desired_count
)
return f"Scaled {service_name} to {desired_count} tasks"
@tool
def restart_service(service_name: str) -> str:
"""Force restart a service by stopping all tasks."""
ecs.update_service(
cluster="production",
service=service_name,
forceNewDeployment=True
)
return f"Restarting {service_name}..."
@tool
def create_incident(title: str, severity: str, details: str) -> str:
"""Create a PagerDuty incident for the on-call team."""
incident = pagerduty.create_incident(
title=title, severity=severity, body=details
)
return f"Incident created: {incident['id']}"
# Agent can autonomously: detect high CPU → check logs → identify memory leak
# → scale service → create incident → notify team
4. Code Review Agent
@tool
def get_pull_request_diff(pr_number: int) -> str:
"""Fetch the diff of a pull request from GitHub."""
pr = github.get_repo("org/repo").get_pull(pr_number)
return pr.get_files()
@tool
def check_code_style(code: str, language: str) -> str:
"""Run linting and style checks on code."""
if language == "python":
result = subprocess.run(["ruff", "check", "--stdin"], input=code)
return result.stdout
@tool
def run_tests(test_path: str) -> str:
"""Run unit tests and return results."""
result = subprocess.run(["pytest", test_path, "--tb=short"])
return result.stdout
@tool
def post_review_comment(pr_number: int, comment: str, file: str, line: int) -> str:
"""Post a review comment on a specific line of a PR."""
pr = github.get_repo("org/repo").get_pull(pr_number)
pr.create_review_comment(body=comment, path=file, line=line)
return "Comment posted"
# Agent reviews PRs: checks style → identifies bugs → suggests improvements
# → verifies tests pass → posts inline comments
5. Personal Research Assistant
@tool
def search_papers(query: str, num_results: int = 5) -> str:
"""Search academic papers on Google Scholar/arXiv."""
papers = scholarly.search(query, limit=num_results)
return format_papers(papers)
@tool
def summarize_pdf(url: str) -> str:
"""Download and summarize a PDF document."""
content = extract_pdf_text(url)
summary = llm.invoke(f"Summarize this paper:\n{content[:5000]}")
return summary.content
@tool
def save_notes(topic: str, notes: str) -> str:
"""Save research notes to the knowledge base."""
vectorstore.add_texts([notes], metadatas=[{"topic": topic}])
return f"Notes saved under topic: {topic}"
@tool
def compare_papers(paper_ids: list) -> str:
"""Compare methodology and findings across multiple papers."""
papers = [get_paper_content(pid) for pid in paper_ids]
comparison = llm.invoke(
f"Compare these papers on methodology, findings, and limitations:\n"
+ "\n---\n".join(papers)
)
return comparison.content