← All Articles

Embedding SecureAI in Your Applications

developer-docs beginner api embedding custom-tools automation developer integration

SecureAI is not just a standalone chat interface. Its REST API and embeddable components let you bring AI-powered chat directly into your own applications, build custom tools that extend what assistants can do, and automate repetitive workflows. This guide covers all three capabilities with practical examples for automotive aftermarket teams.

Prerequisites

Before you begin, make sure you have:

Embedding the Chat Widget

The fastest way to add SecureAI to your application is the embeddable chat widget. It drops a floating chat button into any web page, giving users access to SecureAI conversations without leaving your application.

Basic Embed

Add the following snippet to your HTML, just before the closing </body> tag:

<script>
  window.SECUREAI_CONFIG = {
    instanceUrl: "https://your-secureai-instance.com",
    apiKey: "sk-your-api-key-here",
    position: "bottom-right",
    title: "Parts Assistant"
  };
</script>
<script src="https://your-secureai-instance.com/embed/chat-widget.js"></script>

The widget renders a chat button in the specified corner. When clicked, it opens a conversation panel styled to match the SecureAI interface.

Configuration options:

Option Type Default Description
instanceUrl string required Your SecureAI instance URL
apiKey string required API key for authentication
position string "bottom-right" Widget position: "bottom-right", "bottom-left"
title string "Chat" Header text shown in the chat panel
model string instance default Model to use for conversations
assistantId string none Lock the widget to a specific assistant
theme string "auto" "light", "dark", or "auto" (follows system preference)
welcomeMessage string none Initial message shown when the chat panel opens

Locking to an Assistant

For focused use cases, pin the widget to a specific assistant. This is useful when you want the embedded chat to always use your parts lookup assistant or diagnostic assistant rather than the general-purpose chat.

<script>
  window.SECUREAI_CONFIG = {
    instanceUrl: "https://your-secureai-instance.com",
    apiKey: "sk-your-api-key-here",
    assistantId: "asst_parts_lookup_v2",
    title: "Parts Lookup",
    welcomeMessage: "Hi! I can help you find parts by OEM number, VIN, or description. What are you looking for?"
  };
</script>
<script src="https://your-secureai-instance.com/embed/chat-widget.js"></script>

Iframe Embed

If you need more control over layout, embed SecureAI as an iframe instead of using the widget:

<iframe
  src="https://your-secureai-instance.com/embed/chat?api_key=sk-your-api-key-here&assistant=asst_parts_lookup_v2"
  width="100%"
  height="600"
  style="border: 1px solid #e2e8f0; border-radius: 8px;"
  allow="clipboard-write"
></iframe>

The iframe embed supports the same configuration options as query parameters (model, assistant, theme, welcome_message).

Security Considerations for Embedding

Using the Chat API Directly

For full control over the user experience, call the chat API from your application code instead of using the embed widget.

Sending a Message

curl -X POST https://your-secureai-instance.com/api/v1/chats/new \
  -H "Authorization: Bearer sk-your-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {"role": "user", "content": "What brake pads fit a 2019 Honda Civic EX?"}
    ]
  }'

Response:

{
  "id": "chat_abc123",
  "model": "gpt-4o",
  "message": {
    "role": "assistant",
    "content": "For a 2019 Honda Civic EX, the following brake pad options are compatible:\n\n**Front brake pads:**\n- OEM: Honda 45022-TBA-A01\n- Aftermarket: Bosch BC1764, Wagner ThermoQuiet QC1764\n\n**Rear brake pads:**\n- OEM: Honda 43022-TBA-A01\n- Aftermarket: Bosch BC1336, Wagner ThermoQuiet QC1336\n\nThese fit all 2019 Civic trims (LX, EX, EX-L, Sport, Touring) with standard brakes."
  }
}

Streaming Responses

For real-time display in your application, use server-sent events (SSE) streaming:

