如何集成IBM Watson Conversation API:Python终端及网站消息交互方案
Hey there! Awesome that you've already built out your Watson Assistant bot with entities and dialog flows—let's tackle those two integration scenarios you're asking about.
You can easily set up terminal-based chat using IBM's official Watson Python SDK. Here's how to do it step by step:
First, install the SDK via pip:
pip install ibm-watsonNext, create a Python script that handles session creation, user input, and bot responses in a loop:
from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator # Replace these with your actual Watson Assistant credentials API_KEY = "YOUR_ASSISTANT_API_KEY" ASSISTANT_URL = "YOUR_ASSISTANT_URL" ASSISTANT_ID = "YOUR_ASSISTANT_ID" # Initialize authentication and Assistant client authenticator = IAMAuthenticator(API_KEY) assistant = AssistantV2( version='2021-06-14', # Use the latest version available for your instance authenticator=authenticator ) assistant.set_service_url(ASSISTANT_URL) # Create a new chat session session_response = assistant.create_session(assistant_id=ASSISTANT_ID).get_result() session_id = session_response['session_id'] print("Type 'quit' to end the chat.\n") while True: user_input = input("You: ") if user_input.lower() == 'quit': break # Send user message to Watson Assistant response = assistant.message( assistant_id=ASSISTANT_ID, session_id=session_id, input={ 'message_type': 'text', 'text': user_input } ).get_result() # Extract and display the bot's response if response['output']['generic']: for item in response['output']['generic']: if item['response_type'] == 'text': print(f"Bot: {item['text']}\n") # Clean up the session when done assistant.delete_session(assistant_id=ASSISTANT_ID, session_id=session_id)
Just swap out the placeholder values with your actual API key, assistant URL, and assistant ID (you can find all these in your IBM Cloud Watson Assistant dashboard). Run the script, and you’ll be chatting with your bot right in the terminal—type quit to exit.
There are two common approaches here: using IBM’s pre-built web chat widget (quick and easy) or building a custom interface with direct API calls (for full control over design).
Option 1: Official Web Chat Widget (Recommended for Speed)
IBM provides a ready-to-use chat window that you can embed in your website in minutes:
- Log into your IBM Cloud console, go to your Watson Assistant instance, and navigate to the Integrations tab.
- Find the Web Chat option, click Add, and follow the setup wizard to customize the widget’s look, welcome message, and behavior.
- Copy the generated embed script and paste it into the
<body>section of your website’s HTML:<script> window.watsonAssistantChatOptions = { integrationID: "YOUR_INTEGRATION_ID", // Grab this from the Web Chat setup page region: "YOUR_REGION", // e.g., us-south, eu-gb serviceInstanceID: "YOUR_SERVICE_INSTANCE_ID", onLoad: function(instance) { instance.render(); } }; setTimeout(function(){ const t=document.createElement('script'); t.src="https://web-chat.global.assistant.watson.appdomain.cloud/versions/" + (window.watsonAssistantChatOptions.clientVersion || 'latest') + "/WatsonAssistantChatEntry.js"; document.head.appendChild(t); }); </script>
Save your page, and visitors will see the chat widget ready to interact with your bot.
Option 2: Custom API Calls (Full Design Control)
If you want to build a completely custom chat interface, use JavaScript to call the Watson Assistant API directly:
First, add a basic chat UI to your HTML:
<div id="chat-container"> <div id="messages"></div> <input type="text" id="user-input" placeholder="Type your message..."> <button onclick="sendMessage()">Send</button> </div>Add JavaScript to handle session management and message exchange:
// Replace with your Watson Assistant credentials const API_KEY = "YOUR_ASSISTANT_API_KEY"; const ASSISTANT_URL = "YOUR_ASSISTANT_URL"; const ASSISTANT_ID = "YOUR_ASSISTANT_ID"; let sessionId; // Initialize a chat session when the page loads async function initSession() { const response = await fetch(`${ASSISTANT_URL}/v2/assistants/${ASSISTANT_ID}/sessions?version=2021-06-14`, { method: 'POST', headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json' } }); const data = await response.json(); sessionId = data.session_id; } // Send user message and display bot response async function sendMessage() { const userInput = document.getElementById('user-input').value; if (!userInput || !sessionId) return; // Add user's message to the chat window addMessage('user', userInput); document.getElementById('user-input').value = ''; // Call Watson Assistant API const response = await fetch(`${ASSISTANT_URL}/v2/assistants/${ASSISTANT_ID}/sessions/${sessionId}/message?version=2021-06-14`, { method: 'POST', headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ input: { message_type: 'text', text: userInput } }) }); const data = await response.json(); // Display bot's response if (data.output.generic) { data.output.generic.forEach(item => { if (item.response_type === 'text') { addMessage('bot', item.text); } }); } } // Helper function to add messages to the UI function addMessage(sender, text) { const messagesDiv = document.getElementById('messages'); const messageDiv = document.createElement('div'); messageDiv.className = `${sender}-message`; messageDiv.textContent = text; messagesDiv.appendChild(messageDiv); // Scroll to the latest message messagesDiv.scrollTop = messagesDiv.scrollHeight; } // Initialize session on page load window.onload = initSession;Add some CSS to style the chat interface (optional but recommended):
#chat-container { width: 400px; margin: 20px auto; border: 1px solid #ccc; border-radius: 8px; padding: 10px; } #messages { height: 300px; overflow-y: auto; margin-bottom: 10px; padding: 10px; border-bottom: 1px solid #eee; } .user-message { text-align: right; margin: 5px 0; padding: 8px; background-color: #007bff; color: white; border-radius: 8px; max-width: 70%; margin-left: auto; } .bot-message { text-align: left; margin: 5px 0; padding: 8px; background-color: #f8f9fa; color: #333; border-radius: 8px; max-width: 70%; margin-right: auto; } #user-input { width: 70%; padding: 8px; border-radius: 4px; border: 1px solid #ccc; } button { padding: 8px 16px; border-radius: 4px; border: none; background-color: #007bff; color: white; cursor: pointer; }
This setup gives you full control over how the chat looks and behaves on your website.
内容的提问来源于stack exchange,提问作者ANKIT KUMAR

