Pattern library
Use these patterns as starting points. Each one is minimal and complete.
Pattern index
| Pattern | Intent |
|---|---|
| Web research agent | answer questions with real-time web search |
| Knowledge base agent | answer from private documents |
| Advanced knowledge base agent | extract and summarize key sections from long-form documents |
| SQL data agent | query a database and return answers in natural language |
| Custom business logic agent | wrap existing Python functions as an agent tool |
| Multi-agent team with role delegation | coordinate multiple specialized agents on a complex task |
| Governed agent with runtime inspector | enforce a policy on agent output before it reaches the user |
| MCP integration agent | connect an agent to any MCP server without building a custom tool |
| Integration agent | take actions in external SaaS tools like Slack or Google |
| Code quality agent | automatically write unit tests and documentation for Python code |
| Travel and planning agent | plan a trip using real-time weather, flight, and recommendation data |
Web research agent
Intent: answer questions with real-time web search
When to use: user needs current information beyond the model's training cutoff
Docs: Quickstart
# Pattern: Web research agent
# Intent: answer questions with real-time web search
from aixplain import Aixplain
aix = Aixplain(api_key="YOUR_API_KEY")
search_tool = aix.Tool.get("tavily/tavily-web-search/tavily")
agent = aix.Agent(
name="Research agent",
description="Answers questions using real-time web search.",
instructions="Use web search when needed. Always cite your sources.",
tools=[search_tool],
)
agent.save()
result = agent.run("What are the latest developments in AI safety?")
print(result.data.output)
What this does:
- Fetches a pre-built search tool from the aixplain marketplace
- Creates an agent that autonomously decides when to invoke web search
- Returns a cited, up-to-date answer grounded in live results
Extend this pattern: Quickstart · Tools
Knowledge base agent
Intent: answer from private documents
When to use: user needs answers grounded in proprietary or internal documents
Docs: Knowledge base
# Pattern: Knowledge base agent
# Intent: answer from private documents
from aixplain import Aixplain
aix = Aixplain(api_key="YOUR_API_KEY")
# Create the index tool
index_tool = aix.Tool(
name="Product knowledge base",
description="Vector database containing product documentation.",
integration="aixplain/air-knowledge-base/aixplain",
)
index_tool.save()
# Upsert documents
documents = [
{"id": "doc1", "text": "Widget A costs $50. It is available in red and blue.", "metadata": {"category": "pricing"}},
{"id": "doc2", "text": "Widget B costs $30. It ships within 2 business days.", "metadata": {"category": "shipping"}},
]
index_tool.run(action="upsert", data={"records": documents})
# Attach to agent — restrict to read-only actions
index_tool.allowed_actions = ["search", "get"]
agent = aix.Agent(
name="Product assistant",
description="Answers product questions from the knowledge base.",
instructions="Search the knowledge base to answer questions. Include price and availability.",
tools=[index_tool],
)
agent.save()
result = agent.run("What colors does Widget A come in and how much does it cost?")
print(result.data.output)
What this does:
- Creates a vector index and populates it with your documents
- Restricts the agent to read-only index actions (no accidental writes)
- Returns answers grounded in the indexed documents, not the LLM's training data
Extend this pattern: Knowledge base
Advanced knowledge base agent
Intent: extract and summarize key sections from long-form documents
When to use: documents are large (PDFs, research papers) and need chunking before retrieval
Docs: Knowledge base
# Pattern: Advanced knowledge base agent
# Intent: extract and summarize key sections from long-form documents
from aixplain import Aixplain
aix = Aixplain(api_key="YOUR_API_KEY")
index_tool = aix.Tool(
name="Research index",
description="Chunked index of research papers on quantum computing.",
integration="aixplain/air-knowledge-base/aixplain",
)
index_tool.save()
# Upsert with automatic chunking for long documents
documents = [
{"id": "paper1", "text": "Quantum computing uses superposition and entanglement to process information. [... full paper text ...]"},
{"id": "paper2", "text": "Error correction in quantum systems requires redundant qubit encoding. [... full paper text ...]"},
]
index_tool.run(action="upsert", data={
"records": documents,
"chunking": {
"split_by": "sentence",
"split_length": 3,
"split_overlap": 1,
},
})
index_tool.allowed_actions = ["search", "get"]
agent = aix.Agent(
name="Research analyst",
description="Extracts and summarizes key findings from research papers.",
instructions=(
"Search the research index to find relevant passages. "
"Summarize findings clearly. Cite the source document ID for each claim."
),
tools=[index_tool],
)
agent.save()
result = agent.run("What does the research say about error correction in quantum systems?")
print(result.data.output)
What this does:
- Splits long documents into overlapping sentence chunks before indexing
- Enables precise retrieval over lengthy papers without context-window overflow
- Agent cites source document IDs so claims are traceable
Extend this pattern: Knowledge base
SQL data agent
Intent: query a database and return answers in natural language
When to use: user needs natural language access to structured data in a relational database
Docs: Databases
# Pattern: SQL data agent
# Intent: query a database and return answers in natural language
import sqlite3
from aixplain import Aixplain
from aixplain.v2 import FileUploader
aix = Aixplain(api_key="YOUR_API_KEY")
# Create the database
conn = sqlite3.connect("sales.db")
conn.execute("CREATE TABLE IF NOT EXISTS orders (id INTEGER PRIMARY KEY, product TEXT, quantity INTEGER, revenue REAL)")
conn.executemany("INSERT OR REPLACE INTO orders VALUES (?, ?, ?, ?)", [
(1, "Widget A", 10, 500.0),
(2, "Widget B", 3, 150.0),
])
conn.commit()
conn.close()
# Upload the database file and create the SQLite tool
db_url = FileUploader(api_key="YOUR_API_KEY").upload("sales.db", return_download_link=True)
sqlite_tool = aix.Tool(
name="Sales database",
description="Query sales orders from the SQLite database.",
integration="aixplain/sqlite/aixplain",
config={"url": db_url},
)
sqlite_tool.save()
sqlite_tool.allowed_actions = ["query", "schema"]
# Build the agent; the schema in instructions keeps its SQL on real columns
agent = aix.Agent(
name="Sales analyst",
description="Answers sales questions by querying the database.",
instructions=(
"Table orders(id INTEGER, product TEXT, quantity INTEGER, revenue REAL). "
"Query the database with SQL to answer questions. Return plain text summaries with numbers."
),
tools=[sqlite_tool],
)
agent.save()
result = agent.run("Which product had the highest revenue?")
print(result.data.output)
What this does:
- Uploads a local SQLite file to cloud storage and registers it as a tool
- Agent generates and executes SQL queries autonomously
- Returns plain-language answers without exposing SQL to the end user
Extend this pattern: Databases
Custom business logic agent
Intent: wrap existing Python functions as an agent tool
When to use: agent needs to call internal functions, APIs, or business rules defined in Python
Docs: Python sandbox
# Pattern: Custom business logic agent
# Intent: wrap existing Python functions as an agent tool
import inspect
from aixplain import Aixplain
aix = Aixplain(api_key="YOUR_API_KEY")
# Define the function; type hints help the agent call it correctly
def calculate_discount(price: float, discount_percent: float):
"""Calculate discounted price for a product."""
discount = price * (discount_percent / 100)
return {
"original_price": price,
"discount_amount": round(discount, 2),
"final_price": round(price - discount, 2),
}
# Create and save the tool
discount_tool = aix.Tool(
name="Discount calculator",
description="Calculates the discounted price given an original price and discount percentage.",
integration="aixplain/python-sandbox/aixplain",
config={
"code": inspect.getsource(calculate_discount),
"function_name": "calculate_discount",
},
)
discount_tool.save()
# Build the agent
agent = aix.Agent(
name="Pricing assistant",
description="Answers pricing questions using the discount calculator.",
instructions="Use the discount calculator tool to compute prices. Always show the final price.",
tools=[discount_tool],
)
agent.save()
result = agent.run("What is the final price of a $200 item with a 15% discount?")
print(result.data.output)
What this does:
- Deploys a Python function as a sandboxed, callable tool with no server setup
- Schema is inferred from type hints — no manual definition required
- Agent selects and invokes the function autonomously based on the query
Extend this pattern: Python sandbox
Multi-agent team with role delegation
Intent: coordinate multiple specialized agents to solve a complex task
When to use: task requires parallel specialization — research and synthesis, multi-step workflows, or role separation
Docs: Subagents
# Pattern: Multi-agent team with role delegation
# Intent: coordinate multiple specialized agents to solve a complex task
from aixplain import Aixplain
aix = Aixplain(api_key="YOUR_API_KEY")
search_tool = aix.Tool.get("tavily/tavily-web-search/tavily")
researcher = aix.Agent(
name="Researcher",
description="Searches for information and gathers data.",
instructions="Search the web for current, sourced facts on the topic. Return the facts with their sources.",
tools=[search_tool],
)
writer = aix.Agent(
name="Writer",
description="Writes clear, well-structured reports in markdown.",
instructions="Write a short report from the research you receive. Keep the sources.",
output_format="markdown",
)
team = aix.Agent(
name="Research and writing team",
description="Researches topics and produces written reports.",
instructions="Have the researcher gather facts, then have the writer turn them into a report.",
agents=[researcher, writer],
)
team.save(save_subcomponents=True)
result = team.run("Research the current state of fusion energy and write a summary report.")
print(result.data.output)
What this does:
- Defines specialized subagents with scoped roles and tools
save_subcomponents=Truesaves all subagents before saving the team- The team plans and delegates tasks to subagents at run time, with no orchestration code
Extend this pattern: Subagents · Inspectors
Governed agent with runtime inspector
Intent: enforce a policy on agent output before it reaches the user
When to use: output must meet a compliance, brand, or safety policy before delivery
Docs: Inspectors
# Pattern: Governed agent with runtime inspector
# Intent: enforce a policy on agent output before it reaches the user
from aixplain import Aixplain
aix = Aixplain(api_key="YOUR_API_KEY")
search_tool = aix.Tool.get("tavily/tavily-web-search/tavily")
subagent = aix.Agent(
name="Content writer",
description="Writes responses to user queries.",
instructions="Write the requested content. Use web search for facts you are unsure of.",
tools=[search_tool],
)
llm_asset_id = aix.Model.get("openai/gpt-5.4/openai").id
inspector = aix.Inspector(
name="safety-guard",
description="Blocks output containing harmful or policy-violating content.",
severity="critical",
targets=["output"],
action={"type": "rerun", "max_retries": 2, "on_exhaust": "abort"},
metric={
"assetId": llm_asset_id,
"prompt": "If the output contains harmful, offensive, or policy-violating content, describe the violation. Otherwise pass.",
},
)
team = aix.Agent(
name="Governed content team",
description="Produces responses that pass safety review before delivery.",
instructions="Delegate writing to the content writer and return its result.",
agents=[subagent],
inspectors=[inspector],
)
team.save(save_subcomponents=True)
result = team.run("Write a product description for our new line of kitchen knives.")
if result.status == "SUCCESS":
print(result.data.output)
else:
print("Response blocked:", result.status)
What this does:
- Attaches an LLM-based evaluator to the team agent's output
- Automatically reruns the subagent with the critique injected if the policy is violated
- Aborts and returns a failure status after 2 failed retries
Extend this pattern: Inspectors · Subagents
MCP integration agent
Intent: connect an agent to any MCP server without building a custom tool
When to use: user wants to expose an MCP server's capabilities as agent tools
Docs: Remote MCP
# Pattern: MCP integration agent
# Intent: connect an agent to any MCP server without building a custom tool
from aixplain import Aixplain
aix = Aixplain(api_key="YOUR_API_KEY")
mcp_tool = aix.Tool(
integration="aixplain/mcp-server",
name="DeepWiki MCP",
description="Reads the documentation wiki of a public GitHub repository.",
config={"url": "https://mcp.deepwiki.com/mcp"},
)
mcp_tool.save()
# Scope to only the actions your agent needs
mcp_tool.allowed_actions = ["read_wiki_structure"]
agent = aix.Agent(
name="Repository guide",
description="Explains how GitHub repositories are organized, using an MCP server.",
instructions="Use the DeepWiki MCP tool to read a repository's wiki before answering. Keep answers short.",
tools=[mcp_tool],
)
agent.save()
result = agent.run("What are the main topics in the aixplain/aiXplain repository wiki?")
print(result.data.output)
What this does:
- Connects to any MCP server over Streamable HTTP with a single config line
- Scopes allowed actions to reduce context bloat and prevent unreviewed tool use
- Agent invokes MCP actions autonomously based on the query
Extend this pattern: Remote MCP
Integration agent
Intent: take actions in external SaaS tools like Slack or Google
When to use: agent needs to read from or write to a third-party service (Slack, Salesforce, Linear, etc.)
Docs: Integrations
# Pattern: Integration agent
# Intent: take actions in external SaaS tools like Slack or Google
from aixplain import Aixplain
aix = Aixplain(api_key="YOUR_API_KEY")
slack_tool = aix.Tool(
name="Slack notifier",
description="Sends messages to Slack channels.",
integration="composio/slack/composio",
config={"token": "YOUR_SLACK_TOKEN"},
)
slack_tool.allowed_actions = ["SLACK_SEND_MESSAGE"]
slack_tool.save()
search_tool = aix.Tool.get("tavily/tavily-web-search/tavily")
agent = aix.Agent(
name="Alert agent",
description="Monitors topics and sends Slack alerts when significant events occur.",
instructions=(
"Search for the latest news on the given topic. "
"If there is a significant development, send a concise alert to the #alerts Slack channel."
),
tools=[search_tool, slack_tool],
)
agent.save()
result = agent.run("Check for major AI regulation news and notify the team if anything significant happened today.")
print(result.data.output)
What this does:
- Connects a Slack tool with a bearer token, with no browser sign-in
- Scopes the tool to a single action to prevent unintended Slack operations
- Agent combines web search and Slack notification in a single autonomous run
Extend this pattern: Integrations
Code quality agent
Intent: automatically write unit tests and documentation for Python code
When to use: developer wants automated test and docstring generation for a Python module
Docs: Agents
# Pattern: Code quality agent
# Intent: automatically write unit tests and documentation for Python code
from aixplain import Aixplain
aix = Aixplain(api_key="YOUR_API_KEY")
agent = aix.Agent(
name="Code quality agent",
description="Writes unit tests and docstrings for Python code.",
instructions=(
"When given Python code:\n"
"1. Write a complete pytest test file covering all functions and edge cases.\n"
"2. Add Google-style docstrings to any function that lacks one.\n"
"3. Return the test file first, then the updated source with docstrings.\n"
"Use only the standard library and pytest — no additional dependencies."
),
output_format="markdown",
)
agent.save()
source_code = """
def calculate_bmi(weight_kg: float, height_m: float) -> dict:
bmi = weight_kg / (height_m ** 2)
if bmi < 18.5:
category = "underweight"
elif bmi < 25:
category = "normal"
elif bmi < 30:
category = "overweight"
else:
category = "obese"
return {"bmi": round(bmi, 2), "category": category}
"""
result = agent.run(f"Write unit tests and add a docstring for this function:\n{source_code}")
print(result.data.output)
What this does:
- Uses a pure LLM agent — no external tools needed for code analysis
- Instructions enforce a consistent output structure: test file then annotated source
- The source code travels in the prompt, so any string of code works
Extend this pattern: Agents
Travel and planning agent
Intent: plan a trip using real-time weather, flight, and recommendation data
When to use: user needs a single agent that combines multiple real-time data sources for itinerary planning
Docs: Tools
# Pattern: Travel and planning agent
# Intent: plan a trip using real-time weather, flight, and recommendation data
import inspect
from aixplain import Aixplain
aix = Aixplain(api_key="YOUR_API_KEY")
search_tool = aix.Tool.get("tavily/tavily-web-search/tavily")
def get_trip_budget(origin: str, destination: str, duration_days: int) -> dict:
"""Estimate a travel budget based on destination and trip length."""
daily_estimates = {"Paris": 200, "Tokyo": 180, "New York": 250, "Bangkok": 80}
daily = daily_estimates.get(destination, 150)
return {
"destination": destination,
"duration_days": duration_days,
"estimated_daily_cost_usd": daily,
"estimated_total_usd": daily * duration_days,
"currency": "USD",
}
budget_tool = aix.Tool(
name="Budget estimator",
description="Estimates travel budget for a trip given origin, destination, and duration.",
integration="aixplain/python-sandbox/aixplain",
config={
"code": inspect.getsource(get_trip_budget),
"function_name": "get_trip_budget",
},
)
budget_tool.save()
agent = aix.Agent(
name="Travel planner",
description="Plans trips with real-time data on weather, attractions, and budget.",
instructions=(
"When planning a trip:\n"
"1. Search for current weather and top attractions at the destination.\n"
"2. Use the budget estimator to calculate the estimated trip cost.\n"
"3. Return a structured itinerary with daily activities and a cost summary."
),
tools=[search_tool, budget_tool],
output_format="markdown",
)
agent.save()
result = agent.run("Plan a 5-day trip to Tokyo from New York for a solo traveler.")
print(result.data.output)
What this does:
- Combines a marketplace search tool with a custom budget calculator in one agent
- Agent autonomously decides when to search and when to invoke the budget tool
- Returns a structured markdown itinerary with cost estimates
Extend this pattern: Tools · Python sandbox