curl -X POST https://your-secureai-instance.com/api/v1/chats/new \
  -H "Authorization: Bearer sk-your-api-key-here" \
  -H "Content-Type: application/json" \
  -H "Accept: text/event-stream" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {"role": "user", "content": "What brake pads fit a 2019 Honda Civic EX?"}
    ],
    "stream": true
  }'

Each chunk arrives as an SSE event:

data: {"delta": {"content": "For a "}}
data: {"delta": {"content": "2019 Honda "}}
data: {"delta": {"content": "Civic EX, "}}
...
data: [DONE]

Continuing a Conversation

To maintain context across multiple messages, include the conversation ID:

curl -X POST https://your-secureai-instance.com/api/v1/chats/chat_abc123 \
  -H "Authorization: Bearer sk-your-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {"role": "user", "content": "Which of those are ceramic?"}
    ]
  }'

Using an Assistant via API

To route API conversations through a specific assistant (with its system prompt, knowledge bases, and tools):

curl -X POST https://your-secureai-instance.com/api/v1/chats/new \
  -H "Authorization: Bearer sk-your-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "assistant_id": "asst_parts_lookup_v2",
    "messages": [
      {"role": "user", "content": "Cross-reference Bosch BC1764 to ACDelco"}
    ]
  }'

The assistant's model, system prompt, and attached knowledge bases are applied automatically.

Building Custom Tools

Custom tools let assistants call external APIs and perform actions beyond text generation. A tool is a Python function that SecureAI executes when the assistant determines it is needed during a conversation.

How Tools Work

  1. You define a tool as a Python class with a Valves configuration and one or more callable methods.
  2. An administrator installs the tool in SecureAI (Admin Panel > Tools).
  3. When a user asks a question that matches the tool's description, the assistant calls the tool automatically.
  4. The tool executes, returns structured data, and the assistant incorporates the result into its response.

Tool Structure

Every custom tool follows this pattern:

"""
title: Parts Inventory Lookup
description: Checks real-time parts inventory from your shop management system.
author: Your Name
version: 0.1.0
"""

from pydantic import BaseModel, Field
import requests


class Tools:
    class Valves(BaseModel):
        """Configuration values set by the administrator."""
        api_url: str = Field(
            default="https://sms.example.com/api/v1",
            description="Shop management system API URL"
        )
        api_key: str = Field(
            default="",
            description="API key for the shop management system"
        )

    def __init__(self):
        self.valves = self.Valves()

    def check_inventory(
        self,
        part_number: str,
        __user__: dict = {}
    ) -> str:
        """
        Check real-time inventory for a specific part number.

        :param part_number: The OEM or aftermarket part number to look up.
        :return: Inventory status including quantity, price, and location.
        """
        response = requests.get(
            f"{self.valves.api_url}/inventory",
            params={"part_number": part_number},
            headers={"Authorization": f"Bearer {self.valves.api_key}"},
            timeout=10
        )
        response.raise_for_status()
        data = response.json()

        if not data.get("results"):
            return f"No inventory found for part number {part_number}."

        lines = []
        for item in data["results"]:
            lines.append(
                f"- {item['part_number']}: {item['quantity']} in stock "
                f"at ${item['price']:.2f} (Location: {item['location']})"
            )
        return "\n".join(lines)

Key Concepts

Valves are administrator-configurable settings. They appear in the SecureAI admin panel when the tool is installed. Use valves for API URLs, credentials, and other settings that vary by deployment. Never hardcode secrets in tool code.

The __user__ parameter is injected automatically by SecureAI. It contains information about the user making the request (id, name, email, role). Use it for access control or audit logging.

Docstrings matter. The assistant uses the method's docstring and parameter descriptions to decide when and how to call the tool. Write clear, specific descriptions.

Return strings. Tool methods return plain text that the assistant weaves into its response. For structured data, format it as readable text or Markdown.

