aiXplain SDK — Pattern Library ================================ Minimal, complete, production-ready patterns. One file. No narrative. --- PATTERN 01: Web research agent Intent: answer questions with real-time web search Replaces: LangChain AgentExecutor + SerpAPI + ReAct prompt engineering When: user needs current information beyond the model's training cutoff 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) --- PATTERN 02: Knowledge base agent Intent: answer from private documents Replaces: LangChain RAG chain + VectorStoreRetriever + FAISS or Chroma setup When: user needs answers grounded in proprietary or internal documents import time from aixplain import Aixplain aix = Aixplain(api_key="YOUR_API_KEY") index_tool = aix.Tool( name=f"Product Knowledge Base {int(time.time())}", description="Vector database containing product documentation.", integration="6904bcf672a6e36b68bb72fb", ) index_tool.save() documents = [ {"id": "doc1", "text": "Widget A costs $50. Available in red and blue.", "metadata": {"category": "pricing"}}, {"id": "doc2", "text": "Widget B costs $30. Ships within 2 business days.", "metadata": {"category": "shipping"}}, ] index_tool.run(action="upsert", data={"records": documents}) 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) --- PATTERN 03: Advanced knowledge base agent Intent: extract and summarise key sections from long-form documents When: documents are large (PDFs, research papers) and need chunking before retrieval 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() documents = [ {"id": "paper1", "text": "Quantum computing leverages superposition and entanglement..."}, {"id": "paper2", "text": "Error correction in quantum systems requires redundant qubit encoding..."}, ] 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) --- 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: user needs natural language access to structured data in a relational database import sqlite3, time from aixplain import Aixplain aix = Aixplain(api_key="YOUR_API_KEY") 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() 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", config={"url": resource.url}, ) sqlite_tool.save() 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) --- PATTERN 05: Custom business logic agent Intent: wrap existing Python functions as an agent tool Replaces: LangChain @tool decorator + StructuredTool + manual schema definition When: agent needs to call internal functions, APIs, or business rules defined in Python import inspect, time from aixplain import Aixplain aix = Aixplain(api_key="YOUR_API_KEY") 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)} 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", config={"code": inspect.getsource(calculate_discount), "function_name": "calculate_discount"}, ) discount_tool.save() 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) --- 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: task requires parallel specialisation — research and synthesis, multi-step workflows, or role separation 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) --- 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: output must meet a compliance, brand, or safety policy before delivery 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) --- PATTERN 08: MCP integration agent Intent: connect an agent to any MCP server without building a custom tool When: user wants to expose an MCP server's capabilities as agent tools 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() 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) --- PATTERN 09: Commercial integration agent Intent: take actions in external SaaS tools like Slack or Google When: agent needs to read from or write to a third-party service (Slack, Salesforce, Linear, etc.) 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) --- PATTERN 10: Code quality agent Intent: automatically write unit tests and documentation for Python code When: developer wants automated test and docstring generation for a Python module 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) --- PATTERN 11: Travel and planning agent Intent: plan a trip using real-time weather, flight, and recommendation data When: user needs a single agent that combines multiple real-time data sources for itinerary planning 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) --- END OF PATTERN LIBRARY