Skip to main content

Overview

This guide covers everything you need to integrate LoopOS AI services into your application. LoopOS AI services are designed to be self-contained and easy to integrate.

Base URL

Choose the appropriate environment:
https://loopos-ai-server-3recw.ondigitalocean.app

Authentication

Currently, LoopOS AI services don’t require authentication for public endpoints. However, you should:
  • Use HTTPS: All requests must use HTTPS
  • Validate responses: Always validate response structure
  • Handle errors: Implement proper error handling
Authentication may be added in the future. Check for updates in the documentation.

Request Pattern

All services follow a consistent request pattern:
import requests

BASE_URL = "https://loopos-ai-server-3recw.ondigitalocean.app"

def call_service(endpoint, payload):
    url = f"{BASE_URL}{endpoint}"
    response = requests.post(url, json=payload, timeout=120)
    response.raise_for_status()
    return response.json()

# Example: Decision service
result = call_service("/loopos_ai_decision", {
    "language": "PT-PT",
    "prompt": "What condition?",
    "options": ["Excellent", "Good", "Fair", "Poor"],
    "item_context": "iPhone 12 with scratches"
})

Common Request Fields

Most services accept these common fields:
FieldTypeDescriptionDefault
languagestringLanguage code (e.g., “PT-PT”, “en-US”)“PT-PT”
conversationbooleanWhether this is conversationalfalse
callback_urlstringAsync callback URLnull
loopos_core_contextstringBusiness contextnull
messagesarrayConversation messages[]
imagesarrayImage URLs or base64[]
agent_specificobjectService-specific paramsnull
session_extra_dataobjectSession metadata

Error Handling

Implement robust error handling:
import requests
from requests.exceptions import RequestException, Timeout

def call_service_safe(endpoint, payload, max_retries=3):
    for attempt in range(max_retries):
        try:
            response = requests.post(
                f"{BASE_URL}{endpoint}",
                json=payload,
                timeout=120
            )
            response.raise_for_status()
            return response.json()
        except Timeout:
            if attempt == max_retries - 1:
                raise
            time.sleep(2 ** attempt)  # Exponential backoff
        except requests.HTTPError as e:
            if e.response.status_code == 422:
                # Validation error - don't retry
                error_data = e.response.json()
                raise ValueError(f"Validation error: {error_data}")
            elif e.response.status_code >= 500:
                # Server error - retry
                if attempt < max_retries - 1:
                    time.sleep(2 ** attempt)
                    continue
            raise
        except RequestException as e:
            if attempt == max_retries - 1:
                raise
            time.sleep(2 ** attempt)
    raise Exception("Max retries exceeded")

Session Management

For conversational services, maintain session state:
class LoopOSAIClient:
    def __init__(self, base_url, session_id=None):
        self.base_url = base_url
        self.session_id = session_id or self._generate_session_id()
    
    def _generate_session_id(self):
        import uuid
        return str(uuid.uuid4())
    
    def chat(self, message, images=None):
        payload = {
            "language": "PT-PT",
            "messages": [{"role": "user", "text": message}],
            "images": images or [],
            "conversation": True,
            "session_id": self.session_id
        }
        return self._call_service("/chat", payload)

Image Handling

Handle images in requests:
import base64
from pathlib import Path

def image_to_base64(image_path):
    with open(image_path, "rb") as image_file:
        return f"data:image/jpeg;base64,{base64.b64encode(image_file.read()).decode()}"

# Use in request
payload = {
    "images": [
        image_to_base64("photo.jpg"),
        "https://example.com/image.jpg"  # Or use URL
    ]
}

Best Practices

Set timeouts: Always set appropriate timeouts (120 seconds recommended).
Implement retries: Retry on server errors (5xx) with exponential backoff.
Validate responses: Always validate response structure before using data.
Handle rate limits: Implement rate limiting on client side if needed.
Monitor costs: Track token usage and costs for optimization.
Use async processing: For long-running operations, consider async callbacks.

Integration Examples

Example 1: Simple Decision

result = call_service("/loopos_ai_decision", {
    "language": "PT-PT",
    "prompt": "What condition?",
    "options": ["Excellent", "Good", "Fair", "Poor"],
    "item_context": "iPhone 12 with scratches"
})
print(f"Decision: {result['decision']}")
print(f"Reasoning: {result['reasoning']}")

Example 2: Conversational Submission

client = LoopOSAIClient(BASE_URL)

# First message
response = client.chat("Quero vender um iPhone 12")
print(response[0]["text"])

# Continue conversation
response = client.chat("Apple")
print(response[0]["text"])

Example 3: C2C Descriptor with Images

payload = {
    "language": "PT-PT",
    "images": [image_to_base64("item.jpg")],
    "agent_specific": {
        "category_name": "Electronics",
        "product_name": "iPhone 12 Pro",
        "brand_name": "Apple",
        "user_description": "iPhone em excelente estado"
    }
}

result = call_service("/loopos_ai_c2c_descriptor", payload)
print(f"Title: {result['marketplace_posting_title']}")
print(f"Price: €{result['value_out_average']}")