Installing a Tool

  1. Go to Admin Panel > Tools.
  2. Click Add Tool (the + button).
  3. Paste the tool code into the editor.
  4. Click Save.
  5. Configure the valves -- fill in the API URL, API key, and any other settings.
  6. Assign the tool to one or more assistants, or enable it globally.

Example: Cross-Reference Tool

This tool calls an external parts compatibility API to cross-reference OEM part numbers across manufacturers:

"""
title: Parts Cross-Reference
description: Cross-references OEM part numbers across aftermarket manufacturers.
author: Your Name
version: 0.1.0
"""

from pydantic import BaseModel, Field
import requests


class Tools:
    class Valves(BaseModel):
        api_url: str = Field(
            default="https://parts-api.example.com/v2",
            description="Parts data API URL"
        )
        api_key: str = Field(default="", description="Parts data API key")

    def __init__(self):
        self.valves = self.Valves()

    def cross_reference(
        self,
        part_number: str,
        target_brand: str = "",
        __user__: dict = {}
    ) -> str:
        """
        Find equivalent parts across manufacturers for a given part number.

        :param part_number: The source OEM or aftermarket part number.
        :param target_brand: Optional brand to filter results (e.g., "Bosch", "ACDelco").
        :return: List of cross-referenced part numbers with compatibility notes.
        """
        params = {"part_number": part_number}
        if target_brand:
            params["brand"] = target_brand

        response = requests.get(
            f"{self.valves.api_url}/cross-reference",
            params=params,
            headers={"Authorization": f"Bearer {self.valves.api_key}"},
            timeout=10
        )
        response.raise_for_status()
        data = response.json()

        if not data.get("matches"):
            return f"No cross-references found for {part_number}."

        lines = [f"Cross-references for {part_number}:"]
        for match in data["matches"]:
            note = f" -- {match['note']}" if match.get("note") else ""
            lines.append(f"- {match['brand']} {match['part_number']}{note}")
        return "\n".join(lines)

Testing Tools

Before deploying a tool to production:

  1. Test in the admin panel. After saving the tool, open a chat with the assigned assistant and try queries that should trigger the tool.
  2. Check the tool execution log. Go to Admin Panel > Tools > (your tool) > Logs to see invocation history, inputs, outputs, and errors.
  3. Handle errors gracefully. Wrap external API calls in try/except blocks and return user-friendly error messages. The assistant will relay whatever the tool returns.
def check_inventory(self, part_number: str, __user__: dict = {}) -> str:
    """Check real-time inventory for a specific part number."""
    try:
        response = requests.get(
            f"{self.valves.api_url}/inventory",
            params={"part_number": part_number},
            headers={"Authorization": f"Bearer {self.valves.api_key}"},
            timeout=10
        )
        response.raise_for_status()
    except requests.exceptions.Timeout:
        return "The inventory system is taking too long to respond. Please try again in a moment."
    except requests.exceptions.HTTPError as e:
        return f"Could not check inventory: the system returned an error ({e.response.status_code})."
    # ... process response

Workflow Automation via API

Beyond chat, the SecureAI API supports automating repetitive tasks -- generating reports, processing batches of parts queries, triggering actions based on conversation outcomes.

Batch Parts Lookup

Process a list of part numbers through SecureAI in a script:

import requests
import csv
import time

SECUREAI_URL = "https://your-secureai-instance.com"
API_KEY = "sk-your-api-key-here"
HEADERS = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

def lookup_part(part_number: str) -> str:
    """Send a parts query to SecureAI and return the response."""
    response = requests.post(
        f"{SECUREAI_URL}/api/v1/chats/new",
        headers=HEADERS,
        json={
            "assistant_id": "asst_parts_lookup_v2",
            "messages": [
                {"role": "user", "content": f"Find compatible replacements for {part_number}"}
            ]
        },
        timeout=60
    )
    response.raise_for_status()
    return response.json()["message"]["content"]

