Custom tools let your SecureAI assistants call external APIs, query internal databases, and perform actions beyond text generation. This guide covers how to create, configure, test, and deploy custom tool integrations in your SecureAI OpenWebUI instance.
Prerequisites
Before you begin, ensure you have:
- Admin access to your SecureAI instance.
- The external API or service you want to integrate is accessible from your SecureAI deployment (network, firewall, DNS).
- API credentials (API key, OAuth token, or service account) for the target service.
- Basic familiarity with Python -- custom tools are written as Python functions.
How Custom Tools Work
OpenWebUI tools are Python functions that the assistant can invoke during a conversation. When a user asks a question that requires external data, the assistant calls the tool, receives the result, and incorporates it into its response.
The flow works like this:
- An admin creates a tool with a Python function and a description of what it does.
- The admin assigns the tool to one or more assistants (models).
- A user asks a question that matches the tool's purpose.
- The assistant decides to call the tool based on the description and the user's query.
- The tool function executes, calls the external API, and returns data.
- The assistant uses the returned data in its response to the user.
Tools are the primary way to give assistants access to live, organization-specific data -- parts inventory, shop management systems, pricing databases, or internal knowledge bases.
Step 1: Create a New Tool
- Log in to SecureAI as an administrator.
- Navigate to Workspace > Tools in the left sidebar.
- Click + Create a New Tool.
- Fill in the tool metadata:
- Name: A short, descriptive name (e.g., "Parts Inventory Lookup").
- Description: Explain what the tool does in plain language. The assistant reads this description to decide when to use the tool, so be specific. Example: "Looks up current inventory levels and pricing for a given part number in the company parts database."
- Icon (optional): Choose an icon for visual identification.
Step 2: Write the Tool Function
The tool editor opens with a Python template. Each tool is a Python class with one or more methods that the assistant can call.
Basic Structure
class Tools:
def __init__(self):
"""Initialize the tool. Set up any configuration here."""
self.api_base_url = "https://api.example.com/v1"
def lookup_part(self, part_number: str) -> str:
"""
Look up inventory and pricing for a specific part number.
:param part_number: The OEM or aftermarket part number to search.
:return: Inventory count and current price, or an error message.
"""
import requests
try:
response = requests.get(
f"{self.api_base_url}/parts/{part_number}",
headers={"Authorization": f"Bearer {self.valves.api_key}"},
timeout=10
)
response.raise_for_status()
data = response.json()
return (
f"Part: {data['name']}\n"
f"Part Number: {data['part_number']}\n"
f"In Stock: {data['quantity']}\n"
f"Price: ${data['price']:.2f}\n"
f"Location: {data['warehouse']}"
)
except requests.exceptions.Timeout:
return "Error: The parts database did not respond in time. Try again."
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
return f"Part number {part_number} was not found in the database."
return f"Error querying parts database: {e}"
Key Rules for Tool Functions
| Rule | Details |
|---|---|
| Docstring required | Every method must have a docstring. The assistant uses it to understand when and how to call the tool. |
| Type hints required | Parameters and return types must have type annotations. The assistant uses these to format its tool calls. |
| Return a string | Tool methods should return a string. The assistant incorporates the returned text into its response. |
| Handle errors | Always catch exceptions and return a user-friendly error message. An unhandled exception breaks the conversation flow. |
| Imports inside methods | Place import statements inside the method body, not at the top of the file. This avoids import failures blocking tool registration. |
| Timeout external calls | Always set a timeout on HTTP requests. A hanging request blocks the conversation indefinitely. |
Step 3: Configure Valves (Settings)
Valves are configurable settings that admins can change without editing the tool code. Use valves for API keys, base URLs, feature flags, and other values that differ between environments.
Defining Valves
Add a Valves inner class to your tool:
from pydantic import BaseModel, Field
class Tools:
class Valves(BaseModel):
api_key: str = Field(default="", description="API key for the parts database")
api_base_url: str = Field(
default="https://api.example.com/v1",
description="Base URL of the parts API"
)
timeout_seconds: int = Field(default=10, description="Request timeout in seconds")
def __init__(self):
self.valves = self.Valves()
def lookup_part(self, part_number: str) -> str:
"""Look up inventory and pricing for a specific part number.
:param part_number: The OEM or aftermarket part number to search.
:return: Inventory count and current price.
"""
import requests
response = requests.get(
f"{self.valves.api_base_url}/parts/{part_number}",
headers={"Authorization": f"Bearer {self.valves.api_key}"},
timeout=self.valves.timeout_seconds
)
response.raise_for_status()
data = response.json()
return f"Part: {data['name']} | Stock: {data['quantity']} | Price: ${data['price']:.2f}"
Setting Valve Values
After saving the tool, configure valve values:
- In the Tools list, click the gear icon next to your tool.
- Fill in the valve fields (API key, base URL, etc.).
- Click Save.
Valve values are stored securely and are not visible to end users. They are only accessible to administrators through the tool settings panel.
Step 4: Assign the Tool to an Assistant
Tools are not available to users until assigned to a model or assistant.
- Navigate to Workspace > Models.
- Select the assistant (model) you want to equip with the tool.
- Under the Tools section, toggle on your new tool.
- Click Save.
The assistant can now call the tool during conversations. Users do not need to take any action -- the assistant decides when to invoke the tool based on the conversation context and the tool's description.
Controlling Tool Availability
- Per-model assignment: Assign tools only to assistants that need them. A general-purpose assistant may not need access to your inventory API.
- Multiple tools per assistant: An assistant can have several tools. It will choose the appropriate one based on the user's query.
- Same tool on multiple assistants: You can assign the same tool to multiple assistants.
Step 5: Test the Tool
Test your tool before making it available to users.
Manual Testing in the Tool Editor
- Open the tool in Workspace > Tools.
- Use the Test panel (if available) to call the function with sample inputs.
- Verify the output matches your expectations.
Conversation Testing
- Start a new conversation with the assistant that has the tool assigned.
- Ask a question that should trigger the tool. For a parts lookup tool, try: "What is the current inventory for part number 12345-AB678?"
- Verify that:
- The assistant calls the tool (you may see a tool call indicator in the UI).
- The response includes data from the external API, not a generic answer.
- Error cases are handled gracefully (try an invalid part number, or a number that does not exist).
Common Testing Issues
| Issue | Cause | Fix |
|---|---|---|
| Assistant does not call the tool | Tool description is too vague or does not match the user's query | Rewrite the description to be more specific about when the tool should be used |
| "Tool execution error" in response | Unhandled exception in the tool function | Check the tool logs in Admin > Logs, fix the exception, and re-save |
| Tool returns empty or unexpected data | API response format does not match what the code expects | Print or log the raw API response, then update the parsing logic |
| Timeout errors | External API is slow or unreachable | Check network connectivity from the SecureAI server; increase the timeout value in valves |
| Valve values not applied | Valves were not saved after editing | Re-open valve settings, confirm values are filled in, and click Save |
Practical Examples for Automotive Aftermarket
Parts Inventory Lookup
Connect to your warehouse or distributor API to let the assistant check real-time stock levels, pricing, and warehouse locations for specific part numbers.
VIN Decoder Integration
Integrate a VIN decoding service (such as NHTSA vPIC or a commercial VIN API) so the assistant can decode a VIN and return year, make, model, engine, and trim details without the user leaving the conversation.
Repair Procedure Lookup
Connect to your repair information provider (e.g., ALLDATA, Mitchell, Identifix) to let the assistant retrieve OEM repair procedures, torque specs, or TSBs for a specific vehicle and system.
Shop Management System Query
Build a read-only integration with your SMS (Mitchell 1, CCC ONE, Audatex) to let the assistant pull repair order status, customer history, or estimate details by RO number.
Parts Cross-Reference
Integrate a parts cross-reference database to let the assistant map between OEM and aftermarket part numbers across manufacturers (Dorman, Standard Motor Products, Denso, etc.).
Security Considerations
Custom tools execute server-side code and connect to external services. Follow these guidelines:
- Never hardcode credentials in tool code. Always use valves for API keys, tokens, and secrets.
- Use read-only API access where possible. If the integration only needs to look up data, do not grant write permissions.
- Validate inputs before passing them to external APIs. Sanitize part numbers, VINs, and other user-provided values to prevent injection attacks.
- Set timeouts on all external HTTP calls. A missing timeout can hang the conversation and consume server resources.
- Limit tool scope to what is needed. Do not create a single tool that can access everything -- split into focused tools with clear purposes.
- Review tool code before deploying. Have a second administrator review custom tool code, especially if it connects to sensitive systems.
- Monitor tool usage in the admin logs. Watch for unexpected call patterns that might indicate misuse.
Troubleshooting
Tool Does Not Appear in Assistant Settings
- Confirm the tool was saved successfully (check for syntax errors in the code).
- Refresh the page -- the tools list may be cached.
- Ensure you have admin permissions.
Tool Calls Fail Silently
- Check Admin > Logs for error messages from the tool execution.
- Verify valve values are configured (empty API key is a common cause).
- Test the external API independently (e.g., with
curl) to confirm it is reachable from the server.
Assistant Calls the Wrong Tool
- Review the descriptions of all tools assigned to the assistant. Overlapping or vague descriptions cause the model to pick the wrong one.
- Make each tool's description specific about the type of query it handles.
Rate Limiting from External APIs
- Add rate limiting logic in the tool function (e.g., track call count and return a cached result if the limit is near).
- Consider caching frequently requested data to reduce API calls.
- Monitor your API usage dashboard for the external service.
Next Steps
- Review the Shop Management System Integration article for workflow context on connecting SecureAI with SMS platforms.
- Check the Parts Ordering Platform Integration article for context on parts ordering workflows.
- Review the API keys article for managing the credentials your tools consume.