### Start a Local MCP Server with Node Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=server-adding-mcp-tools-multiple-agents Example command to start a local MCP server using Node.js. Ensure Node.js is installed. ```bash npx -y time-mcp ``` -------------------------------- ### Example Agent Instructions for Workflow Output Handling Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=behavior-adding-instructions Use these instructions to guide the agent on how to process and return responses from agentic workflows. Ensure the output conforms to a specified JSON schema. ```text When invoking agentic workflow, do not reconstruct the final sentence or output from the input parameters. Instead: * Capture the exact response returned by the flow. * If the response is a plain string, return it to the user unchanged. * If the response is a JSON object, extract the relevant field values and include them in the final message. * Only add additional explanatory text after the workflow output, and do not replace the workflow-generated output. * Ensure the output strictly conforms to the JSON schema defined in {self.spec.output_schema}, and do not include any text outside the JSON object. * Provide schema references and example outputs (for example, routing or structured responses) to improve the model's accuracy and consistency in generating correct workflow outputs. ``` -------------------------------- ### Example username and API key Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=api-generating-key-premises This is an example of the combined username and API key string before Base64 encoding. ```text myUser:abcdefghijklmnopqrstuvwxyz1234567890 ``` -------------------------------- ### Example Callback URL Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=credentials-authentication-types-overview An example of a complete callback URL based on a specific watsonx Orchestrate environment URL. ```text `https://dl.watsonx-orchestrate.ibm.com/mfe_connectors/api/v1/agentic/oauth/_callback` ``` -------------------------------- ### Example Service Instance URL Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=credentials-authentication-types-overview An example of a service instance URL that can be used to derive the base URL for constructing the callback URL. ```text `https://api.us-south.watson-orchestrate.cloud.ibm.com/instances/12345678-abcd-90ef-1234-abcdef123456` ``` -------------------------------- ### Get All Skills (On-premises) Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=api-getting-started This example shows how to retrieve all skills using the watsonx Orchestrate API with on-premises authentication. ```APIDOC ## GET /orchestrate/MY_NAMESPACE/instances/MY_INSTANCE_ID/v1/orchestrate/digital-employees/allskills ### Description Retrieves all available skills for digital employees using on-premises authentication. ### Method GET ### Endpoint https://MYHOST:PORT//orchestrate/MY_NAMESPACE/instances/MY_INSTANCE_ID/v1/orchestrate/digital-employees/allskills ### Parameters #### Path Parameters - **MY_NAMESPACE** (string) - Required - The namespace for your on-premises deployment. - **MY_INSTANCE_ID** (string) - Required - Your watsonx Orchestrate instance ID. #### Query Parameters None #### Request Body None ### Request Example **curl** ``` curl -X GET "https://MYHOST:PORT//orchestrate/MY_NAMESPACE/instances/MY_INSTANCE_ID/v1/orchestrate/digital-employees/allskills" \ -H "Authorization: ZenApiKey MY_ZEN_API_KEY" \ -H "Accept: application/json" ``` **Python** ```python import http.client import base64 region_code = f"https://MYHOST:PORT/" api_key = "MY_API_KEY" username = "MY_USER_NAME" api_key_bytes = f"{username}:{api_key}".encode(encoding="utf-8") zen_api_key = base64.encodebytes(api_key_bytes).decode(encoding="utf-8") namespace = "MY_NAMESPACE" instance_id = "MY_INSTANCE_ID" endpoint = "/orchestrate/{namespace}/instances/{instanceid}/v1/orchestrate/digital-employees/allskills/" conn = http.client.HTTPSConnection(f"{myhost}") headers = { 'Authorization': f"ZenApiKey {zen_api_key}",\ 'accept': "application/json" } conn.request("GET", endpoint, headers=headers) res = conn.getresponse() data = res.read() print(data.decode("utf-8")) ``` ### Response #### Success Response (200) - **skills** (array) - A list of available skills. #### Response Example (Example response structure would be detailed here if provided in source) ``` -------------------------------- ### Python: Connect and Send Initial Message Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=overview-building-custom-client-by-using-api This snippet shows how to initialize the Assistant V2 service, send an empty message to start a conversation, and print text responses. Ensure the 'ibm-watson' SDK is installed. ```python # Example 1: Creates service object, sends initial message, and # receives response. from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator # Create Assistant service object. authenticator = IAMAuthenticator('{apikey}') # replace with API key assistant = AssistantV2( version = '2021-11-27', authenticator = authenticator ) assistant.set_service_url('{url}') # replace with service instance URL assistant_id = '{environment_id}' # replace with environment ID # Start conversation with empty message. result = assistant.message_stateless( assistant_id, ).get_result() # Print responses from actions, if any. Supports only text responses. if result['output']['generic']: for response in result['output']['generic']: if response['response_type'] == 'text': print(response['text']) ``` -------------------------------- ### Example of Setting an Output Variable Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=integrations-integrating-genesys-audio-connector An example demonstrating how to set a specific output variable named 'some_variable' with a string value for Genesys Audio Connector. ```text ${system_integrations.genesys_audio_connector.some_variable} = "this is an output variable" ``` -------------------------------- ### Example Header for JSON Response Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=mcbpm-calling-service-before-processing-message-cloud-pak-data-classic-experience This example shows how to configure a header to request that the external application returns the response in JSON format. The 'Content-Type' header is used for this purpose. ```text Content-Type | application/json ``` -------------------------------- ### Define a starting phrase for an action Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=actions-understanding-your-users-questions-requests Enter a single phrase that a user might say or type to initiate a specific action. This phrase is stored in 'Customer starts with'. ```text What are your store hours? ``` -------------------------------- ### Bad Instruction Example for GPT-OSS Model Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=models-gpt-oss-model-behavior-instruction-guidelines This example illustrates an instruction that encourages excessive reasoning and verbosity, contrary to best practices for concise and efficient model responses. ```text Think in exhaustive detail until you're absolutely certain. Explore all possible interpretations. Provide a comprehensive narrative of your thoughts and include context for every claim. ``` -------------------------------- ### Example Phone Integration JSON Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=reference-phone-integration-context-variables This example demonstrates the structure of a JSON payload for a phone integration, including input parameters like speech_to_text_result and context variables such as sip_call_id and user_phone_number. ```json { "input": { "text": "agent ", "integrations": { "voice_telephony": { "speech_to_text_result": { "result_index": 0, "stopTimestamp": "2021-09-29T17:43:31.036Z", "transaction_ids": { "x-global-transaction-id": "43dd6ce0-139a-4d76-95aa-86e03fcfc434", "x-dp-watson-tran-id": "6e60695e-fed7-4efe-a376-0888b027d30f" }, "results": [ { "final": true, "alternatives": [ { "transcript": "agent ", "confidence": 0.78 } ] } ], "transactionID": "43dd6ce0-139a-4d76-95aa-86e03fcfc434", "startTimestamp": "2021-09-29T17:43:29.436Z" }, "is_dtmf": false, "barge_in_occurred": false } } }, "context": { "skills": { "main skill": { "user_defined": {}, "system": {} } }, "integrations": { "voice_telephony": { "private": { "sip_to_uri": "sip:watson-conversation@10.10.10.10", "sip_from_uri": "sip:10.10.10.11", "sip_request_uri": "sip:test@10.10.10.10:5064;transport=tcp" }, "sip_call_id": "QjryZsuAS4", "assistant_phone_number": "18882346789" } } } } ``` -------------------------------- ### Good Instruction Example for GPT-OSS Model Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=models-gpt-oss-model-behavior-instruction-guidelines This concise instruction example enforces constraints on knowledge base usage, reasoning steps, and answer length, while also specifying error handling for knowledge retrieval. ```text Use knowledge bases as the primary source. Cite the document name when used. Limit yourself to 3 reasoning steps and less than 150 words in the final answer. If you cannot find an answer in knowledge, say so and ask one clarifying question. ``` -------------------------------- ### Get All Skills (AWS) Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=api-getting-started This example shows how to retrieve all skills using the watsonx Orchestrate API with AWS authentication. ```APIDOC ## GET /instances/MY_INSTANCE_ID/v1/orchestrate/digital-employees/allskills ### Description Retrieves all available skills for digital employees using AWS authentication. ### Method GET ### Endpoint https://api.REGION_CODE.watson-orchestrate.ibm.com/instances/MY_INSTANCE_ID/v1/orchestrate/digital-employees/allskills ### Parameters #### Path Parameters - **MY_INSTANCE_ID** (string) - Required - Your watsonx Orchestrate instance ID. #### Query Parameters None #### Request Body None ### Request Example **curl** ``` curl -X GET "https://api.REGION_CODE.watson-orchestrate.ibm.com/instances/MY_INSTANCE_ID/v1/orchestrate/digital-employees/allskills" \ -H "Authorization: Bearer MY_JWT_TOKEN" \ -H "Accept: application/json" ``` **Python** ```python import http.client region_code = "REGION_CODE" jwt_token = "MY_JWT_TOKEN" instance_id = "MY_INSTANCE_ID" conn = http.client.HTTPSConnection(f"{region_code}.dl.watson-orchestrate.ibm.com") headers = { 'Authorization': f"Bearer {jwt_token}",\ 'accept': "application/json" } conn.request("GET", f"/instances/{instance_id}/v1/orchestrate/digital-employees/allskills", headers=headers) res = conn.getresponse() data = res.read() print(data.decode("utf-8")) ``` ### Response #### Success Response (200) - **skills** (array) - A list of available skills. #### Response Example (Example response structure would be detailed here if provided in source) ``` -------------------------------- ### Example of a Tool with a Clear Input Schema Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=agents-context-sharing-collaborator Demonstrates a tool definition with descriptive parameter names and types to facilitate clear data passing between agents. ```text Tool: process_subscription_change Parameters: - account_id (required): "Customer account identifier (e.g., ACC-12345)" - new_tier (required): "Target subscription tier (basic|pro|enterprise)" - effective_date (optional): "When to apply change (ISO 8601 date)" ``` -------------------------------- ### Get All Skills (IBM Cloud) Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=api-getting-started This example shows how to retrieve all skills using the watsonx Orchestrate API with IBM Cloud authentication. ```APIDOC ## GET /instances/MY_INSTANCE_ID/v1/orchestrate/digital-employees/allskills ### Description Retrieves all available skills for digital employees. ### Method GET ### Endpoint https://api.REGION_CODE.watson.cloud.ibm.com/instances/MY_INSTANCE_ID/v1/orchestrate/digital-employees/allskills ### Parameters #### Path Parameters - **MY_INSTANCE_ID** (string) - Required - Your watsonx Orchestrate instance ID. #### Query Parameters None #### Request Body None ### Request Example **curl** ``` curl -X GET "https://api.REGION_CODE.watson.cloud.ibm.com/instances/MY_INSTANCE_ID/v1/orchestrate/digital-employees/allskills" \ -H "Authorization: Bearer MY_IAM_TOKEN" \ -H "Accept: application/json" ``` **Python** ```python import http.client region_code = "REGION_CODE" iam_token = "MY_IAM_TOKEN" instance_id = "MY_INSTANCE_ID" conn = http.client.HTTPSConnection(f"api.{region_code}.watson-orchestrate.ibm.com") headers = { 'Authorization': f"Bearer {iam_token}",\ 'accept': "application/json" } conn.request("GET", f"/instances/{instance_id}/v1/orchestrate/digital-employees/allskills", headers=headers) res = conn.getresponse() data = res.read() print(data.decode("utf-8")) ``` ### Response #### Success Response (200) - **skills** (array) - A list of available skills. #### Response Example (Example response structure would be detailed here if provided in source) ``` -------------------------------- ### Example webhook URL for Cloud Functions Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=mcbpm-calling-service-before-processing-message-cloud-pak-data Specify the URL for your Cloud Functions web action. Ensure the URL uses the SSL protocol by starting with `https`. ```shell https://us-south.functions.cloud.ibm.com/api/v1/web/my_org_dev/default/translateToEnglish.json ``` -------------------------------- ### Example Instruction for GPT-OSS 120B Models Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=models-gpt-oss-model-behavior-instruction-guidelines This example demonstrates how to provide clear and multi-faceted instructions to GPT-OSS 120B models. It specifies tone, tool usage for different data types, and error handling for incomplete information. ```text Always respond in a professional tone. When asked for CRM data, use the salesforce_api tool. If the request involves scheduling, call the calendar_agent. If information is incomplete, ask clarifying questions before proceeding. ``` -------------------------------- ### Start a Journey from Your Website Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=developing-guiding-customers-journeys Use the `send()` instance method to trigger a journey from your website. This is useful for interactive tours or guided processes initiated by user actions like button clicks. ```javascript instance.send('Give me a tour'); ``` -------------------------------- ### Node.js: Connect and Send Initial Message Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=overview-building-custom-client-by-using-api This snippet demonstrates how to create a service object, send an initial empty message to start a conversation, and process the response. Ensure the 'ibm-watson' SDK is installed. ```javascript // Example 1: Creates service object, sends initial message, and // receives response. const AssistantV2 = require('ibm-watson/assistant/v2'); const { IamAuthenticator } = require('ibm-watson/auth'); // Create Assistant service object. const assistant = new AssistantV2({ version: '2021-11-27', authenticator: new IamAuthenticator({ apikey: '{apikey}', // replace with API key }), url: '{url}', // replace with URL }); const assistantId = '{environment_id}'; // replace with environment ID // Start conversation with empty message messageInput = { messageType: 'text', text: '', }; sendMessage(messageInput); // Send message to assistant. function sendMessage(messageInput) { assistant .messageStateless({ assistantId, input: messageInput, }) .then(res => { processResult(res.result); }) .catch(err => { console.log(err); // something went wrong }); } // Process the result. function processResult(result) { // Print responses from actions, if any. Supports only text responses. if (result.output.generic) { if (result.output.generic.length > 0) { result.output.generic.forEach( response => { if (response.response_type == 'text') { console.log(response.text); } }); } } } ``` -------------------------------- ### Agent with Tools Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=agents-creating-langgraph-package-import This example shows how to build an agent capable of using tools. It defines a weather tool and configures the agent to use it via a ToolNode and conditional edges. ```python from typing import Annotated, List, TypedDict from langchain_core.messages import BaseMessage from langchain_core.runnables.config import RunnableConfig from langchain_openai import ChatOpenAI from langgraph.graph import StateGraph, END from langgraph.prebuilt import ToolNode, tools_condition class AgentState(TypedDict): messages: Annotated[List[BaseMessage], "conversation history"] def get_weather(location: str) -> str: """Get the current weather for a location.""" return f"The weather in {location} is sunny and 72°F" def create_agent(config: RunnableConfig) -> StateGraph: credentials = config.get("configurable", {}).get("credentials", {}) llm = ChatOpenAI( model="gpt-4o-mini", api_key=credentials.get("openai_api_api_key") ) tools = [get_weather] tool_node = ToolNode(tools) def agent_node(state: AgentState): response = llm.bind_tools(tools).invoke(state["messages"]) return {"messages": [response]} workflow = StateGraph(AgentState) workflow.add_node("agent", agent_node) workflow.add_node("tools", tool_node) workflow.add_conditional_edges( "agent", tools_condition, {"tools": "tools", "__end__": END} ) workflow.add_edge("tools", "agent") workflow.set_entry_point("agent") return workflow ``` -------------------------------- ### Create MilvusClient Session in Python Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=repository-enabling-granular-access-control-milvus Initialize a MilvusClient session with connection details, username, password, and SSL certificate path. Ensure the provided URI and certificate path are correct for your Milvus instance. ```python from pymilvus import MilvusClient client = MilvusClient( uri="", # your Milvus service URI, for example, http://localhost:19530 user="", password="", server_pem_path="./milvus_onprem_tls.crt" # path to your SSL certificate ) ``` -------------------------------- ### Preserving Context for State Management Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=overview-building-custom-client-by-using-api This Node.js example demonstrates how to use the `messageStateless` method to maintain conversation state by preserving and sending back the `context` object with each API call. It includes setup for the Assistant V2 SDK, sending messages, and processing responses to continue the conversation. ```javascript // Example 3: Preserves context to maintain state. const prompt = require('prompt-sync')(); const AssistantV2 = require('ibm-watson/assistant/v2'); const { IamAuthenticator } = require('ibm-watson/auth'); // Create Assistant service object. const assistant = new AssistantV2({ version: '2021-11-27', authenticator: new IamAuthenticator({ apikey: '{apikey}', // replace with API key }), url: '{url}', // replace with URL }); const assistantId = '{environment_id}'; // replace with environment ID // Start conversation with empty message messageInput = { messageType: 'text', text: '', }; context = {}; sendMessage(messageInput); // Send message to assistant. function sendMessage(messageInput, context) { assistant .messageStateless({ assistantId, input: messageInput, context: context, }) .then(res => { processResult(res.result); }) .catch(err => { console.log(err); // something went wrong }); } // Process the result. function processResult(result) { let context = result.context; // Print responses from actions, if any. Supports only text responses. if (result.output.generic) { if (result.output.generic.length > 0) { result.output.generic.forEach( response => { if (response.response_type === 'text') { console.log(response.text); } }); } } // Prompt for the next round of input unless skip_user_input is true. let newMessageFromUser = ''; if (result.context.global.system.skip_user_input !== true) { newMessageFromUser = prompt('>> '); } if (newMessageFromUser !== 'quit') { newMessageInput = { messageType: 'text', text: newMessageFromUser, } sendMessage(newMessageInput, context); } } ``` -------------------------------- ### Example Prompt for Single Schedule Creation Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=limitations-building-tools Illustrates a prompt that attempts to create multiple schedules, which is not supported. Use separate prompts for each schedule. ```text Transfer bonus to employee account 12345 on December 31st at 5 PM, then transfer regular salary on the 1st of every month starting January ``` -------------------------------- ### Check if a string starts with a substring Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=reference-expression-language-methods-actions Returns true if the string starts with the specified substring. ```Expression Language ${step_297}.startsWith('What') ``` -------------------------------- ### Configure Watson Orchestrate Platform User API Connection Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=limitations-building-tools Use these commands to activate the environment, add the WXO_PLATFORM_USER_API connection, configure it for draft and live environments with team type and API key, and set the API key credentials. ```bash $ orchestrate env activate $ orchestrate connections add -a WXO_PLATFORM_USER_API $ orchestrate connections configure -a WXO_PLATFORM_USER_API --env draft -t team -k api_key $ orchestrate connections configure -a WXO_PLATFORM_USER_API --env live -t team -k api_key $ orchestrate connections set-credentials -a WXO_PLATFORM_USER_API --env draft --api-key $ orchestrate connections set-credentials -a WXO_PLATFORM_USER_API --env live --api-key ``` -------------------------------- ### Call API Endpoint (On-premises - Python) Source: https://www.ibm.com/docs/en/watsonx/watson-orchestrate/base?topic=api-getting-started This Python script shows how to call the 'allskills' endpoint for on-premises deployments. It requires your host, port, username, API key, namespace, and instance ID to construct the Zen API key and endpoint. ```python import http.client import base64 region_code = f"https://MYHOST:PORT/" api_key = "MY_API_KEY" username = "MY_USER_NAME" api_key_bytes = f"{username}:{api_key}".encode(encoding="utf-8") zen_api_key = base64.encodebytes(api_key_bytes).decode(encoding="utf-8") namespace = "MY_NAMESPACE" instance_id = "MY_INSTANCE_ID" endpoint = "/orchestrate/{namespace}/instances/{instanceid}/v1/orchestrate/digital-employees/allskills/" conn = http.client.HTTPSConnection(f"{myhost}") headers = { 'Authorization': f"ZenApiKey {zen_api_key}",\ 'accept': "application/json" } conn.request("GET", endpoint, headers=headers) res = conn.getresponse() data = res.read() print(data.decode("utf-8")) ```