aixplain SDK pattern library ============================ Minimal, complete patterns. One file. No narrative. --- PATTERN 01: Web research agent Intent: answer questions with real-time web search 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-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) --- PATTERN 02: Knowledge base agent Intent: answer from private documents When: user needs answers grounded in proprietary or internal 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) --- PATTERN 03: Advanced knowledge base agent Intent: extract and summarize key sections from long-form documents When: documents are large (PDFs, research papers) and need chunking before retrieval 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) --- PATTERN 04: SQL data agent Intent: query a database and return answers in natural language When: user needs natural language access to structured data in a relational database Note: the agent's SQL tool call can intermittently arrive without the query and fail; check result.data.steps, and fall back to sqlite_tool.run(action="query", data={"query": "SELECT ..."}) when it does. 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) --- PATTERN 05: Custom business logic agent Intent: wrap existing Python functions as an agent tool When: agent needs to call internal functions, APIs, or business rules defined in Python 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) --- PATTERN 06: Multi-agent team with role delegation Intent: coordinate multiple specialized agents to solve a complex task When: task requires parallel specialization — 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-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) --- PATTERN 07: Governed agent with runtime inspector Intent: enforce a policy on agent output before it reaches the user When: output must meet a compliance, brand, or safety policy before delivery 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) --- 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="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) --- PATTERN 09: 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.) 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) --- 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(f"Write unit tests and add a docstring for this function:\n{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 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) --- END OF PATTERN LIBRARY