如何让Watson Assistant区分不同用户?API调用场景解决方案
Hey there, great question! When dealing with multiple users interacting with your Watson Assistant chatbot via the API, the key is to maintain unique session contexts for each user—here's exactly how to do it:
Core Concept
Watson Assistant tracks conversation state using the context object included in each API request. To separate users, you need to:
- Assign a unique identifier to each user
- Include this identifier in the
contextof every request from that user - Persist and reuse the full
contextobject for each user across their conversation
Required Parameters & Setup
1. Unique User Identifier
First, generate a unique ID for each user (e.g., a UUID, user's login ID, or a session ID created when the user loads the chat). This ID will be stored in context.user_id—Watson uses this to differentiate between separate user sessions.
2. Persist the Context Object
Every time you get a response from Watson, it returns an updated context object. You need to save this object for the current user (use localStorage, sessionStorage, or backend session storage depending on your needs) and include it in all subsequent requests from that user.
Modified Code Example
Here's how to update your existing JavaScript code to handle multiple users:
// Generate a unique user ID on page load (or use your app's existing user ID) let userId = localStorage.getItem('watson_user_id'); if (!userId) { userId = 'user_' + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); localStorage.setItem('watson_user_id', userId); } // Store the user's context across requests let userContext = {}; document.querySelector("#input").addEventListener("keypress", function(e) { var key = e.which || e.keyCode; if (key === 13) { // Enter button var input = document.getElementById("input").value; document.getElementById("input").value = ""; const TempChatInput = document.getElementById("chatbot"); TempChatInput.innerHTML += "user: " + input + "<br/><br/>"; output(input); } }); function output(input) { // Include the user's context and unique ID in the request const requestData = { input: { text: input }, context: { ...userContext, user_id: userId // Attach the unique user ID } }; $.ajax({ url: "https://gateway.watsonplatform.net/assistant/api/v1/workspaces/myWorkspaceID/message?version=2018-02-16", beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "Basic " + btoa("my username" + ":" + "my password")); }, type: "POST", dataType: "json", contentType: "application/json", processData: false, data: JSON.stringify(requestData), // Use JSON.stringify instead of manual string building success: function(data) { // Update the stored context with Watson's response userContext = data.context; const dataText = data["output"]["text"]; const TempChat = document.getElementById("chatbot"); TempChat.innerHTML += "Chatbot: " + dataText + "<br/><br/>"; const objDiv = document.getElementById("chatbotid"); objDiv.scrollTop = objDiv.scrollHeight; }, error: function() { alert("Cannot get data"); } }); }
Key Changes Explained:
- Unique User ID: We generate a UUID and store it in
localStorageso it persists across page reloads for the same user. - Context Persistence: We save the
contextobject returned by Watson after each request, and reuse it in the next request to maintain conversation history. - Proper Request Format: Using
JSON.stringifyto build the request body is more reliable than manual string concatenation and avoids syntax errors.
Additional Notes
- If your app has authenticated users, replace the generated UUID with your app's existing user ID for better consistency and security.
- For server-side applications, store the
contextobject in a database tied to the user's ID instead oflocalStorageto keep sessions synced across devices.
内容的提问来源于stack exchange,提问作者ANKIT KUMAR

