Sphinx Agent Documentation
Complete developer guide for integrating AI agents into your applications
What is Sphinx Agent?
Sphinx Agent is a powerful platform that allows you to create, deploy, and manage AI-powered customer service agents. Our platform provides:
AI-Powered Conversations
Advanced language models including GPT-4o, Gemini 2.0 Flash, and DeepSeek for natural conversations
Easy Integration
Simple widget embedding, REST API, and SDKs for popular frameworks
Analytics & Insights
Detailed conversation analytics, customer satisfaction metrics, and performance tracking
Multi-channel Support
Chat, voice calls, SMS, and integrations with popular platforms
10 Agent Types
Sales, support, booking, receptionist, interview, lead capture, onboarding, FAQ, real estate, and more
Referral Program
Earn free months for every paying customer you refer. Both parties get rewarded.
Architecture Overview
Sphinx Agent is built on a modern, serverless architecture that scales automatically with your needs:
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Your Website │───▶│ Sphinx Widget │───▶│ Sphinx Agent │
│ │ │ │ │ Platform │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│
┌────────────────────────┼────────────────────────┐
│ │ │
┌───────▼────────┐ ┌─────────▼────────┐ ┌─────────▼────────┐
│ AI Providers │ │ Communication │ │ Analytics │
│ (GPT-4o, Gemini, │ │ (Voice, SMS, │ │ (Metrics, │
│ Gemini) │ │ WhatsApp) │ │ Insights) │
└────────────────┘ └──────────────────┘ └──────────────────┘
Ready to add an AI agent to your website? Start with our Quick Start Guide to have your first agent running in under 5 minutes!
Quick Start Guide
Get your AI agent running in under 5 minutes
Step 1: Create Your Agent
First, create your AI agent using our web interface:
- Go to the Sphinx Agent Dashboard
- Sign in with Google or create a free account
- Click "Create Agent" and follow the wizard
- Configure your agent's personality, knowledge base, and features
Start with 100 free conversations per month. No credit card required!
Step 2: Get Your Widget Code
After creating your agent, you'll get a unique widget code:
<!-- Sphinx Agent Widget -->
<div id="sphinx-agent-widget"></div>
<script>
window.SphinxAgentConfig = {
agentId: 'your-agent-id',
apiUrl: 'https://dgyr0dzn4k.execute-api.us-east-1.amazonaws.com/production',
position: 'bottom-right',
buttonText: 'Chat with AI',
buttonColor: '#D4AF37'
};
</script>
<script src="https://sphinxagent.ai/widget/sphinx-widget.js"></script>
Step 3: Add to Your Website
Simply paste the widget code before the closing </body> tag of your HTML:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<h1>Welcome to my website</h1>
<p>Your content here...</p>
<!-- Sphinx Agent Widget -->
<div id="sphinx-agent-widget"></div>
<script>
window.SphinxAgentConfig = {
agentId: 'your-agent-id',
apiUrl: 'https://dgyr0dzn4k.execute-api.us-east-1.amazonaws.com/production'
};
</script>
<script src="https://sphinxagent.ai/widget/sphinx-widget.js"></script>
</body>
</html>
Use the "Insert Headers and Footers" plugin or add to your theme's footer.php:
<!-- Add this before </body> in footer.php -->
<div id="sphinx-agent-widget"></div>
<script>
window.SphinxAgentConfig = {
agentId: 'your-agent-id',
apiUrl: 'https://dgyr0dzn4k.execute-api.us-east-1.amazonaws.com/production'
};
</script>
<script src="https://sphinxagent.ai/widget/sphinx-widget.js"></script>
Step 4: Test Your Agent
Once you've added the widget code:
- Refresh your website
- Look for the chat button (usually bottom-right corner)
- Click the button to start a conversation
- Test various questions to see how your agent responds
Want to customize colors, position, or behavior? Check out our Widget Customization Guide.
Next Steps
Congratulations! Your AI agent is now live. Here's what you can do next:
- Monitor conversations: Check your dashboard for analytics and insights
- Improve responses: Update your agent's knowledge base based on user questions
- Enable advanced features: Add voice calls, SMS support, or appointment booking
- Scale up: Upgrade to a paid plan for unlimited conversations
Authentication
Secure access to Sphinx Agent APIs
Overview
Sphinx Agent uses JWT (JSON Web Tokens) for API authentication. All API requests must include a valid authentication token.
Getting Your API Token
Sphinx Agent uses Google OAuth for authentication. When a user signs in, the backend returns a JWT token:
{
"credential": "google-oauth-credential-token"
}
{
"success": true,
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": "user_123",
"email": "user@example.com",
"name": "John Doe"
},
"expiresIn": "24h"
}
Using Your Token
Include your token in the Authorization header of all API requests:
Authorization: Bearer your-jwt-token-here
curl -X GET "https://dgyr0dzn4k.execute-api.us-east-1.amazonaws.com/production/agents" \ -H "Authorization: Bearer your-jwt-token-here" \ -H "Content-Type: application/json"
Token Security
- Never expose tokens in client-side code or public repositories
- Use environment variables to store tokens securely
- Implement token rotation for production applications
- Monitor token usage and revoke suspicious tokens immediately
Token Verification
Verify your token is valid before making API calls:
fetch('https://dgyr0dzn4k.execute-api.us-east-1.amazonaws.com/production/auth/verify', {
method: 'POST',
headers: {
'Authorization': 'Bearer your-token-here',
'Content-Type': 'application/json'
},
body: JSON.stringify({ token: 'your-token-here' })
})
Widget Installation
Complete guide to installing the Sphinx Agent widget
Basic Installation
The Sphinx Agent widget can be installed on any website with just a few lines of code:
<!-- Sphinx Agent Widget -->
<div id="sphinx-agent-widget"></div>
<script>
window.SphinxAgentConfig = {
agentId: 'your-agent-id-here'
};
</script>
<script src="https://sphinxagent.ai/widget/sphinx-widget.js"></script>
Platform-Specific Instructions
Method 1: Using a Plugin (Recommended)
- Install the "Insert Headers and Footers" plugin
- Go to Settings → Insert Headers and Footers
- Paste the widget code in "Scripts in Footer"
- Save changes
Theme - Method 2: Theme Editor
- Go to Appearance → Theme Editor
- Select footer.php
- Add the widget code before
</body> - Update file
1. Go to Online Store → Themes 2. Click "Actions" → "Edit Code" 3. Open layout/theme.liquid 4. Add widget code before </body> 5. Save
1. Open your project settings 2. Go to Custom Code tab 3. Add widget code to "Footer Code" 4. Publish site
import { useEffect } from 'react';
export default function MyApp({ Component, pageProps }) {
useEffect(() => {
// Configure Sphinx Agent
window.SphinxAgentConfig = {
agentId: 'your-agent-id-here'
};
// Load widget script
const script = document.createElement('script');
script.src = 'https://sphinxagent.ai/widget/sphinx-widget.js';
script.async = true;
document.head.appendChild(script);
}, []);
return <Component {...pageProps} />;
}
Configuration Options
Customize your widget behavior with these configuration options:
| Parameter | Type | Default | Description |
|---|---|---|---|
| agentId | string | required | Your unique agent identifier |
| position | string | bottom-right | Widget position: top-left, top-right, bottom-left, bottom-right |
| buttonText | string | Chat with AI | Text displayed on the chat button |
| buttonColor | string | #D4AF37 | Hex color code for the chat button |
| welcomeMessage | string | Hi! How can I help? | First message shown to users |
| autoOpen | boolean | false | Automatically open chat window on page load |
| soundNotifications | boolean | false | Play sound for new messages |
window.SphinxAgentConfig = {
agentId: 'your-agent-id-here',
position: 'bottom-left',
buttonText: 'Ask AI Assistant',
buttonColor: '#2563eb',
welcomeMessage: 'Welcome! How can I assist you today?',
chatTitle: 'Customer Support',
autoOpen: false,
soundNotifications: true,
showOnlineIndicator: true,
theme: 'light', // 'light' or 'dark'
language: 'en', // Language code
customCSS: 'https://yoursite.com/custom-widget.css'
};
REST API Overview
Complete reference for Sphinx Agent REST API
Base URL
https://dgyr0dzn4k.execute-api.us-east-1.amazonaws.com/production
A custom domain https://api.sphinxagent.ai will be available soon. For now, use the full API Gateway URL above. Your code will work with either URL once the custom domain is live.
Authentication
All API requests require authentication using JWT tokens in the Authorization header:
Authorization: Bearer your-jwt-token-here
Response Format
All API responses follow this standard format:
{
"success": true,
"data": { ... },
"message": "Operation completed successfully"
}
{
"success": false,
"error": "Error description",
"code": "ERROR_CODE",
"details": { ... }
}
Rate Limits
- Free: 100 messages/month, 1 agent
- Starter ($19/mo): 2,500 messages/month, 5 agents
- Pro ($49/mo): 10,000 messages/month, 25 agents, voice enabled
- Business ($99/mo): 50,000 messages/month, 50 agents, white-label
- Enterprise ($249/mo): 250,000 messages/month, unlimited agents
- Enterprise Plus ($499/mo): 1,000,000 messages/month, unlimited everything, SLA
API Endpoints
Health check endpoint
Authenticate with Google OAuth
List all agents
Create a new agent
Get specific agent details
Send chat message to agent (public — no auth required)
List conversations for your agents
List captured leads
Provision a phone number for voice agent (Pro+ plans)
Create Stripe checkout session
Get Stripe billing portal URL
Stripe webhook endpoint (Stripe → server only)
Error Codes
| Code | Status | Description |
|---|---|---|
| INVALID_TOKEN | 401 | Authentication token is invalid or expired |
| AGENT_NOT_FOUND | 404 | Specified agent ID does not exist |
| RATE_LIMIT_EXCEEDED | 429 | API rate limit exceeded |
| VALIDATION_ERROR | 400 | Request validation failed |
| INTERNAL_ERROR | 500 | Internal server error |
JavaScript Integration
Embed and interact with Sphinx Agent using vanilla JavaScript
Widget Embed (Easiest)
Add one script tag before </body> — that's it:
<script src="https://sphinxagent.ai/widget/sphinx-widget.js" data-agent-id="YOUR_AGENT_ID" data-color="#D4AF37" data-greeting="Hi! How can I help you today?"></script>
| Attribute | Type | Required | Description |
|---|---|---|---|
| data-agent-id | string | Yes | Your agent's unique ID (from dashboard) |
| data-color | string | No | Hex color for the widget button (default: #D4AF37) |
| data-greeting | string | No | First message shown when chat opens |
| data-position | string | No | Widget position: bottom-right (default), bottom-left |
REST API (Direct Calls)
For custom integrations, call the API directly with fetch:
const API = 'https://dgyr0dzn4k.execute-api.us-east-1.amazonaws.com/production';
const response = await fetch(`${API}/widget/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
agentId: 'YOUR_AGENT_ID',
message: 'Hello, I need help with my order',
conversationId: null // null for new conversation, or pass existing ID
})
});
const data = await response.json();
// data.response = "Hi! I'd be happy to help with your order..."
// data.conversationId = "conv_abc123" (use this for follow-up messages)
const API = 'https://dgyr0dzn4k.execute-api.us-east-1.amazonaws.com/production';
const token = 'your-jwt-token'; // From Google OAuth login
// List your agents
const agents = await fetch(`${API}/agents`, {
headers: { 'Authorization': `Bearer ${token}` }
}).then(r => r.json());
// Create a new agent
const newAgent = await fetch(`${API}/agents`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Sales Bot',
type: 'sales',
businessName: 'My Company',
businessInfo: 'We sell widgets...',
greeting: 'Hi! Looking for pricing or a demo?'
})
}).then(r => r.json());
The widget embed is best for websites — it handles UI, chat history, voice, and TTS automatically. Use the REST API directly when building custom chat UIs, mobile apps, or server-side integrations.
React / Next.js
Add Sphinx Agent to React and Next.js applications
React Component
import { useEffect, useRef } from 'react';
function SphinxWidget({ agentId, color = '#D4AF37', greeting }) {
const loaded = useRef(false);
useEffect(() => {
if (loaded.current) return;
loaded.current = true;
const script = document.createElement('script');
script.src = 'https://sphinxagent.ai/widget/sphinx-widget.js';
script.setAttribute('data-agent-id', agentId);
script.setAttribute('data-color', color);
if (greeting) script.setAttribute('data-greeting', greeting);
script.async = true;
document.body.appendChild(script);
return () => {
if (document.body.contains(script)) document.body.removeChild(script);
};
}, [agentId, color, greeting]);
return null; // Widget injects its own DOM
}
// Usage
export default function App() {
return (
<div>
<h1>My App</h1>
<SphinxWidget agentId="YOUR_AGENT_ID" greeting="Hi! How can I help?" />
</div>
);
}
Next.js (App Router)
'use client';
import { useEffect, useRef } from 'react';
export function SphinxWidget({ agentId }) {
const loaded = useRef(false);
useEffect(() => {
if (loaded.current) return;
loaded.current = true;
const script = document.createElement('script');
script.src = 'https://sphinxagent.ai/widget/sphinx-widget.js';
script.setAttribute('data-agent-id', agentId);
script.setAttribute('data-color', '#D4AF37');
script.async = true;
document.body.appendChild(script);
}, [agentId]);
return null;
}
// In your layout.tsx or page.tsx:
// <SphinxWidget agentId="YOUR_AGENT_ID" />
Custom Chat UI with React
Build your own chat interface using the REST API:
import { useState } from 'react';
const API = 'https://dgyr0dzn4k.execute-api.us-east-1.amazonaws.com/production';
function CustomChat({ agentId }) {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState('');
const [convId, setConvId] = useState(null);
const [loading, setLoading] = useState(false);
async function sendMessage(e) {
e.preventDefault();
if (!input.trim() || loading) return;
const userMsg = input.trim();
setInput('');
setMessages(prev => [...prev, { role: 'user', text: userMsg }]);
setLoading(true);
try {
const res = await fetch(`${API}/widget/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
agentId,
message: userMsg,
conversationId: convId
})
});
const data = await res.json();
setConvId(data.conversationId);
setMessages(prev => [...prev, { role: 'bot', text: data.response }]);
} catch {
setMessages(prev => [...prev, { role: 'bot', text: 'Connection error.' }]);
}
setLoading(false);
}
return (
<div>
{messages.map((m, i) => (
<div key={i} className={m.role}>{m.text}</div>
))}
<form onSubmit={sendMessage}>
<input value={input} onChange={e => setInput(e.target.value)} placeholder="Type a message..." />
<button disabled={loading}>Send</button>
</form>
</div>
);
}
Node.js (Server-Side)
Integrate Sphinx Agent into your Node.js backend
Sphinx Agent uses a simple REST API. No SDK installation needed — just use fetch (Node 18+) or any HTTP client.
Send Messages from Your Server
const API = 'https://dgyr0dzn4k.execute-api.us-east-1.amazonaws.com/production';
// Chat with an agent (no auth required for widget/chat)
async function chatWithAgent(agentId, message, conversationId = null) {
const res = await fetch(`${API}/widget/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ agentId, message, conversationId })
});
if (!res.ok) throw new Error(`API error: ${res.status}`);
return res.json();
}
// Usage
const reply = await chatWithAgent('YOUR_AGENT_ID', 'What are your hours?');
console.log(reply.response);
// "We're open Monday-Friday, 9am-5pm EST!"
Express.js Proxy Example
Proxy widget chat through your own backend:
const express = require('express');
const app = express();
app.use(express.json());
const API = 'https://dgyr0dzn4k.execute-api.us-east-1.amazonaws.com/production';
const AGENT_ID = 'YOUR_AGENT_ID';
app.post('/api/chat', async (req, res) => {
try {
const response = await fetch(`${API}/widget/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
agentId: AGENT_ID,
message: req.body.message,
conversationId: req.body.conversationId || null
})
});
const data = await response.json();
res.json(data);
} catch (err) {
res.status(500).json({ error: 'Chat service unavailable' });
}
});
app.listen(3000);
Python (Server-Side)
Integrate Sphinx Agent into Python applications
Use the requests library or any HTTP client. No special SDK needed.
Basic Integration
import requests
API = "https://dgyr0dzn4k.execute-api.us-east-1.amazonaws.com/production"
AGENT_ID = "YOUR_AGENT_ID"
def chat(message, conversation_id=None):
response = requests.post(f"{API}/widget/chat", json={
"agentId": AGENT_ID,
"message": message,
"conversationId": conversation_id
})
response.raise_for_status()
return response.json()
# Start a conversation
reply = chat("What services do you offer?")
print(reply["response"])
# Continue the conversation
follow_up = chat("How much does it cost?", reply["conversationId"])
print(follow_up["response"])
Flask Integration
from flask import Flask, request, jsonify
import requests
app = Flask(__name__)
API = "https://dgyr0dzn4k.execute-api.us-east-1.amazonaws.com/production"
@app.route("/chat", methods=["POST"])
def proxy_chat():
data = request.json
resp = requests.post(f"{API}/widget/chat", json={
"agentId": data["agentId"],
"message": data["message"],
"conversationId": data.get("conversationId")
})
return jsonify(resp.json())
if __name__ == "__main__":
app.run(port=5000)
Django Integration
# views.py
import json, requests
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
API = "https://dgyr0dzn4k.execute-api.us-east-1.amazonaws.com/production"
@csrf_exempt
def chat_view(request):
if request.method != "POST":
return JsonResponse({"error": "POST required"}, status=405)
body = json.loads(request.body)
resp = requests.post(f"{API}/widget/chat", json={
"agentId": body["agentId"],
"message": body["message"],
"conversationId": body.get("conversationId")
})
return JsonResponse(resp.json())
Agent Types
10 pre-configured agent personas for different business needs
When creating an agent via the Agent Wizard or API, choose a type that matches your use case. Each type comes with a tailored default greeting and system prompt.
💰 Sales Agent
Qualify leads, answer pricing questions, book demos. Ideal for SaaS, e-commerce, and B2B.
🛠 Support Agent
Troubleshoot issues, guide users through steps, resolve problems. For tech support and helpdesks.
🤝 Customer Service
General inquiries, order status, account help, returns. The all-purpose frontline agent.
💼 Interview Agent
Screen candidates with structured interviews. For HR, recruiting, and staffing firms. (Enterprise Plus)
📅 Booking Agent
Schedule appointments, consultations, and meetings. For healthcare, salons, consulting.
🙋 Receptionist
Greet visitors, route inquiries, take messages. Your 24/7 virtual front desk.
🎯 Lead Capture
Engage visitors, collect contact info, qualify leads. For marketing and growth teams.
🎓 Onboarding
Guide new hires through policies, tools, and setup. For HR and internal ops.
❓ FAQ Agent
Answer common questions from your knowledge base. For any business with repeat inquiries.
🏠 Real Estate
Property inquiries, schedule showings, buyer qualification. For agents and brokerages.
Supported Industries
The wizard includes pre-configured contexts for 16 industries:
E-commerce/Retail, SaaS/Technology, Healthcare/Medical, Real Estate, Education/Training, Finance/Insurance, Restaurant/Food, Legal/Law Firm, Travel/Hospitality, Automotive/Dealership, Construction/Trades, Recruiting/Staffing, Marketing/Agency, Nonprofit/Charity, Fitness/Wellness, Beauty/Salon/Spa
Agents API
Create, read, update, and delete agents programmatically
List Agents
curl -X GET "https://dgyr0dzn4k.execute-api.us-east-1.amazonaws.com/production/agents" \ -H "Authorization: Bearer YOUR_JWT_TOKEN"
Create Agent
{
"name": "Sales Bot",
"type": "sales",
"businessName": "Acme Inc",
"businessInfo": "We sell premium widgets for enterprise customers.",
"greeting": "Hi! Looking for pricing or a demo?",
"model": "deepseek-chat",
"industry": "SaaS"
}
| Field | Type | Required | Description |
|---|---|---|---|
| name | string | Yes | Agent display name |
| type | string | Yes | One of: sales, support, customer-service, interview, booking, receptionist, lead-capture, onboarding, faq, real-estate |
| businessName | string | No | Your business name (used in greetings) |
| businessInfo | string | No | Description of your business (max 2000 chars) |
| greeting | string | No | Custom greeting (defaults based on type) |
| model | string | No | AI model: deepseek-chat (free), gpt-4o-mini (Starter+), gpt-4o (Pro+) |
Update Agent
Same body as Create. Only include fields you want to change.
Delete Agent
Chat API
Send messages to agents and get AI responses
Send Message
The widget/chat endpoint is public — it's designed for end-user chat widgets embedded on your website. Rate limits are enforced per agent.
// Request
{
"agentId": "d264272d-1366-4b2a-8436-8cd7f6200fa6",
"message": "What are your business hours?",
"conversationId": null // null = new conversation
}
// Response
{
"response": "We're open Monday through Friday, 9am to 5pm EST.",
"conversationId": "conv_abc123def456"
}
Pass the returned conversationId in subsequent messages to maintain context:
{
"agentId": "d264272d-1366-4b2a-8436-8cd7f6200fa6",
"message": "Do you have weekend hours?",
"conversationId": "conv_abc123def456"
}
Voice API
Phone call agents powered by Vapi
Voice features require Pro plan or higher. Phone number provisioning is available on Pro (1 number), Business (5), Enterprise (10), and Enterprise Plus (unlimited).
How Voice Works
- Create an agent with voice enabled in the Agent Wizard
- Choose a voice persona (Kira, Sarah, Josh for English; Valentina, Sofía, Horacio for Spanish)
- Provision a phone number via dashboard or API
- Customers call the number and talk to your AI agent in real time
Provision Phone Number
// Requires auth + Pro plan or higher
{
"agentId": "YOUR_AGENT_ID"
}
// Response
{
"phoneNumber": "+12548529961",
"status": "active"
}
Browser-Based Voice
The widget includes built-in speech recognition and text-to-speech. Users can click the microphone icon to speak, and hear bot responses read aloud. This works on all plans (including Free) via the Web Speech API — no phone number needed.
Webhooks
Receive real-time notifications for events
Stripe Webhooks
Sphinx Agent uses Stripe webhooks to handle subscription lifecycle events. These are processed automatically — you don't need to configure them unless you're building a custom integration.
Events Handled
| Event | Action |
|---|---|
| checkout.session.completed | New subscription created, user upgraded, referral metadata stored |
| invoice.payment_succeeded | Payment processed, referral credits triggered (after threshold) |
| customer.subscription.updated | Plan change (upgrade/downgrade) applied |
| customer.subscription.deleted | Subscription cancelled, user moved to Free tier |
Lead Capture Webhook
When a visitor provides their email or phone number during a chat, a lead is automatically captured and available via the GET /leads endpoint.
Referral Program
Earn free months by referring customers
How It Works
- Each user gets a unique referral link:
https://sphinxagent.ai/?ref=YOUR_CODE - When a referred user signs up and subscribes, both parties get rewarded
- Monthly plans: Both get 1 free month (referrer credit after 2nd payment)
- Yearly plans: Both get 2 free months (referrer credit after 1st payment)
Referral Link Format
https://sphinxagent.ai/?ref=abc123def456
The ref parameter is captured in localStorage, passed through Google OAuth signup, stored in DynamoDB, and included in Stripe checkout metadata. Credits are applied as dollar amounts to the referrer's Stripe balance.
Full details: Referral Program Page
Code Examples
Practical examples to get you started quickly
Basic Widget Integration
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<h1>Welcome to My Site</h1>
<!-- Sphinx Agent Widget -->
<script>
window.SphinxAgentConfig = {
agentId: 'agent_123456789'
};
</script>
<script src="https://sphinxagent.ai/widget/sphinx-widget.js"></script>
</body>
</html>
<script>
window.SphinxAgentConfig = {
agentId: 'agent_123456789',
position: 'bottom-left',
buttonText: 'Need Help?',
buttonColor: '#2563eb',
welcomeMessage: 'Hi! I\'m your AI assistant. How can I help?',
chatTitle: 'Customer Support',
theme: 'light',
autoOpen: false,
soundNotifications: true
};
</script>
<script src="https://sphinxagent.ai/widget/sphinx-widget.js"></script>
React Integration
import React, { useEffect } from 'react';
function App() {
useEffect(() => {
// Configure Sphinx Agent
window.SphinxAgentConfig = {
agentId: 'agent_123456789',
position: 'bottom-right',
buttonText: 'Chat with AI',
theme: 'light'
};
// Load widget script
const script = document.createElement('script');
script.src = 'https://sphinxagent.ai/widget/sphinx-widget.js';
script.async = true;
document.body.appendChild(script);
// Cleanup function
return () => {
document.body.removeChild(script);
};
}, []);
return (
<div className="App">
<h1>My React App</h1>
<p>The Sphinx Agent widget will appear here!</p>
</div>
);
}
export default App;
import React, { useEffect, useState } from 'react';
const SphinxAgentWidget = ({ agentId, config = {} }) => {
const [isLoaded, setIsLoaded] = useState(false);
useEffect(() => {
// Set configuration
window.SphinxAgentConfig = {
agentId,
...config
};
// Load script
const script = document.createElement('script');
script.src = 'https://sphinxagent.ai/widget/sphinx-widget.js';
script.async = true;
script.onload = () => setIsLoaded(true);
document.head.appendChild(script);
return () => {
if (document.head.contains(script)) {
document.head.removeChild(script);
}
};
}, [agentId, config]);
return (
<div id="sphinx-agent-widget">
{!isLoaded && <div>Loading AI assistant...</div>}
</div>
);
};
// Usage
function MyApp() {
return (
<div>
<h1>My App</h1>
<SphinxAgentWidget
agentId="agent_123456789"
config={{
position: 'bottom-right',
buttonText: 'AI Support',
theme: 'dark'
}}
/>
</div>
);
}
Vue.js Integration
<template>
<div id="app">
<h1>My Vue App</h1>
<div id="sphinx-agent-widget"></div>
</div>
</template>
<script>
export default {
name: 'App',
mounted() {
// Configure Sphinx Agent
window.SphinxAgentConfig = {
agentId: 'agent_123456789',
position: 'bottom-right',
buttonText: 'Chat Support',
theme: 'light'
};
// Load widget script
const script = document.createElement('script');
script.src = 'https://sphinxagent.ai/widget/sphinx-widget.js';
script.async = true;
document.head.appendChild(script);
},
beforeDestroy() {
// Clean up if needed
if (window.SphinxAgent) {
window.SphinxAgent.destroy();
}
}
}
</script>
Advanced Customization
<script>
window.SphinxAgentConfig = {
agentId: 'agent_123456789',
position: 'bottom-right',
// Event callbacks
onWidgetReady: function() {
console.log('Sphinx Agent widget is ready!');
// Track widget load event
gtag('event', 'widget_loaded', {
'agent_id': 'agent_123456789'
});
},
onChatOpen: function() {
console.log('Chat window opened');
// Track chat open event
gtag('event', 'chat_opened', {
'agent_id': 'agent_123456789'
});
},
onChatClose: function() {
console.log('Chat window closed');
},
onMessageSent: function(message) {
console.log('User sent message:', message);
// Track user engagement
gtag('event', 'user_message', {
'message_length': message.length
});
},
onMessageReceived: function(message) {
console.log('Agent responded:', message);
},
onError: function(error) {
console.error('Sphinx Agent error:', error);
// Report errors to your monitoring service
Sentry.captureException(error);
}
};
</script>
<script>
// Only load the widget for certain pages or conditions
function shouldLoadWidget() {
// Don't show on mobile devices
if (window.innerWidth < 768) return false;
// Only show on specific pages
const allowedPages = ['/support', '/contact', '/pricing'];
if (!allowedPages.some(page => window.location.pathname.includes(page))) {
return false;
}
// Don't show for returning visitors who already interacted
if (localStorage.getItem('sphinx_agent_interacted')) {
return false;
}
return true;
}
if (shouldLoadWidget()) {
window.SphinxAgentConfig = {
agentId: 'agent_123456789',
position: 'bottom-right',
// Auto-open after 30 seconds if user hasn't scrolled much
autoOpen: window.scrollY < 100,
onChatClose: function() {
// Remember that user interacted
localStorage.setItem('sphinx_agent_interacted', 'true');
}
};
// Load script after 3 seconds to avoid blocking page load
setTimeout(() => {
const script = document.createElement('script');
script.src = 'https://sphinxagent.ai/widget/sphinx-widget.js';
script.async = true;
document.head.appendChild(script);
}, 3000);
}
</script>
E-commerce Integration
<script>
// Pass shopping cart context to the agent
function getShoppingContext() {
return {
cartItems: getCartItems(), // Your cart function
cartTotal: getCartTotal(), // Your total function
currentProduct: getCurrentProduct(), // Current product page
customerId: getCustomerId(), // Logged in user
previousOrders: getPreviousOrders() // Order history
};
}
window.SphinxAgentConfig = {
agentId: 'ecommerce_agent_123',
position: 'bottom-right',
buttonText: 'Shopping Assistant',
// Pass context with every message
contextProvider: getShoppingContext,
// Custom welcome based on cart status
welcomeMessage: function() {
const cartItems = getCartItems();
if (cartItems.length > 0) {
return `Hi! I see you have ${cartItems.length} items in your cart. Need help with checkout?`;
}
return "Hi! I'm here to help you find what you're looking for!";
},
onMessageSent: function(message) {
// Track customer inquiries
analytics.track('Customer Inquiry', {
message: message,
cart_value: getCartTotal(),
page: window.location.pathname
});
}
};
</script>