{"id":13801215,"url":"https://github.com/watson-developer-cloud/ruby-sdk","last_synced_at":"2025-04-07T07:12:27.521Z","repository":{"id":32710644,"uuid":"140028155","full_name":"watson-developer-cloud/ruby-sdk","owner":"watson-developer-cloud","description":":diamonds: Ruby SDK to use the IBM Watson services.","archived":false,"fork":false,"pushed_at":"2024-09-16T12:02:39.000Z","size":6470,"stargazers_count":44,"open_issues_count":1,"forks_count":19,"subscribers_count":15,"default_branch":"master","last_synced_at":"2025-03-31T05:05:15.813Z","etag":null,"topics":["hacktoberfest","ibm-watson","ibm-watson-services","ruby","ruby-gem","rubygem","watson"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/watson-developer-cloud.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":".github/CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-07-06T20:46:16.000Z","updated_at":"2024-03-28T00:57:28.000Z","dependencies_parsed_at":"2024-11-24T13:02:05.897Z","dependency_job_id":"bd71494b-f740-4cb6-8755-6b850affee86","html_url":"https://github.com/watson-developer-cloud/ruby-sdk","commit_stats":{"total_commits":719,"total_committers":14,"mean_commits":"51.357142857142854","dds":0.56884561891516,"last_synced_commit":"d7f4347bc6cd31ee294245fe9e0004c61a8bd12f"},"previous_names":[],"tags_count":55,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/watson-developer-cloud%2Fruby-sdk","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/watson-developer-cloud%2Fruby-sdk/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/watson-developer-cloud%2Fruby-sdk/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/watson-developer-cloud%2Fruby-sdk/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/watson-developer-cloud","download_url":"https://codeload.github.com/watson-developer-cloud/ruby-sdk/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247608153,"owners_count":20965952,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["hacktoberfest","ibm-watson","ibm-watson-services","ruby","ruby-gem","rubygem","watson"],"created_at":"2024-08-04T00:01:20.613Z","updated_at":"2025-04-07T07:12:27.499Z","avatar_url":"https://github.com/watson-developer-cloud.png","language":"Ruby","readme":"# IBM Watson Ruby SDK\n\n[![Build and Test](https://github.com/watson-developer-cloud/ruby-sdk/workflows/Build%20and%20Test/badge.svg?branch=master)](https://github.com/watson-developer-cloud/ruby-sdk/actions?query=workflow%3A\"Build+and+Test\")\n[![Deploy and Publish](https://github.com/watson-developer-cloud/ruby-sdk/workflows/Deploy%20and%20Publish/badge.svg?branch=master)](https://github.com/watson-developer-cloud/ruby-sdk/actions?query=workflow%3A%22Deploy+and+Publish%22)\n[![Slack](https://wdc-slack-inviter.mybluemix.net/badge.svg)](https://wdc-slack-inviter.mybluemix.net)\n[![codecov.io](https://codecov.io/github/watson-developer-cloud/ruby-sdk/coverage.svg)](https://codecov.io/github/watson-developer-cloud/ruby-sdk)\n[![Gem Version](https://badge.fury.io/rb/ibm_watson.svg)](https://badge.fury.io/rb/ibm_watson)\n[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)\n[![CLA assistant](https://cla-assistant.io/readme/badge/watson-developer-cloud/ruby-sdk)](https://cla-assistant.io/watson-developer-cloud/ruby-sdk)\n\n## Deprecated builds\n[![Build Status](https://travis-ci.org/watson-developer-cloud/ruby-sdk.svg)](https://travis-ci.org/watson-developer-cloud/ruby-sdk)\n[![Build status](https://ci.appveyor.com/api/projects/status/ir3k0ue138o4u67e?svg=true)](https://ci.appveyor.com/project/maxnussbaum/ruby-sdk)\n\nRuby gem to quickly get started with the various [IBM Watson][wdc] services.\n\n## Announcements\n### Tone Analyzer Deprecation\n​\nAs of this major release, 3.0.0, the Tone Analyzer api has been removed in preparation for deprecation. If you wish to continue using this sdk to make calls to Tone Analyzer until its final deprecation, you will have to use a previous version.\n​\nOn 24 February 2022, IBM announced the deprecation of the Tone Analyzer service. The service will no longer be available as of 24 February 2023. As of 24 February 2022, you will not be able to create new instances. Existing instances will be supported until 24 February 2023.\n​\nAs an alternative, we encourage you to consider migrating to the Natural Language Understanding service on IBM Cloud. With Natural Language Understanding, tone analysis is done by using a pre-built classifications model, which provides an easy way to detect language tones in written text. For more information, see [Migrating from Watson Tone Analyzer Customer Engagement endpoint to Natural Language Understanding](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-tone_analytics).\n​\n### Natural Language Classifier Deprecation\n​\nAs of this major release, 3.0.0, the NLC api has been removed in preparation for deprecation. If you wish to continue using this sdk to make calls to NLC until its final deprecation, you will have to use a previous version.\n​\nOn 9 August 2021, IBM announced the deprecation of the Natural Language Classifier service. The service will no longer be available from 8 August 2022. As of 9 September 2021, you will not be able to create new instances. Existing instances will be supported until 8 August 2022. Any instance that still exists on that date will be deleted.\n​\nAs an alternative, we encourage you to consider migrating to the Natural Language Understanding service on IBM Cloud that uses deep learning to extract data and insights from text such as keywords, categories, sentiment, emotion, and syntax, along with advanced multi-label text classification capabilities, to provide even richer insights for your business or industry. For more information, see [Migrating to Natural Language Understanding](https://cloud.ibm.com/docs/natural-language-classifier?topic=natural-language-classifier-migrating).\n\n### Support for 2.7 ruby\nTo support 2.7 the http gem dependency is updated to 4.4.0. Since it conflicted with the dependency in the ruby-sdk-core that gem was also updated.  Using 2.0.2 or above ruby sdk will require a core of 1.1.3 or above.\n\n### Updating endpoint URLs from watsonplatform.net\nWatson API endpoint URLs at watsonplatform.net are changing and will not work after 26 May 2021. Update your calls to use the newer endpoint URLs. For more information, see https://cloud.ibm.com/docs/watson?topic=watson-endpoint-change.\n\n## Before you begin\n\n* You need an [IBM Cloud][ibm-cloud-onboarding] account.\n\n## Installation\n\nInstall the gem:\n\n```bash\ngem install ibm_watson\n```\n\nInstall with development dependencies:\n\n```bash\ngem install --dev ibm_watson\n```\n\nInside of your Ruby program do:\n\n```ruby\nrequire \"ibm_watson\"\n```\n\n## Examples\n\nThe [examples][examples] folder has basic and advanced examples. The examples within each service assume that you already have [service credentials](#getting-credentials).\n\n## Running in IBM Cloud\n\nIf you run your app in IBM Cloud, the SDK gets credentials from the [`VCAP_SERVICES`][vcap_services] environment variable.\n\n## Authentication\n\nWatson services are migrating to token-based Identity and Access Management (IAM) authentication.\n\n* With some service instances, you authenticate to the API by using **[IAM](#iam)**.\n* In other instances, you authenticate by providing the **[username and password](#username-and-password)** for the service instance.\n\n### Getting credentials\n\nTo find out which authentication to use, view the service credentials. You find the service credentials for authentication the same way for all Watson services:\n\n1. Go to the IBM Cloud [Dashboard](https://cloud.ibm.com/) page.\n1. Either click an existing Watson service instance in your [resource list](https://cloud.ibm.com/resources) or click [**Create resource \u003e AI**](https://cloud.ibm.com/catalog?category=ai) and create a service instance.\n1. Click on the **Manage** item in the left nav bar of your service instance.\n\n On this page, you should be able to see your credentials for accessing your service instance.\n\n### Supplying credentials\n\n There are two ways to supply the credentials you found above to the SDK for authentication.\n\n#### Credential file (easier!)\n\nWith 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 the **Download** button for the credentials in the **Manage** tab of your service instance.\n\nThe file downloaded will be called `ibm-credentials.env`. This is the name the SDK will search for and **must** be preserved unless you want to configure the file path (more on that later). The SDK will look for your `ibm-credentials.env` file in the following places (in order):\n\n* The top-level directory of the project you're using the SDK in\n* Your system's home directory\n\n As 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:\n\n ```ruby\ndiscovery = DiscoveryV1(version: \"2018-08-01\")\n```\n\n And that's it! \n\n If you're using more than one service at a time in your code and get two different `ibm-credentials.env` files, just put the contents together in one `ibm-credentials.env` file and the SDK will handle assigning credentials to their appropriate services.\n\n If you would like to configure the location/name of your credential file, you can set an environment variable called `IBM_CREDENTIALS_FILE`. **This will take precedence over the locations specified above.** Here's how you can do that:\n\n ```bash\nexport IBM_CREDENTIALS_FILE=\"\u003cpath\u003e\"\n```\n\n where `\u003cpath\u003e` is something like `/home/user/Downloads/\u003cfile_name\u003e.env`.\n\n#### Manually\n\nIf 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.\n\n### IAM\n\nIBM Cloud is migrating 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.\n\nYou supply either an IAM service **API key** or an **access token**:\n\n* 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.\n* Use the access token if you want to manage the lifecycle yourself. For details, see [Authenticating with IAM tokens](https://cloud.ibm.com/docs/watson?topic=watson-iam).\n\n#### Supplying the IAM API key\n\n```ruby\n# In the constructor, letting the SDK manage the IAM token\nauthenticator = IBMWatson::Authenticators::IamAuthenticator.new(\n  apikey: \"\u003ciam_apikey\u003e\",\n  url: \"\u003ciam_url\u003e\" # optional - the default value is https://iam.cloud.ibm.com/identity/token\n)\ndiscovery = IBMWatson::DiscoveryV1.new(\n  version: \"2017-10-16\",\n  authenticator: authenticator\n)\ndiscover.service_url = \"\u003cservice-url\u003e\" # setting service url\n```\n\n#### Supplying the access token\n\n```ruby\nauthenticator = IBMWatson::Authenticators::BearerTokenAuthenticator.new(\n  bearer_token: \"\u003caccess_token\u003e\"\n)\ndiscovery = IBMWatson::DiscoveryV1.new(version: \"2017-10-16\", authenticator)\n```\n\n### Username and password\n\n```ruby\nrequire \"ibm_watson\"\nrequire \"ibm_cloud_sdk_core\"\ninclude IBMWatson\n# In the constructor\nauthenticator = IBMWatson::Authenticators::BasicAuthenticator.new(\n  username: \"\u003cusername\u003e\",\n  password: \"\u003cpassword\u003e\"\n)\ndiscovery = DiscoveryV1.new(\n  version: \"2017-10-16\",\n  authenticator: authenticator\n)\n```\n\n## Sending requests asynchronously\n\nRequests can be sent asynchronously. There are two asynchronous methods available for the user, `async` \u0026 `await`. When used, these methods return an [Ivar][ivar] object.\n\n* To call a method asynchronously, simply insert `.await` or `.async` into the call: `service.translate` would be `service.async.translate`\n* To access the response from an [Ivar][ivar] object called `future`, simply call `future.value`\n\nWhen `await` is used, the request is made synchronously.\n\n```ruby\nauthenticator = IBMWatson::Authenticators::BasicAuthenticator.new(\n  username: \"\u003cusername\u003e\",\n  password: \"\u003cpassword\u003e\"\n)\n\nspeech_to_text = IBMWatson::SpeechToTextV1.new(\n  authenticator: authenticator\n)\naudio_file = File.open(Dir.getwd + \"/resources/speech.wav\")\nfuture = speech_to_text.await.recognize(\n  audio: audio_file\n)\np future.complete? # If the request is successful, then this will be true\noutput = future.value # The response is accessible at future.value\n```\n\nWhen `async` is used, the request is made asynchronously\n\n```ruby\nauthenticator = IBMWatson::Authenticators::BasicAuthenticator.new(\n  username: \"\u003cusername\u003e\",\n  password: \"\u003cpassword\u003e\"\n)\n\nspeech_to_text = IBMWatson::SpeechToTextV1.new(\n  authenticator: authenticator\n)\naudio_file = File.open(Dir.getwd + \"/resources/speech.wav\")\nfuture = speech_to_text.async.recognize(\n  audio: audio_file\n)\np future.complete? # Can be false if the request is still running\nfuture.wait # Wait for the asynchronous call to finish\np future.complete? # If the request is successful, then this will now be true\noutput = future.value\n```\n\n## Sending request headers\n\nCustom headers can be passed in any request in the form of a `Hash` as a parameter to the `headers` chainable method. For example, to send a header called `Custom-Header` to a call in Watson Assistant, pass the headers as a parameter to the `headers` chainable method:\n\n```ruby\nrequire \"ibm_watson\"\ninclude IBMWatson\n\nassistant = AssistantV1.new(\n  authenticator: \"\u003cauthenticator\u003e\"\n  version: \"2017-04-21\"\n)\n\nresponse = assistant.headers(\n  \"Custom-Header\" =\u003e \"custom_value\"\n  ).list_workspaces\n```\n\n## Parsing HTTP response info\n\nHTTP requests all return `DetailedResponse` objects that have a `result`, `status`, and `headers`\n\n```ruby\nrequire \"ibm_watson\"\ninclude IBMWatson\n\nassistant = AssistantV1.new(\n  authenticator: \"\u003cauthenticator\u003e\"\n  version: \"2017-04-21\"\n)\n\nresponse = assistant.headers(\n  \"Custom-Header\" =\u003e \"custom_value\"\n  ).list_workspaces\n\np \"Status: #{response.status}\"\np \"Headers: #{response.headers}\"\np \"Result: #{response.result}\"\n```\n\nThis would give an output of `DetailedResponse` having the structure:\n\n```ruby\nStatus: 200\nHeaders: \"\u003chttp response headers\u003e\"\nResult: \"\u003cresponse returned by service\u003e\"\n```\n\n### Transaction IDs\n\nEvery SDK call returns a response with a transaction ID in the `X-Global-Transaction-Id` header. Together the service instance region, this ID helps support teams troubleshoot issues from relevant logs.\n\n```ruby\nrequire \"ibm_watson\"\ninclude IBMWatson\n\nassistant = AssistantV1.new(\n  authenticator: \"\u003cauthenticator\u003e\"\n  version: \"2017-04-21\"\n)\n\nbegin\n  response = assistant.list_workspaces\n  p \"Global transaction id: #{response.headers[\"X-Global-Transaction-Id\"]}\"\nrescue IBMCloudSdkCore::ApiException =\u003e e\n  # Global transaction on failed api call is contained in the error message\n  print \"Error: ##{e}\"\nend\n```\n\nHowever, 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 `\u003cmy-unique-transaction-id\u003e` in the following example with a unique transaction ID.\n\n```ruby\nrequire \"ibm_watson\"\ninclude IBMWatson\n\nassistant = AssistantV1.new(\n  authenticator: \"\u003cauthenticator\u003e\"\n  version: \"2017-04-21\"\n)\n\nresponse = assistant.headers(\n  \"X-Global-Transaction-Id\" =\u003e \"\u003cmy-unique-transaction-id\u003e\"\n  ).list_workspaces\n```\n\n## Configuring the HTTP client\n\nTo set client configs like timeout or proxy use the `configure_http_client` function and pass in the configurations.\n\n```ruby\nrequire \"ibm_watson/assistant_v1\"\ninclude IBMWatson\n\nassistant = AssistantV1.new(\n  authenticator: \"\u003cauthenticator\u003e\"\n  version: \"2018-07-10\"\n)\n\nassistant.configure_http_client(\n  timeout: {\n    # Accepts either :per_operation or :global\n    per_operation: { # The individual timeouts for each operation\n      read: 5,\n      write: 7,\n      connect: 10\n    }\n    # global: 30 # The total timeout time\n  },\n  proxy: {\n    address: \"bogus_address.com\",\n    port: 9999,\n    username: \"username\",\n    password: \"password\",\n    headers: {\n      bogus_header: true\n    }\n  }\n)\n```\n\nThe HTTP client can be configured to disable SSL verification. Note that this has serious security implications - only do this if you really mean to! ⚠️\n\nTo do this, pass `disable_ssl_verification` as `true` in `configure_http_client()`, like below:\n\n```ruby\nrequire \"ibm_watson/assistant_v1\"\ninclude IBMWatson\n\nservice = AssistantV1.new(\n  version: \"\u003cversion\u003e\",\n  authenticator: \"\u003cauthenticator\u003e\"\n)\n\nservice.configure_http_client(disable_ssl_verification: true)\n```\n\n## Using Websockets\n\nThe Speech-to-Text service supports websockets with the `recognize_using_websocket` method. The method accepts a custom callback class. The `eventmachine` loop that the websocket uses blocks the main thread by default. Here is an example of using the websockets method:\n\n```ruby\nrequire \"ibm_watson\"\n\ncallback = IBMWatson::RecognizeCallback.new\naudio_file = \"\u003cAudio File for Analysis\u003e\"\nspeech_to_text = IBMWatson::SpeechToTextV1.new(\n  username: \"\u003cusername\u003e\",\n  password: \"\u003cpassword\u003e\"\n)\nwebsocket = speech_to_text.recognize_using_websocket(\n  audio: audio_file,\n  recognize_callback: callback,\n  interim_results: true\n)\nthr = Thread.new do # Start the websocket inside of a thread\n  websocket.start # Starts the websocket and begins sending audio to the server.\n  # The `callback` processes the data from the server\nend\nthr.join # Wait for the thread to finish before ending the program or running other code\n```\n\nNote: `recognize_with_websocket` has been **deprecated** in favor of **`recognize_using_websocket`**\n\n## IBM Cloud Pak for Data(CP4D)\n\nIf your service instance is of ICP4D, below are two ways of initializing the assistant service.\n\n### Supplying the `username`, `password`, and `url`\n\nThe SDK will manage the token for the user\n\n```ruby\n\nauthenticator = IBMWatson::Authenticators::CloudPakForDataAuthenticator.new(\n  username: \"\u003cusername\u003e\",\n  password: \"\u003cpassword\u003e\",\n  url: \"\u003cauthentication url\u003e\",\n  disable_ssl: true\n)\nassistant = IBMWatson::AssistantV1.new(\n  version: \"\u003cversion\u003e\",\n  authenticator: authenticator\n)\n\n```\n\n## Questions\n\nIf you have issues with the APIs or have a question about the Watson services, see [Stack Overflow](https://stackoverflow.com/questions/tagged/ibm-watson+ruby).\n\n## Ruby version\n\nTested on:\n\n* MRI Ruby (RVM): 2.5.1, 2.6.1\n* RubyInstaller (Windows x64): 2.5.1, 2.6.1\n\n2.3.7 and 2.4.4 should still work but support will be deprecated in next major release.\n\n## Contributing\n\nSee [CONTRIBUTING.md][CONTRIBUTING].\n\n## License\n\nThis library is licensed under the [Apache 2.0 license][license].\n\n## Featured projects\n\nHere are some projects that have been using the SDK:\n\n* [GuardianCity](https://github.com/TalentoBogotaFedesoft/ULIBRE-061-grupo-2)\n\nWe'd love to highlight cool open-source projects that use this SDK! If you'd like to get your project added to the list, feel free to make an issue linking us to it.\n\n[wdc]: http://www.ibm.com/watson/developercloud/\n[ibm_cloud]: https://cloud.ibm.com/\n[watson-dashboard]: https://cloud.ibm.com/catalog?category=ai\n[examples]: https://github.com/watson-developer-cloud/ruby-sdk/tree/master/examples\n[CONTRIBUTING]: https://github.com/watson-developer-cloud/ruby-sdk/blob/master/CONTRIBUTING.md\n[license]: http://www.apache.org/licenses/LICENSE-2.0\n[vcap_services]: https://cloud.ibm.com/docs/watson?topic=watson-vcapServices\n[ibm-cloud-onboarding]: http://cloud.ibm.com/registration?target=/developer/watson\u0026cm_sp=WatsonPlatform-WatsonServices-_-OnPageNavLink-IBMWatson_SDKs-_-Ruby\n[ivar]: http://ruby-concurrency.github.io/concurrent-ruby/Concurrent/IVar.html\n","funding_links":[],"categories":["Data \u0026 AI"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwatson-developer-cloud%2Fruby-sdk","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwatson-developer-cloud%2Fruby-sdk","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwatson-developer-cloud%2Fruby-sdk/lists"}