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:

  1. Log in to the Dumpling AI dashboard
  2. Navigate to the Agents section
  3. Click “Create New Agent”
  4. Configure your agent with a name, description, and system prompt
  5. 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, // Optional, for continuing a conversation
        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);
  }
}

// Chat with the agent
const agentId = 'your_agent_id'; // Replace with 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) {
  // First message
  const response1 = await chatWithAgent(agentId, 'What are the main features of your analytics dashboard?');
  const threadId = response1.threadId;
  
  // Continue the conversation
  const response2 = await chatWithAgent(agentId, 'How can I customize the charts?', threadId);
  
  // Ask a follow-up question
  const response3 = await chatWithAgent(agentId, 'Can I export the data?', threadId);
  
  return {
    threadId,
    responses: [
      response1.text,
      response2.text,
      response3.text
    ]
  };
}

// Run a multi-turn conversation
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  // This will parse the response as JSON
      },
      {
        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);
  }
}

// Get a structured response
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 {
    // First, search the knowledge base for relevant information
    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');
    
    // Then, ask the agent a question with the knowledge base context
    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);
  }
}

// Ask a question using the agent and knowledge base
const knowledgeBaseId = 'your_kb_id'; // Replace with your knowledge base 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:

// This example assumes you're using Express for a web server
const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');

const app = express();
app.use(bodyParser.json());

// Store active threads in memory (use a database in production)
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 {
    // Get or create thread ID for this user
    const threadId = activeThreads[userId];
    
    // Call the agent
    const response = await axios.post(
      'https://app.dumplingai.com/api/v1/agents/generate-completion',
      {
        messages: [
          {
            role: 'user',
            content: message
          }
        ],
        agentId: 'your_agent_id', // Replace with your agent ID
        threadId: threadId,
        parseJson: false
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer YOUR_API_KEY'
        }
      }
    );
    
    // Save the thread ID for future messages
    activeThreads[userId] = response.data.threadId;
    
    // Return the agent's response
    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

You are a helpful customer support agent for a software company. 
Your goal is to assist users with their technical issues and questions about our product.

Guidelines:
1. Be friendly and professional
2. Ask clarifying questions if the user's issue is unclear
3. Provide step-by-step instructions when explaining technical processes
4. Recommend relevant documentation when appropriate
5. Escalate complex issues by suggesting the user contact our support team at support@example.com

E-commerce Product Recommendation Agent

You are a knowledgeable e-commerce assistant specializing in helping customers find the right products.

When recommending products:
1. Ask about the customer's needs, preferences, and budget
2. Provide 2-3 specific product recommendations with brief explanations
3. Include pros and cons for each recommendation
4. Suggest accessories or complementary products when relevant
5. Always remain neutral and objective in your recommendations

Best Practices

  1. Test thoroughly: Try various inputs to ensure your agent responds appropriately.
  2. Start simple: Begin with basic functionality and add complexity gradually.
  3. Use system prompts effectively: Clear, detailed system prompts lead to better agent performance.
  4. Handle errors gracefully: Implement proper error handling for API failures.
  5. Respect user privacy: Don’t store sensitive information in conversation threads.
  6. 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