langgenius / dify

Dify is an open-source LLM app development platform. Dify's intuitive interface combines AI workflow, RAG pipeline, agent capabilities, model management, observability features and more, letting you quickly go from prototype to production.
https://dify.ai
Other
45.54k stars 6.4k forks source link

Custom API Chatbot with nodejs no history of the conversation Included #7327

Open andsty opened 1 month ago

andsty commented 1 month ago

Self Checks

Dify version

0.6.16

Cloud or Self Hosted

Self Hosted (Docker)

Steps to reproduce

Create a chatbot with nodejs

✔️ Expected Behavior

When asking follow up question to remember history

❌ Actual Behavior

It does not remember previous conversation

dosubot[bot] commented 1 month ago

To fix the issue where your custom API chatbot created using Node.js and Dify version 0.6.16 does not remember the previous conversation when asking follow-up questions, you need to ensure that you are correctly managing the conversation_id in your API requests. Here is how you can do it:

  1. Retrieve the conversation_id after the initial chat request.
  2. Use the same conversation_id for subsequent requests to maintain the context of the conversation.

Here is an example of how you can achieve this:

const axios = require('axios');

const API_URL = 'https://api.dify.ai/v1/chat-messages';
const API_KEY = 'YOUR_SECRET_KEY';
let conversationId = '';

async function sendMessage(query) {
    try {
        const response = await axios.post(API_URL, {
            inputs: {},
            query: query,
            response_mode: 'streaming',
            conversation_id: conversationId,
            user: 'abc-123'
        }, {
            headers: {
                'Authorization': `Bearer ${API_KEY}`,
                'Content-Type': 'application/json'
            }
        });

        // Update conversationId with the one from the response
        if (response.data.conversation_id) {
            conversationId = response.data.conversation_id;
        }

        console.log(response.data);
    } catch (error) {
        console.error('Error sending message:', error);
    }
}

// Example usage
sendMessage('Hello, how are you?').then(() => {
    sendMessage('Can you tell me more about that?');
});

In this example:

Make sure to replace YOUR_SECRET_KEY with your actual API secret key. This approach ensures that the chatbot remembers the previous conversation when handling follow-up questions.

Additionally, as per Dify's best practices, API keys should be called through the backend, rather than being directly exposed in plaintext within frontend code or requests. This helps prevent your application from being abused or attacked [1][2].

To continue talking to Dosu, mention @dosu.

xutengfei commented 3 weeks ago

can we submit history without conversion_id? We need custom some content of history.