This document will help you create, deploy, and integrate AI agents seamlessly on our platform. Whether you’re building an API, chatbot, or website-based AI, this guide will walk you through the essential steps.

Here are few samples to understand & use

πŸ”„ Interface & Routes

Design your agent’s interface routes following these guidelines:

  1. Main Interface

    • Create a single unified interface at ”/” for all user interactions
    • Keep the interface clean and intuitive
    • Put clear instructions on how to use the agent
    • Use a framework like FastAPI, Flask, or Node.js for building the interface
    • Ensure the interface is responsive and user-friendly
    • Need to use windows.href (javascript ) then add /your path name
  2. API routes

    • Define routes for API interactions
    • Use RESTful principles for API design
    • Example routes:
      • /run - for executing agent logic
      • /process - for processing user input
      • /status - for checking agent status
      • /uploads - for uploading files
      • /docs - for API & Route documentation
    • Use appropriate HTTP methods (GET, POST, PUT, DELETE) for each route
    • Use JSON for data exchange
    • Use appropriate HTTP status codes for responses
    • Use appropriate HTTP headers for authentication and content type
    • Please keep all your routes in one main file ( main.py or app.py )
    • For client-side navigation, utilize window.location.href followed by your desired route path
    • include User-Token in the request headers for all API calls to the agent
    // Function to change the URL to fit the agent's path
    
    const url = window.location.href.replace(/\/+$/, "") + "/data";
    fetch(url, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((response) => response.json())
      .then((data) => {
        console.log("Success:", data);
        // Handle success response
      })
      .catch((error) => {
        console.error("Error:", error);
        // Handle error response
      });
  3. Documentation

    • All routes and endpoints must be documented at β€œ/docs”
    • Use built-in documentation tools:
      • FastAPI: Built-in Swagger UI
      • Flask: Flask-RESTPlus or Flask-Swagger
      • Node.js: Swagger UI Express or similar

πŸ“‚ Folder Structure

To keep things organized, structure your project like this:

/my-agent
│── Dockerfile
│── requirements.txt (for Python projects)
β”œβ”€β”€ main.py (entry point)
│── src/
β”‚   β”œβ”€β”€ utils.py
β”‚   β”œβ”€β”€ handlers/
│── logs/
β”‚   β”œβ”€β”€ agent.log
│── instead of .env -> use Secret Manager
  • Zip the project folder (e.g. /my-agent ) into a .zip file. Ensure that the Dockerfile and all necessary files are included in the root folder within the zip.
  • Check the size of the zip file to ensure it is within the upload limits set by OptimalAgents.ai (typically 100MB).
  • Make sure to remove unnecessary files or folders (like .git or node_modules or virtual env folders) to keep the upload size minimal.
  • If your project exceeds this limit, consider optimizing or splitting it into smaller components.

🌐 Routes & API Endpoints

Your agent can expose API endpoints for users to interact with. Example setup in Flask:

from flask import Flask, request, jsonify
app = Flask(**name**)

def check_agent_run():
  url = "https://optimalagents.ai/check-user-credits"
  agent_id = os.getenv("AGENT_ID")
  api_key = os.getenv("CREATOR_API_KEY")
  user_id = os.getenv("USER_ID")
  data = {"api_key": api_key, "agent_id": agent_id, "user_id": user_id}
  response = requests.post(url, json=data)
  result = response.json()

    if result.get("status") == "allowed":
        print("Agent execution permitted.")
    else:
        print(f"Error: {result.get('message')}")


@app.route("/")
def home():
  return "Welcome to the AI Agent!"

@app.route("/docs")
def docs():
  return "API Documentation: /process"

@app.route("/run", methods=["POST"])
def run():
  ##check for user authorization and credit verification
  resp = check_agent_run()
  if resp.get("status") == "allowed":
      authorized = True
      enough_credits = True
  else:
      authorized = False
      enough_credits = False
  if not authorized or not enough_credits:
      return jsonify({"error": "Unauthorized or insufficient credits"}), 403
  data = request.json
  response = {"result": "Processed " + str(data)}
  return jsonify(response)

if **name** == "**main**":
    app.run(host='0.0.0.0', port=8000)

Ensure your routes are well-documented and secured.

πŸ”‘ Env Variables (Secrets)

Secrets are environment variables required by your agent to function which will be passed to the Docker container when the agent runs. Store them securely in your profile’s Secret manager. These variables will be securely managed by OptimalAgents.ai and injected into the agent’s docker runtime environment.

Please generate your CREATOR_API_KEY. This will be required to run any Agent that you have uploaded

By default, we will including AGENT_ID, CREATOR_API_KEY, Secrets as environment variables.

For testing purposes, Creator need to use their own versions of API KEYs and Secrets.

User Secrets Keys & API KEYs or OptimalAgent.ai API KEYS will be accessible to the agent only after the agent is verified & available in marketplace.

Examples include:

API_KEY=your_api_key
DB_URL=your_database_url
MODEL_NAME=gpt-4

Never hardcode secrets! Load them in your app like this:

import os
api_key = os.getenv("CREATOR_API_KEY")

πŸ” Credit Check & Authorization

Before running, agents must verify user credits via the OptimalAgents API.

βœ… Credit Check API

Make a request before executing agent logic:

POST https://optimalagents.ai/check-user-credits
Content-Type: application/json

{
  "api_key": "<CREATOR_API_KEY>",
  "agent_id": "<AGENT_ID>",
  "user_id": "<USER_ID>"
}

Handling Responses

Response Examples Success Response

{
"status": "allowed",
"message": "Agent execution permitted."
}

Error Response (Not Enough Credits)

"status": "error",
"message": "Not enough credits to run the agent."
}

Error Response (Unauthorized Agent)

{
"status": "error",
"message": "Agent not allowed for this user."
}

🐳 Docker Containerization

All agents run inside Docker containers. Your Dockerfile should look like this:

FROM python:3.11-slim
WORKDIR /app
COPY . /app
RUN pip install -r requirements.txt
CMD ["python", "src/main.py"]

Steps to Build, Run & Test in Local

Build the container:

docker build -t my-agent .

Run the container:

docker run -p 5000:5000 my-agent

A Docker image will be automatically generated upon initial deployment and regenerated following any edits to the codebase.

For file uploads, kindly direct your bytes to the β€˜/app/uploads’ directory - it’s where the magic happens! OptimalAgents has cleverly bound a persistent storage space to this location, ensuring your uploads don’t pull a disappearing act.

πŸ—‚οΈ CORS Configuration

To enable Cross-Origin Resource Sharing (CORS) for all origins and ports in your server-side application, configure your middleware with appropriate security settings.

# from fastapi.middleware.cors import CORSMiddleware
# from fastapi import FastAPI
# app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

πŸ“œ Logging & Monitoring

Use logging for debugging and tracking agent performance.

import logging
logging.basicConfig(level=logging.INFO, filename='logs/agent.log')
logging.info("Agent started successfully!")

Always log errors and API failures for troubleshooting!

Congratulations! πŸŽ‰ You now have everything needed to create and deploy AI agents on OptimalAgents.ai. If you need help, reach out to our support team or explore our community forums! πŸš€