API Use Cases
The NeuralTalk AI API enables a wide range of applications and integrations. This guide explores common use cases and provides examples to help you get started with implementing your own solutions.
Customer Support Automation
Overview
Integrate the NeuralTalk AI API into your customer support system to provide immediate responses to common questions, freeing up your support team to focus on more complex issues.
Implementation Example
// Webhook handler for incoming customer support tickets
app.post('/support-ticket', async (req, res) => {
const { message, customerId, ticketId } = req.body;
try {
// Create a conversation with the AI
const conversationResponse = await axios.post(
'https://api.neuraltalk.ai/v1/conversations',
{
chatbot_id: process.env.SUPPORT_BOT_ID,
user_id: customerId,
metadata: { ticketId }
},
{
headers: { Authorization: `Bearer ${process.env.API_KEY}` }
}
);
const conversationId = conversationResponse.data.data.conversation_id;
// Send the customer's question to the AI
const messageResponse = await axios.post(
`https://api.neuraltalk.ai/v1/conversations/${conversationId}/messages`,
{
text: message,
user_id: customerId
},
{
headers: { Authorization: `Bearer ${process.env.API_KEY}` }
}
);
const aiResponse = messageResponse.data.data.text;
const confidence = messageResponse.data.data.confidence || 0;
// If the AI is confident in its answer, send it to the customer
// Otherwise, route to a human agent
if (confidence > 0.8) {
await sendResponseToCustomer(customerId, aiResponse, ticketId);
await updateTicketStatus(ticketId, 'resolved_by_ai');
} else {
await routeTicketToAgent(ticketId, {
originalMessage: message,
aiSuggestion: aiResponse,
confidence
});
}
res.status(200).json({ success: true });
} catch (error) {
console.error('Error processing support ticket:', error);
await routeTicketToAgent(ticketId, { originalMessage: message });
res.status(500).json({ success: false, error: 'Failed to process ticket' });
}
});
Lead Generation Chatbot
Overview
Create a chatbot that engages website visitors, qualifies leads, and collects contact information for your sales team.
Implementation Example
// React component for a lead generation chatbot
function LeadChatbot() {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState('');
const [conversationId, setConversationId] = useState(null);
const [userId] = useState(`visitor_${Date.now()}`);
useEffect(() => {
// Create a new conversation when the component mounts
async function initializeConversation() {
try {
const response = await axios.post(
'https://api.neuraltalk.ai/v1/conversations',
{
chatbot_id: process.env.LEAD_BOT_ID,
user_id: userId,
metadata: { source: 'website', page: window.location.pathname }
},
{
headers: { Authorization: `Bearer ${process.env.API_KEY}` }
}
);
setConversationId(response.data.data.conversation_id);
// Add welcome message
const welcomeResponse = await axios.post(
`https://api.neuraltalk.ai/v1/conversations/${response.data.data.conversation_id}/messages`,
{
text: 'welcome',
is_system_command: true,
user_id: userId
},
{
headers: { Authorization: `Bearer ${process.env.API_KEY}` }
}
);
setMessages([{
id: welcomeResponse.data.data.message_id,
text: welcomeResponse.data.data.text,
sender: 'bot'
}]);
} catch (error) {
console.error('Failed to initialize chatbot:', error);
}
}
initializeConversation();
}, [userId]);
const sendMessage = async () => {
if (!input.trim() || !conversationId) return;
const userMessage = { id: Date.now(), text: input, sender: 'user' };
setMessages([...messages, userMessage]);
setInput('');
try {
const response = await axios.post(
`https://api.neuraltalk.ai/v1/conversations/${conversationId}/messages`,
{
text: input,
user_id: userId
},
{
headers: { Authorization: `Bearer ${process.env.API_KEY}` }
}
);
setMessages(prev => [
...prev,
{
id: response.data.data.message_id,
text: response.data.data.text,
sender: 'bot'
}
]);
// Check if the response contains lead information
if (response.data.data.metadata?.lead_info) {
await submitLeadToSalesSystem(response.data.data.metadata.lead_info);
}
} catch (error) {
console.error('Failed to send message:', error);
}
};
// Component JSX and event handlers...
}
Knowledge Base Integration
Overview
Connect your existing knowledge base or documentation to NeuralTalk AI to provide accurate responses based on your specific content.
Implementation Example
import os
import requests
from datetime import datetime
API_KEY = os.environ.get('NEURALTALK_API_KEY')
BASE_URL = 'https://api.neuraltalk.ai/v1'
CHATBOT_ID = os.environ.get('KNOWLEDGE_BOT_ID')
def update_knowledge_base():
"""Sync your knowledge base with NeuralTalk AI when documentation changes"""
# Get list of documentation files
documentation_files = get_documentation_files()
# For each file that was modified since last sync
for file in documentation_files:
if file['last_modified'] > get_last_sync_time():
# Extract content from the file
content = extract_content(file['path'])
# Upload to NeuralTalk AI knowledge base
response = requests.post(
f'{BASE_URL}/knowledge',
json={
'chatbot_id': CHATBOT_ID,
'title': file['title'],
'content': content,
'source_url': file['url'],
'category': file['category']
},
headers={'Authorization': f'Bearer {API_KEY}'}
)
if response.status_code == 200:
print(f"Successfully updated: {file['title']}")
else:
print(f"Failed to update: {file['title']}")
print(response.json())
# Update last sync time
update_last_sync_time(datetime.now())
# Run the update function whenever documentation is modified
if __name__ == '__main__':
update_knowledge_base()
Multi-Platform Support
Overview
Integrate NeuralTalk AI across multiple communication channels (website, mobile app, social media) while maintaining conversation context.
Implementation Example
// Express.js middleware to handle messages from different platforms
const handleMessage = async (platform, userId, message, res) => {
try {
// Look up existing conversation or create a new one
let conversationId;
const existingConversation = await findExistingConversation(userId);
if (existingConversation) {
conversationId = existingConversation.id;
} else {
// Create a new conversation
const response = await axios.post(
'https://api.neuraltalk.ai/v1/conversations',
{
chatbot_id: process.env.OMNICHANNEL_BOT_ID,
user_id: userId,
metadata: { platform, initial_platform: platform }
},
{
headers: { Authorization: `Bearer ${process.env.API_KEY}` }
}
);
conversationId = response.data.data.conversation_id;
await storeConversation(userId, conversationId);
}
// Send message to the AI
const messageResponse = await axios.post(
`https://api.neuraltalk.ai/v1/conversations/${conversationId}/messages`,
{
text: message,
user_id: userId,
metadata: { platform }
},
{
headers: { Authorization: `Bearer ${process.env.API_KEY}` }
}
);
// Send the AI's response back to the appropriate platform
const aiResponse = messageResponse.data.data.text;
await sendPlatformSpecificResponse(platform, userId, aiResponse);
res.status(200).json({ success: true });
} catch (error) {
console.error(`Error handling message from ${platform}:`, error);
res.status(500).json({ success: false, error: 'Failed to process message' });
}
};
// Route handlers for different platforms
app.post('/api/website-chat', (req, res) => {
const { userId, message } = req.body;
handleMessage('website', userId, message, res);
});
app.post('/api/mobile-app', (req, res) => {
const { userId, message } = req.body;
handleMessage('mobile', userId, message, res);
});
app.post('/api/facebook', (req, res) => {
const { senderId, message } = req.body;
handleMessage('facebook', `fb_${senderId}`, message, res);
});
Analytics and Reporting
Overview
Use the API to collect data about conversations and user interactions for analysis and reporting.
Implementation Example
import os
import requests
import pandas as pd
from datetime import datetime, timedelta
API_KEY = os.environ.get('NEURALTALK_API_KEY')
BASE_URL = 'https://api.neuraltalk.ai/v1'
def generate_weekly_report():
"""Generate a weekly report of chatbot performance"""
# Set date range for the report
end_date = datetime.now()
start_date = end_date - timedelta(days=7)
# Get analytics data
response = requests.get(
f'{BASE_URL}/analytics/conversations',
params={
'start_date': start_date.isoformat(),
'end_date': end_date.isoformat()
},
headers={'Authorization': f'Bearer {API_KEY}'}
)
if response.status_code != 200:
print("Failed to fetch analytics data")
return
data = response.json()['data']
# Process the data
df = pd.DataFrame(data['conversations'])
# Calculate key metrics
total_conversations = len(df)
avg_messages_per_conversation = df['message_count'].mean()
resolution_rate = len(df[df['resolved'] == True]) / total_conversations if total_conversations > 0 else 0
avg_response_time = df['avg_response_time_seconds'].mean()
# Generate report
report = f"""
Weekly Chatbot Performance Report ({start_date.strftime('%Y-%m-%d')} to {end_date.strftime('%Y-%m-%d')})
Total Conversations: {total_conversations}
Average Messages Per Conversation: {avg_messages_per_conversation:.2f}
Resolution Rate: {resolution_rate:.2%}
Average Response Time: {avg_response_time:.2f} seconds
Top 5 User Intents:
{df['primary_intent'].value_counts().head(5).to_string()}
Top 5 Unanswered Questions:
{df[df['resolved'] == False]['last_user_message'].value_counts().head(5).to_string()}
"""
# Save or email the report
print(report)
return report
# Run weekly
if __name__ == '__main__':
generate_weekly_report()
Additional Use Cases
- Appointment Scheduling: Implement a chatbot that can schedule appointments and send reminders
- Product Recommendations: Create a shopping assistant that provides personalized product recommendations
- Content Personalization: Deliver customized content based on user preferences and behavior
- Survey and Feedback Collection: Gather customer feedback through conversational interfaces
- Interactive Training: Develop interactive training experiences for employees or customers
For help implementing any of these use cases, or to discuss your specific requirements, contact our support team.