AI Agents Tutorial
This tutorial will guide you through creating and using AI agents with Dumpling AI. You’ll learn how to set up agents, customize them for specific tasks, and integrate them into your applications.
What are AI Agents?
AI agents in Dumpling AI are advanced AI assistants that can perform complex tasks, access tools, and maintain conversation context. They can be customized for specific use cases such as customer support, content generation, data analysis, and more.
Key capabilities include:
- Maintaining conversation history and context
- Accessing knowledge bases for domain-specific knowledge
- Using tools to perform actions like web searches, calculations, or API calls
- Generating structured outputs like JSON
Prerequisites
Before you begin, make sure you have:
- A Dumpling AI account with an API key
- Basic knowledge of HTTP requests
- A code editor and environment for running examples (Node.js, Python, etc.)
Creating an Agent
The first step is to create an agent through the Dumpling AI dashboard:
- Log in to the Dumpling AI dashboard
- Navigate to the Agents section
- Click “Create New Agent”
- Configure your agent with a name, description, and system prompt
- Save your new agent and note the agent ID for API calls
Basic Agent Interaction
Let’s start with a simple example of interacting with your agent:
const axios = require('axios');
async function chatWithAgent(agentId, message, threadId = null) {
try {
const response = await axios.post(
'https://app.dumplingai.com/api/v1/agents/generate-completion',
{
messages: [
{
role: 'user',
content: message
}
],
agentId: agentId,
threadId: threadId,
parseJson: false
},
{
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
console.log('Agent Response:', response.data.text);
console.log('Thread ID:', response.data.threadId);
return response.data;
} catch (error) {
console.error('Error:', error.response ? error.response.data : error.message);
}
}
const agentId = 'your_agent_id';
const result = await chatWithAgent(agentId, 'Tell me about the features of your product.');
Maintaining Conversation Context
To maintain context across multiple messages, use the thread ID returned from the first interaction:
async function conversationDemo(agentId) {
const response1 = await chatWithAgent(agentId, 'What are the main features of your analytics dashboard?');
const threadId = response1.threadId;
const response2 = await chatWithAgent(agentId, 'How can I customize the charts?', threadId);
const response3 = await chatWithAgent(agentId, 'Can I export the data?', threadId);
return {
threadId,
responses: [
response1.text,
response2.text,
response3.text
]
};
}
const conversation = await conversationDemo(agentId);
console.log('Conversation Thread ID:', conversation.threadId);
console.log('Conversation History:', conversation.responses);
Getting Structured JSON Responses
For applications that need structured data, you can request JSON responses:
async function getStructuredResponse(agentId, prompt) {
try {
const response = await axios.post(
'https://app.dumplingai.com/api/v1/agents/generate-completion',
{
messages: [
{
role: 'system',
content: 'You are a helpful assistant that always responds in JSON format. Your responses should follow this structure: {"answer": "your detailed answer", "categories": ["category1", "category2"], "confidence": 0.0 to 1.0}'
},
{
role: 'user',
content: prompt
}
],
agentId: agentId,
parseJson: true
},
{
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
console.log('Structured Response:', response.data.parsedJson);
return response.data.parsedJson;
} catch (error) {
console.error('Error:', error.response ? error.response.data : error.message);
}
}
const jsonResponse = await getStructuredResponse(
agentId,
'What are the three main benefits of using AI in customer service?'
);
console.log('Answer:', jsonResponse.answer);
console.log('Categories:', jsonResponse.categories);
console.log('Confidence:', jsonResponse.confidence);
Connecting Agents to Knowledge Bases
To make your agent more knowledgeable about specific domains, connect it to a knowledge base:
async function askAgentWithKnowledgeBase(agentId, knowledgeBaseId, question) {
try {
const kbResponse = await axios.post(
'https://app.dumplingai.com/api/v1/knowledge-bases/search',
{
knowledgeBaseId: knowledgeBaseId,
query: question,
maxResults: 3
},
{
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
const context = kbResponse.data.results.map(result => result.content).join('\n\n');
const agentResponse = await axios.post(
'https://app.dumplingai.com/api/v1/agents/generate-completion',
{
messages: [
{
role: 'system',
content: `You are a knowledgeable assistant with expertise in the company's products. Use the following information to answer the user's question. If you don't know, say so.\n\nContext from knowledge base:\n${context}`
},
{
role: 'user',
content: question
}
],
agentId: agentId,
parseJson: false
},
{
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
console.log('Answer with Knowledge Base:', agentResponse.data.text);
return agentResponse.data.text;
} catch (error) {
console.error('Error:', error.response ? error.response.data : error.message);
}
}
const knowledgeBaseId = 'your_kb_id';
const answer = await askAgentWithKnowledgeBase(
agentId,
knowledgeBaseId,
'How do I reset my password?'
);
Creating a Chatbot Interface
Here’s a simple example of how to create a chatbot interface using the agent API:
const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');
const app = express();
app.use(bodyParser.json());
const activeThreads = {};
app.post('/api/chat', async (req, res) => {
const { userId, message } = req.body;
if (!userId || !message) {
return res.status(400).json({ error: 'Missing userId or message' });
}
try {
const threadId = activeThreads[userId];
const response = await axios.post(
'https://app.dumplingai.com/api/v1/agents/generate-completion',
{
messages: [
{
role: 'user',
content: message
}
],
agentId: 'your_agent_id',
threadId: threadId,
parseJson: false
},
{
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
activeThreads[userId] = response.data.threadId;
res.json({
response: response.data.text,
threadId: response.data.threadId
});
} catch (error) {
res.status(500).json({
error: 'Failed to get response from agent',
details: error.response ? error.response.data : error.message
});
}
});
app.listen(3000, () => {
console.log('Chatbot server running on port 3000');
});
Advanced Agent Customization
To create more sophisticated agents, customize the system prompt in the Dumpling AI dashboard. Here are some examples:
Customer Support Agent
E-commerce Product Recommendation Agent
Best Practices
- Test thoroughly: Try various inputs to ensure your agent responds appropriately.
- Start simple: Begin with basic functionality and add complexity gradually.
- Use system prompts effectively: Clear, detailed system prompts lead to better agent performance.
- Handle errors gracefully: Implement proper error handling for API failures.
- Respect user privacy: Don’t store sensitive information in conversation threads.
- Monitor usage: Keep track of token usage to manage costs.
Conclusion
You’ve learned how to create and use AI agents with Dumpling AI, including maintaining conversation context, getting structured responses, and connecting agents to knowledge bases. These capabilities enable you to build sophisticated AI-powered applications for various use cases.
Next Steps