# Process a CSV of part numbers
with open("parts_to_lookup.csv") as infile, open("results.csv", "w", newline="") as outfile:
    reader = csv.DictReader(infile)
    writer = csv.writer(outfile)
    writer.writerow(["Part Number", "Results"])

    for row in reader:
        result = lookup_part(row["part_number"])
        writer.writerow([row["part_number"], result])
        time.sleep(1)  # Respect rate limits

Webhook-Triggered Automation

Set up a webhook endpoint that receives events from your shop management system and queries SecureAI automatically:

from flask import Flask, request, jsonify
import requests

app = Flask(__name__)

SECUREAI_URL = "https://your-secureai-instance.com"
API_KEY = "sk-your-api-key-here"

@app.route("/webhook/new-repair-order", methods=["POST"])
def handle_repair_order():
    """When a new repair order arrives, query SecureAI for parts recommendations."""
    order = request.json
    vin = order.get("vin")
    complaint = order.get("customer_complaint")

    response = requests.post(
        f"{SECUREAI_URL}/api/v1/chats/new",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json"
        },
        json={
            "assistant_id": "asst_diagnostic_v1",
            "messages": [
                {
                    "role": "user",
                    "content": (
                        f"New repair order for VIN {vin}. "
                        f"Customer complaint: {complaint}. "
                        f"What parts might be needed and what diagnostic steps should the technician start with?"
                    )
                }
            ]
        },
        timeout=60
    )
    response.raise_for_status()
    recommendation = response.json()["message"]["content"]

    return jsonify({
        "vin": vin,
        "recommendation": recommendation
    })

Scheduled Reports

Use a cron job or task scheduler to generate periodic reports with SecureAI:

import requests
import smtplib
from email.mime.text import MIMEText
from datetime import datetime

SECUREAI_URL = "https://your-secureai-instance.com"
API_KEY = "sk-your-api-key-here"

def generate_weekly_summary():
    """Ask SecureAI to summarize the week's parts trends."""
    response = requests.post(
        f"{SECUREAI_URL}/api/v1/chats/new",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json"
        },
        json={
            "assistant_id": "asst_analytics_v1",
            "messages": [
                {
                    "role": "user",
                    "content": (
                        f"Generate a weekly parts demand summary for the week ending "
                        f"{datetime.now().strftime('%Y-%m-%d')}. "
                        f"Include top requested parts, trending categories, and any "
                        f"supply concerns based on recent queries."
                    )
                }
            ]
        },
        timeout=120
    )
    response.raise_for_status()
    return response.json()["message"]["content"]

summary = generate_weekly_summary()

msg = MIMEText(summary)
msg["Subject"] = f"Weekly Parts Demand Summary - {datetime.now().strftime('%Y-%m-%d')}"
msg["From"] = "secureai@yourshop.com"
msg["To"] = "parts-team@yourshop.com"

with smtplib.SMTP("smtp.yourshop.com", 587) as server:
    server.starttls()
    server.login("secureai@yourshop.com", "email-password")
    server.send_message(msg)

Rate Limits and Best Practices

When automating API calls, keep these guidelines in mind:

Guideline Details
Respect rate limits Default: 60 requests/minute per API key. Add delays between batch requests. Check X-RateLimit-Remaining headers.
Use appropriate timeouts Set request timeouts to at least 30 seconds for chat completions. Complex queries with knowledge base searches may take longer.
Handle errors and retries Implement exponential backoff for 429 Too Many Requests and 5xx errors. Do not retry 4xx client errors without fixing the request.
Use dedicated API keys Create separate keys for each automation script. This makes it easy to revoke or rate-limit individual scripts without affecting others.
Log API usage Track request counts and response times. This helps identify scripts that are consuming disproportionate resources.
Prefer assistants over raw prompts Route automation through assistants so that system prompts, knowledge bases, and tools are applied consistently.

What's Next