Implementing DeepChat: Secure Backend Integration for Conversational AI
DeepChat is essentially a highly customizable, open-source chat component designed to connect your application's frontend with various powerful AI models and services (like OpenAI, Azure, and others). It significantly simplifies the process of integrating complex conversational AI features into your projects.
DeepChat offers several key benefits that streamline development and enhance user experience
Reduced Boilerplate
You don't have to spend time building the chat UI (input box, message display, loading states, error handling) from scratch. DeepChat provides a polished, ready-to-use component.
Quick AI Integration
It abstracts away the complexities of different AI provider APIs. You configure the provider (e.g., OpenAI, Google, Hugging Face) in a straightforward manner, focusing on the conversational logic rather than the API plumbing.
Feature Rich
The component often comes with built-in features like streaming responses (messages appear word-by-word), file uploads, and image generation, which are essential for a modern AI chat experience.
Customization
It's designed to be highly customizable via props or attributes, allowing you to easily match the chat interface's look and feel to your application's branding.
Provider Agnostic
You can switch between or combine different AI providers easily. This is great for testing and future-proofing your application as new models emerge.
Backend Integration
While it supports direct client-side calls for simplicity, it also provides excellent support for integrating with your own custom backend API, which is crucial for secure API key management and implementing complex logic (like RAG - Retrieval Augmented Generation).
The primary way to use DeepChat is by including it in your web application. It supports plain JavaScript, React, Vue, and other frameworks. Here is the general approach
If you're using a package manager like npm (common in React, Vue, Angular projects)
npm install deep-chat
# or
yarn add deep-chat
For a basic HTML/JavaScript setup, you might include the script and CSS via CDN
<script src="https://unpkg.com/[email protected]/dist/deepChat.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/deepChat.css">
You can initialize the chat by adding a custom HTML tag and configuring it using attributes.
<deep-chat
style="border-radius: 10px; box-shadow: 0 0 10px rgba(0,0,0,0.1);"
placeholder="Ask me anything..."
>
<connectors>
<open-ai
api-key="YOUR_OPENAI_API_KEY"
chat-model="gpt-3.5-turbo"
></open-ai>
</connectors>
</deep-chat>
Note
For production applications, never embed your actual API keys directly in client-side code like this. Use the Custom API Connector (see section 3) to route requests through your secure backend server.
For a robust, production-ready setup, you'll use a custom backend API. This keeps your API keys safe and allows you to add your own business logic.
In your React component, you'll configure DeepChat to call your custom endpoint (/api/chat).
import { DeepChat } from 'deep-chat/react';
const ChatAssistant = () => {
return (
<div style={{ height: '400px', width: '300px' }}>
<h2>My Secure AI Chat</h2>
<DeepChat
// Configuration for your custom API endpoint
request={{
url: 'http://localhost:3000/api/chat', // Your backend endpoint
method: 'POST',
}}
// Optional: Customizing the UI
style={{ borderRadius: '15px', border: '1px solid #ccc' }}
initialMessages={[
{ role: 'ai', content: 'Hi! How can I assist you today?' }
]}
/>
</div>
);
};
export default ChatAssistant;
This is a simplified example of how your backend server would receive the user message, call the real OpenAI API securely using your stored key, and send the response back.
// A simple Express server setup (install express and openai packages first)
const express = require('express');
const { OpenAI } = require('openai');
const app = express();
app.use(express.json());
// Initialize OpenAI client with your securely stored key
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
app.post('/api/chat', async (req, res) => {
// DeepChat sends an array of messages (history)
const { messages } = req.body;
try {
// Call the OpenAI API securely
const completion = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: messages, // Pass the conversation history
});
// Send back the AI's response in the format DeepChat expects
// DeepChat expects a JSON object with a 'text' property for the response
res.json({
text: completion.choices[0].message.content,
});
} catch (error) {
console.error("OpenAI API Error:", error);
res.status(500).json({ error: "Failed to communicate with AI service." });
}
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});