You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Watson Assistant区分不同用户?API调用场景解决方案

How to Let Watson Assistant Distinguish Between Multiple Users

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:

  1. Assign a unique identifier to each user
  2. Include this identifier in the context of every request from that user
  3. Persist and reuse the full context object 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 localStorage so it persists across page reloads for the same user.
  • Context Persistence: We save the context object returned by Watson after each request, and reuse it in the next request to maintain conversation history.
  • Proper Request Format: Using JSON.stringify to 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 context object in a database tied to the user's ID instead of localStorage to keep sessions synced across devices.

内容的提问来源于stack exchange,提问作者ANKIT KUMAR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:15:40