Package: ibm-watson
Watson Developer Cloud Python SDKDeprecated buildsPython client library to quickly get started with the various [Watson APIs][wdc] services.Before you beginYou need an [IBM Cloud][ibm-cloud-onboarding] account. We now only supportpython 3.5and aboveInstallationTo install, usepiporeasy_install:pipinstall--upgradeibm-watsonoreasy_install--upgradeibm-watsonNote the following:
a) Versions prior to 3.0.0 can be installed using:pipinstall--upgradewatson-developer-cloudb) If you run into permission issues try:sudo-Hpipinstall--ignore-installedsixibm-watsonFor more details see#225c) In case you run into problems installing the SDK in DSX, try!pip install --upgrade pipRestarting the kernelFor more details see#405ExamplesThe [examples][examples] folder has basic and advanced examples. The examples within each service assume that you already haveservice credentials.Running in IBM CloudIf you run your app in IBM Cloud, the SDK gets credentials from the [VCAP_SERVICES][vcap_services] environment variable.AuthenticationWatson services are migrating to token-based Identity and Access Management (IAM) authentication.With some service instances, you authenticate to the API by usingIAM.In other instances, you authenticate by providing theusername and passwordfor the service instance.Getting credentialsTo find out which authentication to use, view the service credentials. You find the service credentials for authentication the same way for all Watson services:Go to the IBM CloudDashboardpage.Either click an existing Watson service instance in yourresource listor clickCreate resource > AIand create a service instance.Click on theManageitem in the left nav bar of your service instance.On this page, you should be able to see your credentials for accessing your service instance.Supplying credentialsThere are three ways to supply the credentials you found above to the SDK for authentication.Credential fileWith a credential file, you just need to put the file in the right place and the SDK will do the work of parsing and authenticating. You can get this file by clicking theDownloadbutton for the credentials in theManagetab of your service instance.The file downloaded will be calledibm-credentials.env. This is the name the SDK will search for andmustbe preserved unless you want to configure the file path (more on that later). The SDK will look for youribm-credentials.envfile in the following places (in order):The top-level directory of the project you're using the SDK inYour system's home directoryAs long as you set that up correctly, you don't have to worry about setting any authentication options in your code. So, for example, if you created and downloaded the credential file for your Discovery instance, you just need to do the following:discovery=DiscoveryV1(version='2019-04-30')And that's it!If you're using more than one service at a time in your code and get two differentibm-credentials.envfiles, just put the contents together in oneibm-credentials.envfile and the SDK will handle assigning credentials to their appropriate services.If you would like to configure the location/name of your credential file, you can set an environment variable calledIBM_CREDENTIALS_FILE.This will take precedence over the locations specified above.Here's how you can do that:exportIBM_CREDENTIALS_FILE="<path>"where<path>is something like/home/user/Downloads/<file_name>.env.Environment VariablesSimply set the environment variables using _ syntax. For example, using your favourite terminal, you can set environment variables for Assistant service instance:exportASSISTANT_APIKEY="<your apikey>"exportASSISTANT_AUTH_TYPE="iam"The credentials will be loaded from the environment automaticallyassistant=AssistantV1(version='2018-08-01')ManuallyIf you'd prefer to set authentication values manually in your code, the SDK supports that as well. The way you'll do this depends on what type of credentials your service instance gives you.IAMIBM Cloud has migrated to token-based Identity and Access Management (IAM) authentication. IAM authentication uses a service API key to get an access token that is passed with the call. Access tokens are valid for approximately one hour and must be regenerated.You supply either an IAM serviceAPI keyor abearer token:Use the API key to have the SDK manage the lifecycle of the access token. The SDK requests an access token, ensures that the access token is valid, and refreshes it if necessary.Use the access token if you want to manage the lifecycle yourself. For details, seeAuthenticating with IAM tokens.Use a server-side to generate access tokens using your IAM API key for untrusted environments like client-side scripts. The generated access tokens will be valid for one hour and can be refreshed.Supplying the API keyfromibm_watsonimportDiscoveryV1fromibm_cloud_sdk_core.authenticatorsimportIAMAuthenticator# In the constructor, letting the SDK manage the tokenauthenticator=IAMAuthenticator('apikey',url='<iam_url>')# optional - the default value is https://iam.cloud.ibm.com/identity/tokendiscovery=DiscoveryV1(version='2019-04-30',authenticator=authenticator)discovery.set_service_url('<url_as_per_region>')Generating bearer tokens using API keyfromibm_watsonimportIAMTokenManager# In your API endpoint use this to generate new bearer tokensiam_token_manager=IAMTokenManager(apikey='<apikey>')token=iam_token_manager.get_token()Supplying the bearer tokenfromibm_watsonimportDiscoveryV1fromibm_cloud_sdk_core.authenticatorsimportBearerTokenAuthenticator# in the constructor, assuming control of managing the tokenauthenticator=BearerTokenAuthenticator('your bearer token')discovery=DiscoveryV1(version='2019-04-30',authenticator=authenticator)discovery.set_service_url('<url_as_per_region>')Username and passwordfromibm_watsonimportDiscoveryV1fromibm_cloud_sdk_core.authenticatorsimportBasicAuthenticatorauthenticator=BasicAuthenticator('username','password')discovery=DiscoveryV1(version='2019-04-30',authenticator=authenticator)discovery.set_service_url('<url_as_per_region>')No Authenticationfromibm_watsonimportDiscoveryV1fromibm_cloud_sdk_core.authenticatorsimportNoAuthAuthenticatorauthenticator=NoAuthAuthenticator()discovery=DiscoveryV1(version='2019-04-30',authenticator=authenticator)discovery.set_service_url('<url_as_per_region>')Python versionTested on Python 3.9, 3.10, and 3.11.QuestionsIf you have issues with the APIs or have a question about the Watson services, seeStack Overflow.Configuring the http client (Supported from v1.1.0)To set client configs like timeout use theset_http_config()function and pass it a dictionary of configs. See thisdocumentationfor more information about the options. All options shown exceptmethod,url,headers,params,data, andauthare configurable viaset_http_config(). For example for a Assistant service instancefromibm_watsonimportAssistantV1fromibm_cloud_sdk_core.authenticatorsimportIAMAuthenticatorauthenticator=IAMAuthenticator('your apikey')assistant=AssistantV1(version='2021-11-27',authenticator=authenticator)assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com')assistant.set_http_config({'timeout':100})response=assistant.message(workspace_id=workspace_id,input={'text':'What\'s the weather like?'}).get_result()print(json.dumps(response,indent=2))Use behind a corporate proxyTo use the SDK with any proxies you may have they can be set as shown below. For documentation on proxies seehereSee this example configuration:fromibm_watsonimportAssistantV1fromibm_cloud_sdk_core.authenticatorsimportIAMAuthenticatorauthenticator=IAMAuthenticator('your apikey')assistant=AssistantV1(version='2021-11-27',authenticator=authenticator)assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com')assistant.set_http_config({'proxies':{'http':'http://10.10.1.10:3128','https':'http://10.10.1.10:1080',}})Sending custom certificatesTo send custom certificates as a security measure in your request, use the cert property of the HTTPS Agent.fromibm_watsonimportAssistantV1fromibm_cloud_sdk_core.authenticatorsimportIAMAuthenticatorauthenticator=IAMAuthenticator('your apikey')assistant=AssistantV1(version='2021-11-27',authenticator=authenticator)assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com')assistant.set_http_config({'cert':('path_to_cert_file','path_to_key_file')})Disable SSL certificate verificationFor ICP(IBM Cloud Private), you can disable the SSL certificate verification by:service.set_disable_ssl_verification(True)Or can set it from extrernal sources. For example set in the environment variable.export <service name>_DISABLE_SSL=TrueSetting the service urlTo set the base service to be used when contacting the serviceservice.set_service_url('my_new_service_url')Or can set it from extrernal sources. For example set in the environment variable.export <service name>_URL="<your url>"Sending request headersCustom headers can be passed in any request in the form of adictas:headers={'Custom-Header':'custom_value'}For example, to send a header calledCustom-Headerto a call in Watson Assistant, pass
the headers parameter as:fromibm_watsonimportAssistantV1fromibm_cloud_sdk_core.authenticatorsimportIAMAuthenticatorauthenticator=IAMAuthenticator('your apikey')assistant=AssistantV1(version='2018-07-10',authenticator=authenticator)assistant.set_service_url('https://gateway.watsonplatform.net/assistant/api')response=assistant.list_workspaces(headers={'Custom-Header':'custom_value'}).get_result()Parsing HTTP response informationIf you would like access to some HTTP response information along with the response model, you can set theset_detailed_response()toTrue. Since Python SDKv2.0, it is set toTruefromibm_watsonimportAssistantV1fromibm_cloud_sdk_core.authenticatorsimportIAMAuthenticatorauthenticator=IAMAuthenticator('your apikey')assistant=AssistantV1(version='2018-07-10',authenticator=authenticator)assistant.set_service_url('https://gateway.watsonplatform.net/assistant/api')assistant.set_detailed_response(True)response=assistant.list_workspaces(headers={'Custom-Header':'custom_value'}).get_result()print(response)This would give an output ofDetailedResponsehaving the structure:{'result':<responsereturnedbyservice>,'headers':{<httpresponseheaders>},'status_code':<httpstatuscode>}You can use theget_result(),get_headers()and get_status_code() to return the result, headers and status code respectively.Getting the transaction IDEvery SDK call returns a response with a transaction ID in theX-Global-Transaction-Idheader. Together the service instance region, this ID helps support teams troubleshoot issues from relevant logs.Suceessfromibm_watsonimportAssistantV1service=AssistantV1(authenticator={my_authenticator})response_headers=service.my_service_call().get_headers()print(response_headers.get('X-Global-Transaction-Id'))Failurefromibm_watsonimportAssistantV1,ApiExceptiontry:service=AssistantV1(authenticator={my_authenticator})service.my_service_call()exceptApiExceptionase:print(e.global_transaction_id)# ORprint(e.http_response.headers.get('X-Global-Transaction-Id'))However, the transaction ID isn't available when the API doesn't return a response for some reason. In that case, you can set your own transaction ID in the request. For example, replace<my-unique-transaction-id>in the following example with a unique transaction ID.fromibm_watsonimportAssistantV1service=AssistantV1(authenticator={my_authenticator})service.my_service_call(headers={'X-Global-Transaction-Id':'<my-unique-transaction-id>'})Using WebsocketsThe Text to Speech service supports synthesizing text to spoken audio using web sockets with thesynthesize_using_websocket. The Speech to Text service supports recognizing speech to text using web sockets with therecognize_using_websocket. These methods need a custom callback class to listen to events. Below is an example ofsynthesize_using_websocket. Note: The service accepts one request per connection.fromibm_watson.websocketimportSynthesizeCallbackclassMySynthesizeCallback(SynthesizeCallback):def__init__(self):SynthesizeCallback.__init__(self)defon_audio_stream(self,audio_stream):returnaudio_streamdefon_data(self,data):returndatamy_callback=MySynthesizeCallback()service.synthesize_using_websocket('I like to pet dogs',my_callback,accept='audio/wav',voice='en-US_AllisonVoice')Cloud Pak for DataIf your service instance is of CP4D, below are two ways of initializing the assistant service.1) Supplying the username, password and authentication urlThe SDK will manage the token for the userfromibm_watsonimportAssistantV1fromibm_cloud_sdk_core.authenticatorsimportCloudPakForDataAuthenticatorauthenticator=CloudPakForDataAuthenticator('<your username>','<your password>','<authentication url>',# should be of the form https://{icp_cluster_host}{instance-id}/apidisable_ssl_verification=True)# Disable ssl verification for authenticatorassistant=AssistantV1(version='<version>',authenticator=authenticator)assistant.set_service_url('<service url>')# should be of the form https://{icp_cluster_host}/{deployment}/assistant/{instance-id}/apiassistant.set_disable_ssl_verification(True)# MAKE SURE SSL VERIFICATION IS DISABLED2) Supplying the access tokenfromibm_watsonimportAssistantV1fromibm_cloud_sdk_core.authenticatorsimportBearerTokenAuthenticatorauthenticator=BearerTokenAuthenticator('your managed access token')assistant=AssistantV1(version='<version>',authenticator=authenticator)assistant.set_service_url('<service url>')# should be of the form https://{icp_cluster_host}/{deployment}/assistant/{instance-id}/apiassistant.set_disable_ssl_verification(True)# MAKE SURE SSL VERIFICATION IS DISABLEDLoggingEnable loggingimportlogginglogging.basicConfig(level=logging.DEBUG)This would show output of the form:DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): iam.cloud.ibm.com:443
DEBUG:urllib3.connectionpool:https://iam.cloud.ibm.com:443 "POST /identity/token HTTP/1.1" 200 1809
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): gateway.watsonplatform.net:443
DEBUG:urllib3.connectionpool:https://gateway.watsonplatform.net:443 "POST /assistant/api/v1/workspaces?version=2018-07-10 HTTP/1.1" 201 None
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): gateway.watsonplatform.net:443
DEBUG:urllib3.connectionpool:https://gateway.watsonplatform.net:443 "GET /assistant/api/v1/workspaces/883a2a44-eb5f-4b1a-96b0-32a90b475ea8?version=2018-07-10&export=true HTTP/1.1" 200 None
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): gateway.watsonplatform.net:443
DEBUG:urllib3.connectionpool:https://gateway.watsonplatform.net:443 "DELETE /assistant/api/v1/workspaces/883a2a44-eb5f-4b1a-96b0-32a90b475ea8?version=2018-07-10 HTTP/1.1" 200 28Low level request and response dumpTo get low level information of the requests/ responses:fromhttp.clientimportHTTPConnectionHTTPConnection.debuglevel=1Dependencies[requests]python_dateutil>= 2.5.3[responses] for testingFollowing for web sockets support in speech to textwebsocket-client1.1.0ibm_cloud_sdk_core>= 3.16.2ContributingSee [CONTRIBUTING.md][contributing].LicenseThis library is licensed under the [Apache 2.0 license][license].