aiXplain SDK — Pattern Library
Use these patterns as canonical starting points. Each is minimal, complete, and production-ready.
This file is auto-assembled from individual pattern files under /patterns/.
To add a pattern, convert a tutorial using the aiXplain Pattern Library skill.
Plain-text version for AI tools: pathname:///downloads/pattern-library-skill/raw.txt
Pattern index
| # | Pattern | Intent |
|---|---|---|
| 01 | Web research agent | answer questions with real-time web search |
| 02 | Knowledge base agent | answer from private documents |
| 03 | Advanced knowledge base agent | extract and summarise key sections from long-form documents |
| 04 | SQL data agent | query a database and return answers in natural language |
| 05 | Custom business logic agent | wrap existing Python functions as an agent tool |
| 06 | Multi-agent team with role delegation | coordinate multiple specialised agents on a complex task |
| 07 | Governed agent with runtime inspector | enforce a policy on agent output before it reaches the user |
| 08 | MCP integration agent | connect an agent to any MCP server without building a custom tool |
| 09 | Commercial integration agent | take actions in external SaaS tools like Slack or Google |
| 10 | Code quality agent | automatically write unit tests and documentation for Python code |
| 11 | Travel and planning agent | plan a trip using real-time weather, flight, and recommendation data |
Pattern 01: Web research agent
Intent: answer questions with real-time web search
Replaces: LangChain AgentExecutor + SerpAPI + ReAct prompt engineering
When to use: user needs current information beyond the model's training cutoff
Docs: Quick start
# Pattern: Web research agent
# Intent: answer questions with real-time web search
# Replaces: LangChain AgentExecutor + SerpAPI + ReAct prompt engineering
from aixplain import Aixplain
aix = Aixplain(api_key="YOUR_API_KEY")
search_tool = aix.Tool.get("tavily/tavily-search-api")
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: Quick start · Tools overview
Pattern 02: Knowledge base agent
Intent: answer from private documents
Replaces: LangChain RAG chain + VectorStoreRetriever + FAISS or Chroma setup
When to use: user needs answers grounded in proprietary or internal documents
Docs: Build an agentic RAG
# Pattern: Knowledge base agent
# Intent: answer from private documents
# Replaces: LangChain RAG chain + VectorStoreRetriever + FAISS or Chroma setup
import time
from aixplain import Aixplain
aix = Aixplain(api_key="YOUR_API_KEY")
# 1. Create the index tool
index_tool = aix.Tool(
name=f"Product Knowledge Base {int(time.time())}",
description="Vector database containing product documentation.",
integration="6904bcf672a6e36b68bb72fb", # aiR vector database
)
index_tool.save()
# 2. 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})
# 3. 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 colours 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: Build an agentic RAG · Knowledge base
Pattern 03: Advanced knowledge base agent
Intent: extract and summarise key sections from long-form documents
When to use: documents are large (PDFs, research papers) and need chunking before retrieval
Docs: Build an advanced agentic RAG
# Pattern: Advanced knowledge base agent
# Intent: extract and summarise key sections from long-form documents
import time
from aixplain import Aixplain
aix = Aixplain(api_key="YOUR_API_KEY")
index_tool = aix.Tool(
name=f"Research Index {int(time.time())}",
description="Chunked index of research papers on quantum computing.",
integration="6904bcf672a6e36b68bb72fb",
)
index_tool.save()
# Upsert with automatic chunking for long documents
documents = [
{"id": "paper1", "text": "Quantum computing leverages 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 summarises key findings from research papers.",
instructions=(
"Search the research index to find relevant passages. "
"Summarise 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: Build an advanced agentic RAG · Knowledge base
Pattern 04: SQL data agent
Intent: query a database and return answers in natural language
Replaces: LangChain SQLDatabaseChain + custom SQL prompt + manual schema injection
When to use: user needs natural language access to structured data in a relational database
Docs: Build an agent with SQLite
# Pattern: SQL data agent
# Intent: query a database and return answers in natural language
# Replaces: LangChain SQLDatabaseChain + custom SQL prompt + manual schema injection
import sqlite3, time
from aixplain import Aixplain
aix = Aixplain(api_key="YOUR_API_KEY")
# 1. 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 INTO orders VALUES (?, ?, ?, ?)", [
(1, "Widget A", 10, 500.0),
(2, "Widget B", 3, 150.0),
])
conn.commit()
conn.close()
# 2. Upload and create the SQLite tool
resource = aix.Resource(name=f"Sales DB {int(time.time())}", file_path="sales.db")
resource.save()
sqlite_tool = aix.Tool(
name="Sales Database",
description="Query sales orders from the SQLite database.",
integration="689e06ed3ce71f58d73cc999", # SQLite integration ID
config={"url": resource.url},
)
sqlite_tool.save()
# 3. Build the agent
agent = aix.Agent(
name="Sales Analyst",
description="Answers sales questions by querying the database.",
instructions="Query the database 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: Build an agent with SQLite · SQLite
Pattern 05: Custom business logic agent
Intent: wrap existing Python functions as an agent tool
Replaces: LangChain @tool decorator + StructuredTool + manual schema definition
When to use: agent needs to call internal functions, APIs, or business rules defined in Python
Docs: Build agents with custom tools
# Pattern: Custom business logic agent
# Intent: wrap existing Python functions as an agent tool
# Replaces: LangChain @tool decorator + StructuredTool + manual schema definition
import inspect, time
from aixplain import Aixplain
aix = Aixplain(api_key="YOUR_API_KEY")
# 1. Define the function — all imports inside, type hints required
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),
}
# 2. Create and save the tool
discount_tool = aix.Tool(
name=f"Discount Calculator {int(time.time())}",
description="Calculates the discounted price given an original price and discount percentage.",
integration="688779d8bfb8e46c273982ca", # Python Sandbox
config={
"code": inspect.getsource(calculate_discount),
"function_name": "calculate_discount",
},
)
discount_tool.save()
# 3. 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: Build agents with custom tools · Python sandbox
Pattern 06: Multi-agent team with role delegation
Intent: coordinate multiple specialised agents to solve a complex task
Replaces: CrewAI Crew + role definitions + process configuration
When to use: task requires parallel specialisation — research and synthesis, multi-step workflows, or role separation
Docs: Team agents
# Pattern: Multi-agent team with role delegation
# Intent: coordinate multiple specialised agents to solve a complex task
# Replaces: CrewAI Crew + role definitions + process configuration
from aixplain import Aixplain
aix = Aixplain(api_key="YOUR_API_KEY")
search_tool = aix.Tool.get("tavily/tavily-search-api")
researcher = aix.Agent(
name="Researcher",
description="Searches for information and gathers data.",
tools=[search_tool],
)
writer = aix.Agent(
name="Writer",
description="Writes clear, well-structured reports in markdown.",
output_format="markdown",
)
team = aix.Agent(
name="Research and Writing Team",
description="Researches topics and produces written reports.",
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 specialised subagents with scoped roles and tools
save_subcomponents=Truesaves all subagents before saving the team- The Mentalist micro-agent plans and delegates tasks at runtime — no explicit orchestration code
Extend this pattern: Team agents · Inspectors
Pattern 07: Governed agent with runtime inspector
Intent: enforce a policy on agent output before it reaches the user
Replaces: Guardrails AI wrapper + custom validation middleware + output post-processing
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
# Replaces: Guardrails AI wrapper + custom validation middleware + output post-processing
from aixplain import Aixplain
from aixplain.v2.inspector import (
Inspector,
InspectorSeverity,
InspectorAction,
InspectorActionConfig,
InspectorOnExhaust,
EvaluatorType,
EvaluatorConfig,
)
aix = Aixplain(api_key="YOUR_API_KEY")
search_tool = aix.Tool.get("tavily/tavily-search-api")
subagent = aix.Agent(
name="Content Writer",
description="Writes responses to user queries.",
tools=[search_tool],
)
llm_asset_id = aix.Model.get("openai/gpt-4o").id
inspector = Inspector(
name="safety-guard",
description="Blocks output containing harmful or policy-violating content.",
severity=InspectorSeverity.CRITICAL,
targets=["output"],
action=InspectorActionConfig(
type=InspectorAction.RERUN,
max_retries=2,
on_exhaust=InspectorOnExhaust.ABORT,
),
evaluator=EvaluatorConfig(
type=EvaluatorType.ASSET,
asset_id=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.",
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 · Team agents
Pattern 08: 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: Build an agent with 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="Web Fetch MCP",
config={"url": "https://remote.mcpservers.org/fetch/mcp"},
)
mcp_tool.save()
# Scope to only the actions your agent needs
mcp_tool.allowed_actions = ["fetch"]
agent = aix.Agent(
name="MCP Agent",
description="Fetches and summarises web pages via MCP.",
instructions="Use the MCP tool to fetch page content, then summarise key points concisely.",
tools=[mcp_tool],
)
agent.save()
result = agent.run("Summarise the content at https://www.aixplain.com.")
print(result.data.output)
What this does:
- Connects to any HTTP or SSE MCP server 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: Build an agent with remote MCP · Remote MCP
Pattern 09: Commercial 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: Build an agent with integrations
# Pattern: Commercial integration agent
# Intent: take actions in external SaaS tools like Slack or Google
import time
from aixplain import Aixplain
aix = Aixplain(api_key="YOUR_API_KEY")
slack_tool = aix.Tool(
name=f"Slack Notifier {int(time.time())}",
description="Sends messages to Slack channels.",
integration="composio/slack",
config={"token": "YOUR_SLACK_TOKEN"},
)
slack_tool.allowed_actions = ["SLACK_SENDS_A_MESSAGE_TO_A_SLACK_CHANNEL"]
slack_tool.save()
search_tool = aix.Tool.get("tavily/tavily-search-api")
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:
- Creates a Composio-backed Slack tool using an API token — no UI OAuth flow required
- 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: Build an agent with integrations · Commercial integrations
Pattern 10: 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: Build a unit test agent
# 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(
query="Write unit tests and add a docstring for this function.",
content=[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
contentpasses the source code as context separate from the query
Extend this pattern: Build a unit test agent · Agents
Pattern 11: 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: Build a travel agent
# Pattern: Travel and planning agent
# Intent: plan a trip using real-time weather, flight, and recommendation data
import inspect, time
from aixplain import Aixplain
aix = Aixplain(api_key="YOUR_API_KEY")
search_tool = aix.Tool.get("tavily/tavily-search-api")
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=f"Budget Estimator {int(time.time())}",
description="Estimates travel budget for a trip given origin, destination, and duration.",
integration="688779d8bfb8e46c273982ca",
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 traveller.")
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: Build a travel agent · Custom tools