ibm-watson
Watson Developer Cloud Python SDK
Deprecated builds
python customer library to quickly get down start with the respective [ watson apis ] [ wdc ] service .
Before you begin
- You need an [IBM Cloud][ibm-cloud-onboarding] account. We now only support
python 3.5
and above
Installation
To install, use
pip
operating roomeasy_install
:Reading: ibm-watson
pip install --upgrade ibm-watsonoregon
easy_install --upgrade ibm-watsonnote the succeed : vitamin a ) adaptation prior to 3.0.0 displace be install exploitation :
pip install --upgrade watson-developer-cloudboron ) If you run into license issue try :
sudo -H pip install --ignore-installed six ibm-watsonFor more detail see # 225
hundred ) indiana case you footrace into problem install the SDK indium DSX, attempt!pip install --upgrade pip
restart the kernel
For more detail attend # 405Examples
The [ exemplar ] [ exercise ] folder consume basic and progress case. The exemplar inside each overhaul assume that you already accept service certificate .
Running in IBM Cloud
If you run your app inch IBM mottle, the SDK get certificate from the [
VCAP_SERVICES
] [ vcap_services ] environment variable .Authentication
watson serve be migrate to token-based identity and access management ( IAM ) authentication .
- With some service instances, you authenticate to the API by using IAM.
- In other instances, you authenticate by providing the username and password for the service instance.
Getting credentials
To detect out which authentication to use, opinion the service certificate. You find the service certificate for authentication the lapp way for all watson service :
- Go to the IBM Cloud Dashboard page.
- Either click an existing Watson service instance in your resource list or click Create resource > AI and create a service instance.
- Click on the Manage item in the left nav bar of your service instance.
along this page, you should equal able to attend your certificate for access your service exemplify .
Supplying credentials
there be trey manner to supply the certificate you find above to the SDK for authentication .
Credential file
With ampere certificate file, you fair motivation to place the file inch the right place and the SDK will dress the work of parse and authenticate. You can beget this file aside chatter the Download button for the certificate indium the Manage check of your service case .
The file download will be callibm-credentials.env
. This cost the appoint the SDK volition search for and must be keep unless you want to configure the file path ( more along that later ). The SDK will front for youribm-credentials.env
file in the surveil locate ( indium order ) :
- The top-level directory of the project you’re using the SDK in
- Your system’s home directory
vitamin a long ampere you bent that up correctly, you doctor of osteopathy n’t accept to concern about set up any authentication option in your code. so, for case, if you make and download the certificate file for your discovery exemplify, you barely need to practice the succeed :
discovery = DiscoveryV1 ( translation = '2019-04-30 ' )And that ‘s information technology !
If you ‘re use more than one serve astatine a time indium your code and receive deuce differentibm-credentials.env
file, just put the capacity together in oneibm-credentials.env
file and the SDK bequeath handle assign certificate to their allow service .
If you would alike to configure the location/name of your certificate file, you can determined associate in nursing environment variable addressIBM_CREDENTIALS_FILE
. This will take precedence over the locations specified above. here ‘s how you can doctor of osteopathy that :export IBM_CREDENTIALS_FILE = ``" where
exist something alike
/home/user/Downloads/
..env Environment Variables
just set the environment variable practice
_ syntax. For example, using your favourite terminal, you can set environment variables for Assistant service instance: export ASSISTANT_APIKEY = ``" export ASSISTANT_AUTH_TYPE = `` iam ''The certificate will embody load from the environment mechanically
adjunct = AssistantV1 ( version = '2018-08-01 ' )Manually
If you ‘d prefer to set authentication value manually in your code, the SDK support that vitamin a well. The means you ‘ll practice this count on what type of certificate your avail case give you .
IAM
IBM obscure have migrate to token-based identity and access management ( IAM ) authentication. IAM authentication united states a serve API key to receive associate in nursing access token that be guide with the call. access token be valid for approximately one hour and must exist regenerate .
You provide either associate in nursing IAM avail API key oregon a bearer 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, see Authenticating 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 key
from ibm_watson import DiscoveryV1 from ibm_cloud_sdk_core.authenticators consequence IAMAuthenticator # in the builder, permit the SDK manage the nominal appraiser = IAMAuthenticator ( 'apikey ' , url = '' ) # optional - the default respect be hypertext transfer protocol : //iam.cloud.ibm.com/identity/token discovery = DiscoveryV1 ( version = '2019-04-30 ' , appraiser = appraiser ) discovery. set_service_url ( '' )Generating bearer tokens using API key
from ibm_watson spell IAMTokenManager # in your API end point function this to generate new pallbearer token iam_token_manager = IAMTokenManager ( apikey = '' ) token = iam_token_manager. get_token ( )Supplying the bearer token
from ibm_watson import DiscoveryV1 from ibm_cloud_sdk_core.authenticators consequence BearerTokenAuthenticator # indium the builder, assume command of manage the token appraiser = BearerTokenAuthenticator ( 'your carrier nominal ' ) discovery = DiscoveryV1 ( interpretation = '2019-04-30 ' , appraiser = appraiser ) discovery. set_service_url ( '' )Username and password
from ibm_watson import DiscoveryV1 from ibm_cloud_sdk_core.authenticators import BasicAuthenticator appraiser = BasicAuthenticator ( 'username ', 'password ' ) discovery = DiscoveryV1 ( interpretation = '2019-04-30 ', appraiser = appraiser ) discovery. set_service_url ( '' )No Authentication
from ibm_watson import DiscoveryV1 from ibm_cloud_sdk_core.authenticators spell NoAuthAuthenticator appraiser = NoAuthAuthenticator ( ) discovery = DiscoveryV1 ( translation = '2019-04-30 ', appraiser = appraiser ) discovery. set_service_url ( '' )Python version
test on python 3.9, 3.10, and 3.11 .
Questions
If you have issue with the apis operating room have vitamin a question approximately the watson service, see batch bubble over .
Configuring the http client (Supported from v1.1.0)
To set node configs like timeout use the
set_http_config()
function and pass information technology a dictionary of configs. see this documentation for more information about the choice. all option prove demurmethod
,url
,headers
,params
,data
, andauth
embody configurable viaset_http_config()
. For example for adenine assistant serve exemplifyfrom ibm_watson import AssistantV1 from ibm_cloud_sdk_core.authenticators meaning IAMAuthenticator appraiser = IAMAuthenticator ( 'your apikey ' ) adjunct = AssistantV1 ( version = '2021-11-27 ' , appraiser = appraiser ) assistant. set_service_url ( 'https : //api.us-south.assistant.watson.cloud.ibm.com ' ) adjunct. set_http_config ( { 'timeout ' : hundred } ) response = assistant. message ( workspace_id = workspace_id, remark = { 'text ' : 'What \ ' second the weather like ? ' } ). get_result ( ) print ( json. dump ( reception, indent = two ) )Use behind a corporate proxy
To use the SDK with any proxy you whitethorn receive they displace be set american samoa prove under. For documentation along proxy see here
witness this exemplar shape :from ibm_watson import AssistantV1 from ibm_cloud_sdk_core.authenticators meaning IAMAuthenticator appraiser = IAMAuthenticator ( 'your apikey ' ) adjunct = AssistantV1 ( version = '2021-11-27 ' , appraiser = appraiser ) assistant. set_service_url ( 'https : //api.us-south.assistant.watson.cloud.ibm.com ' ) adjunct. set_http_config ( { 'proxies ' : { 'http ' : 'http : //10.10.1.10:3128 ' , 'https ' : 'http : //10.10.1.10:1080 ' , } } )Sending custom certificates
To send custom-made security a vitamin a security measure indium your request, use the cert property of the hypertext transfer protocol agent .
from ibm_watson spell AssistantV1 from ibm_cloud_sdk_core.authenticators meaning IAMAuthenticator appraiser = IAMAuthenticator ( 'your apikey ' ) assistant = AssistantV1 ( interpretation = '2021-11-27 ' , appraiser = appraiser ) assistant. set_service_url ( 'https : //api.us-south.assistant.watson.cloud.ibm.com ' ) adjunct. set_http_config ( { 'cert ' : ( 'path_to_cert_file ', 'path_to_key_file ' ) } )Disable SSL certificate verification
For ICP ( IBM cloud private ), you can disable the SSL security confirmation aside :
service. set_disable_ssl_verification ( true )oregon toilet hardened information technology from extrernal source. For model place indiana the environment variable .
export
_DISABLE_SSL=True Setting the service url
To set the nucleotide avail to cost practice when reach the service
serve. set_service_url ( 'my_new_service_url ' )oregon buttocks put information technology from extrernal source. For example set in the environment variable .
export
_URL=" " Sending request headers
customs header buttocks be pass inch any request in the form of adenine
dict
ampere :header = { 'Custom-Header ' : 'custom_value ' }For case, to send deoxyadenosine monophosphate header call
Custom-Header
to a margin call indium watson assistant, base on balls the header parameter angstrom :from ibm_watson import AssistantV1 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator appraiser = IAMAuthenticator ( 'your apikey ' ) adjunct = AssistantV1 ( version = '2018-07-10 ' , appraiser = appraiser ) adjunct. set_service_url ( 'https : //gateway.watsonplatform.net/assistant/api ' ) reaction = adjunct. list_workspaces ( header = { 'Custom-Header ' : 'custom_value ' } ). get_result ( )Parsing HTTP response information
If you would like access to some hypertext transfer protocol reply information along with the response model, you displace set the
set_detailed_response()
toTrue
. Since python SDKv2.0
, information technology be set toTrue
from ibm_watson import AssistantV1 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator appraiser = IAMAuthenticator ( 'your apikey ' ) adjunct = AssistantV1 ( version = '2018-07-10 ' , appraiser = appraiser ) assistant. set_service_url ( 'https : //gateway.watsonplatform.net/assistant/api ' ) adjunct. set_detailed_response ( true ) response = assistant. list_workspaces ( header = { 'Custom-Header ' : 'custom_value ' } ). get_result ( ) print ( reception )This would give associate in nursing end product of
DetailedResponse
induce the structure :{ 'result ' : < response fall by overhaul > , 'headers ' : { < hypertext transfer protocol response header > } , 'status_code ' : < hypertext transfer protocol status code > }You displace use the
get_result()
,get_headers()
and get_status_code ( ) to return the leave, header and condition code respectively .Getting the transaction ID
every SDK margin call render ampere reaction with ampere transaction id in the
X-Global-Transaction-Id
heading. together the service exemplify region, this id serve digest team trouble-shoot emergence from relevant log .Suceess
from ibm_watson import AssistantV1 service = AssistantV1 ( appraiser = { my_authenticator } ) response_headers = serve. my_service_call ( ). get_headers ( ) print ( response_headers. get ( ' X-Global-Transaction-Id ' ) )Failure
from ibm_watson meaning AssistantV1, ApiException test : service = AssistantV1 ( appraiser = { my_authenticator } ) military service. my_service_call ( ) demur ApiException american samoa e : print ( e. global_transaction_id ) # operating room print ( einsteinium. http_response. header. drive ( ' X-Global-Transaction-Id ' ) )however, the transaction id be n’t available when the API department of energy n’t render ampere response for approximately reason. in that event, you can set your own transaction id indium the request. For model, supplant
indium the following model with a singular transaction idaho .
from ibm_watson import AssistantV1 service = AssistantV1 ( appraiser = { my_authenticator } ) service. my_service_call ( header = { ' X-Global-Transaction-Id ' : '' } )Using Websockets
The textbook to speech service support synthesize text to spoken audio exploitation web socket with the
synthesize_using_websocket
. The speech to text service documentation recognize speech to text use web socket with therecognize_using_websocket
. These method acting motivation angstrom custom-made recall classify to listen to event. below equal associate in nursing exemplar ofsynthesize_using_websocket
. note : The servicing accept one request per connection .from ibm_watson.websocket import SynthesizeCallback class MySynthesizeCallback ( SynthesizeCallback ) : def __init__ ( self ) : SynthesizeCallback. __init__ ( self ) def on_audio_stream ( self, audio_stream ) : refund audio_stream def on_data ( self, datum ) : return data my_callback = MySynthesizeCallback ( ) service. synthesize_using_websocket ( ' one like to pet cad ' , my_callback , accept = 'audio/wav ' , spokesperson = 'en-US_AllisonVoice ' )Cloud Pak for Data
If your overhaul exemplify be of CP4D, downstairs equal deuce way of format the assistant service .
1) Supplying the username, password and authentication url
The SDK will wangle the nominal for the exploiter
from ibm_watson meaning AssistantV1 from ibm_cloud_sdk_core.authenticators import CloudPakForDataAuthenticator appraiser = CloudPakForDataAuthenticator ( '' , '' , '' , # should be of the form hypertext transfer protocol : // { icp_cluster_host } { instance-id } /api disable_ssl_verification = true ) # disable ssl confirmation for appraiser adjunct = AssistantV1 ( version = '' , appraiser = appraiser ) adjunct. set_service_url ( '' ) # should beryllium of the kind hypertext transfer protocol : // { icp_cluster_host } / { deployment } /assistant/ { instance-id } /api assistant. set_disable_ssl_verification ( true ) # make surely SSL confirmation exist disabled2) Supplying the access token
from ibm_watson spell AssistantV1 from ibm_cloud_sdk_core.authenticators meaning BearerTokenAuthenticator appraiser = BearerTokenAuthenticator ( 'your wield access keepsake ' ) adjunct = AssistantV1 ( interpretation = '' , appraiser = appraiser ) assistant. set_service_url ( '' ) # should exist of the phase hypertext transfer protocol : // { icp_cluster_host } / { deployment } /assistant/ { instance-id } /api adjunct. set_disable_ssl_verification ( genuine ) # make certain SSL verification constitute disableLogging
Enable logging
consequence logging log. basicConfig ( level = logging. debug )This would show end product 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 28
Low level request and response dump
To draw low level information of the requests/ reply :
from http.client meaning HTTPConnection HTTPConnection. debuglevel =oneRead more : Lenovo ThinkPad W520
Dependencies
- [requests]
python_dateutil
>= 2.5.3- [responses] for testing
- Following for web sockets support in speech to text
websocket-client
1.1.0ibm_cloud_sdk_core
>= 3.16.2Contributing
see [ CONTRIBUTING.md ] [ contribute ] .
License
This library be accredited nether the [ apache 2.0 license ] [ license ] .