vania-janet/multiturn-rag-retrieval-data huggingface dataset:
The response body to return depends on the method; see [Methods](https://cloud.ibm.com/docs/api-handbook?topic=api-handbook-methods) for more details. 
 201 [Created](https://datatracker.ietf.org/doc/html/rfc7231section-6.3.2) This code MUST be returned when a new resource was successfully created in a synchronous manner. When returning this code, the server MUST also return a Location header with the URI of the created resource. Depending on the Prefer header, a representation of the resource MAY be included in the response body; see the [POST section](https://cloud.ibm.com/docs/api-handbook?topic=api-handbook-methodspost) for more details. 
 202 [Accepted](https://datatracker.ietf.org/doc/html/rfc7231section-6.3.3) This code MUST be returned when the request will be processed asynchronously, and may be rejected when it's actually processed. A resource representing the status of the request SHOULD be included in the response, and the response Location header SHOULD include a URI where this same status may be retrieved so that the client may stay up-to-date. 
 204 [No Content](https://datatracker.ietf.org/doc/html/rfc7231section-6.3.5) This code MUST be returned when the server successfully processed the request and is not returning any content. This MAY be used for DELETE requests or requests where the client includes a Prefer header containing return=minimal. It MAY occasionally be used for PUT or POST requests where it is impractical to return a resource representation because of size or cost, or for GET requests where a resource exists but has an empty representation. 
 206 [Partial Content](https://datatracker.ietf.org/doc/html/rfc7233section-4.1) This code indicates that the server is delivering only part of the resource. Servers MUST use this when enabling the client to resume interrupted downloads, or to split a download into multiple simultaneous streams.<br><br>[2] 





 Requests requiring no action
result: true,
params: {}
});
})
.catch((error) => {
console.log('An error occurred! ' + JSON.stringify(error));
// IMPORTANT! Re-throw the error, to avoid following .then() block to be executed!
throw error;
})
.then((result) => {
console.log('Result from db-access ' + JSON.stringify(result));

// storing result
chained_action_results.push(result);

console.log('Now invoking cos-access...');

return ow.actions.invoke({
name: 'action-tutorial/cos-access',
blocking: true,
result: true,
params: {}
});
})
.catch((error) => {
console.log('An error occurred! ' + JSON.stringify(error));
// IMPORTANT! Re-throw the error, to avoid following .then() block to be executed!
throw error;
})
.then((result) => {
console.log('Result from cos-access ' + JSON.stringify(result));

// storing result
chained_action_results.push(result);

console.log('Custom SEQUENCE with openwhisk-node-js-sdk completed.');

// returning the result here, makes sure that the top-most promise, we returned in main() returns the combined results of all
// chained action invokes

// since the result needs to be a valid JSON object, we cannot directly return the array, so we wrap it
return {
action_results: chained_action_results
};
})
.catch((error) => {
console.log('An error occurred! ' + JSON.stringify(error));
.getResult();

System.out.println(response);

const { CloudantV1 } = require('@ibm-cloud/cloudant');

const service = CloudantV1.newInstance({});

service.postView({
db: 'users',
ddoc: 'allusers',
view: 'getVerifiedEmails',
keys: ['amelie.smith@aol.com', 'bob.smith@aol.com']
}).then(response => {
console.log(response.result);
});

from ibmcloudant.cloudant_v1 import CloudantV1

service = CloudantV1.new_instance()

response = service.post_view(
db='users',
ddoc='allusers',
view='getVerifiedEmails',
keys=['amelie.smith@aol.com', 'bob.smith@aol.com']
).get_result()

print(response)

postViewOptions := service.NewPostViewOptions(
"users",
"allusers",
"getVerifiedEmails",
)

keys := []interface{}{"amelie.smith@aol.com", "bob.smith@aol.com"}
postViewOptions.SetKeys(keys)

viewResult, response, err := service.PostView(postViewOptions)
if err != nil {
panic(err)
}

b, _ := json.MarshalIndent(viewResult, "", " ")
fmt.Println(string(b))

The previous Go example requires the following import block:

import (
"encoding/json"
"fmt"
"github.com/IBM/cloudant-go-sdk/cloudantv1"
)

All Go examples require the service object to be initialized.
resolve({ cloudant_result: 'SUCCESS' });
}, 5000);
});
}
Show more
6. Click Save.
7. Test your action by clicking Invoke and waiting for the following output to display.

Example output

Results:
{
"cloudant_result": "SUCCESS"
}

Logs:
[
"2020-04-21T01:53:36.739565Z stdout: fake db access done. Resolving Promise..."
]





Your db-access action is ready!





 Step 3: Create the ow-sdk-action actionow-sdk-action action 

The ow-sdk-action action is a Node.js program that calls the other two actions: cos-access and db-access. When invoked, the ow-sdk-action action code acts as a custom sequence, first calling cos-access, then db-access, and finally cos-access again. The results of each action are stored in a variable that is called chained_action_results, which is then returned at the end. When the action is invoked, follow the code comments to see what is happening.



1. From the Actions page, create a third action called ow-sdk-action.



1. Name your action ow-sdk-action.
2. Select the action-tutorial package.
3. Select Node.js 10 for the runtime.
4. Click Create.
5. Paste in the following code example:

/
* main() will be run when you invoke this action
* @param Cloud Functions actions accept a single parameter, which must be a JSON object.
* @return The output of this action, which must be a JSON object.
/
const openwhisk = require('openwhisk');
const ow = openwhisk();

function main(params) {
// for demonstration purposes, we keep track of the individual results of each action that we invoke in our
update Specify whether or not the view in question must be updated before you respond to the user.<br><br><br><br> * true - Return results after the view is updated.<br> * false - Return results without updating the view.<br> * lazy - Return the view results without waiting for an update, but update them immediately after the request.<br><br><br> Yes String True Yes 



Using include_docs=true might have [performance implications](https://cloud.ibm.com/docs/Cloudant?topic=Cloudant-using-viewsmulti-document-fetching).

See the example of using HTTP to retrieve a list of the first 10 documents that include the full content of the documents from a partition of a database, applying a user-created view.

GET $SERVICE_URL/$DATABASE/_partition/$PARTITION_KEY/_design/$DDOC/_view/$VIEW_NAME?include_docs=true&limit=10 HTTP/1.1

See the example of using HTTP to retrieve a list of the first 10 documents from a database, applying a user-created view.

GET $SERVICE_URL/$DATABASE/_design/$DDOC/_view/$VIEW_NAME?limit=10 HTTP/1.1

See the example to retrieve a list of the first 10 documents that include the full content of them from the small-appliances partition of a database, applying the user-created byApplianceProdId view.

Client libraries use POST method instead of GET because they have the same behavior.



* Curl
* Java
* Node
* Python
* Go



curl -X GET "$SERVICE_URL/products/_partition/small-appliances/_design/appliances/_view/byApplianceProdId?include_docs=true&limit=10"

import com.ibm.cloud.cloudant.v1.Cloudant;
import com.ibm.cloud.cloudant.v1.model.PostPartitionViewOptions;
import com.ibm.cloud.cloudant.v1.model.ViewResult;

Cloudant service = Cloudant.newInstance();
return {payload: 'Hello, World!'};
} else if (params.payload == 2) {
return {error: 'payload must be 0 or 1'};
}
}





 Structuring JavaScript code with asynchronous behavior 

JavaScript functions can continue to run in a callback function even after a return. The JavaScript activation is asynchronous if the main function exits by returning a promise. In this case, the system assumes that the action is still running until the promise is fulfilled or rejected. JavaScript functions that run asynchronously can return the activation result after the main function returns by returning a promise in your action.

Start by instantiating a new promise object and passing a callback function. The callback takes two arguments, resolve and reject, which are both functions. All your asynchronous code goes inside that callback. The action handler can have any name that conforms to the conventional signature of accepting an object and returning an object (or a Promise of an object).

In the following example, you can see how to fulfill a promise by calling the resolve function.

function main(args) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve({ done: true });
}, 2000);
})
}

This example shows how to reject a promise by calling the reject function.

function main(args) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
reject({ done: true });
}, 2000);
})
}

In the examples, the following details are executed.



* The main function returns a promise. The promise indicates that the activation isn't completed yet but is expected to in the future.
* The setTimeout() JavaScript function waits for 2 seconds before it calls the promise's callback function, which represents the asynchronous code.
* The promise's callback accepts the arguments resolve and reject, which are both functions.
.execute()
.getResult();

while (response.getRows().size() > 1) {
List<DocsResultRow> responseDocuments = response.getRows();
// on the last page, show all documents:
if (responseDocuments.size() <= pageSize) {
System.out.println(responseDocuments);
} else { // otherwise, hide the last document:
System.out.println(responseDocuments.subList(0, pageSize));
}
// The startKey of the next request becomes the hidden document id:
docsOptionsBuilder
.startKey(responseDocuments
.get(responseDocuments.size() - 1)
.getId()
);
response =
service.postAllDocs(docsOptionsBuilder.build())
.execute()
.getResult();
}
const { CloudantV1 } = require('@ibm-cloud/cloudant');

const service = CloudantV1.newInstance({});

async function paginate(pageSize) {
let allDocsResult = (await service.postAllDocs({
db: 'orders',
limit: pageSize + 1
})).result;
while(allDocsResult.rows.length > 1) {
let documents = allDocsResult.rows;
// on the last page, show all documents:
if(documents.length <= pageSize) {
console.log(documents);
} else { // otherwise, hide the last document:
console.log(documents.slice(0, documents.length - 1))
}
allDocsResult = (await service.postAllDocs({
db: 'orders',
limit: pageSize + 1,
startKey: documentsdocuments.length - 1] .id
})).result;
}
name=serviceid_name
).get_result()

print(json.dumps(service_id_list, indent=2))

listServiceIdsOptions := iamIdentityService.NewListServiceIdsOptions()
listServiceIdsOptions.SetAccountID(accountID)
listServiceIdsOptions.SetName(serviceIDName)

serviceIDList, response, err := iamIdentityService.ListServiceIds(listServiceIdsOptions)
if err != nil {
panic(err)
}
b, _ := json.MarshalIndent(serviceIDList, "", " ")
fmt.Println(string(b))

const params = {
accountId: accountId,
name: serviceIdName,
};

try {
const res = await iamIdentityService.listServiceIds(params)
console.log(JSON.stringify(res.result, null, 2));
} catch (err) {
console.warn(err);
}
3. Extract the value of the crn field from the response.

{
"offset": 0,
"limit": 1,
"first": {
"href": "https://iam.cloud.ibm.com/v1/serviceids?account_id=accountId"
},
"next": {
"href": "https://iam.cloud.ibm.com/v1/serviceids?pagetoken=pageToken"
},
"serviceids": {
"id": "ServiceId-ee1103f8-e03b-4d02-a977-e540ebdffb16",
// returning the result here, makes sure that the top-most promise, we returned in main() returns the combined results of all
// chained action invokes

// since the result needs to be a valid JSON object, we cannot directly return the array, so we wrap it
return {
action_results: chained_action_results
};
})
.catch((error) => {
console.log('An error occurred! ' + JSON.stringify(error));

console.log('Custom SEQUENCE with openwhisk-node-js-sdk FAILED');

// This last throw is absolutely important to make the top-most promise, which we initially returned at the
// top of the main() function REJECTS with the given error. If we did not throw here, it would still RESOLVE
// even though the code herein failed.
throw error;
});
}
Show more
6. Click Save.
7. Test your action by clicking Invoke and waiting for the following output to display.

Example output

Results:
{
"action_results": [
{
"cos_message": "SUCCESS"
},
{
"cloudant_result": "SUCCESS"
},
{
"cos_message": "SUCCESS"
}
]
}

Logs:
[
"2020-04-17T04:31:20.965176Z stdout: Building custom sequence, using openwhisk node-js SDK...",
"2020-04-17T04:31:31.670466Z stdout: Result from cos-access {"cos_message":"SUCCESS"}",
"2020-04-17T04:31:31.670501Z stdout: Now invoking db-access...",
In the examples, the following details are executed.



* The main function returns a promise. The promise indicates that the activation isn't completed yet but is expected to in the future.
* The setTimeout() JavaScript function waits for 2 seconds before it calls the promise's callback function, which represents the asynchronous code.
* The promise's callback accepts the arguments resolve and reject, which are both functions.



* The call to resolve() fulfills the promise and indicates that the activation completes normally.
* A call to reject() can be used to reject the promise and signal that the activation completes abnormally.









 Structuring JavaScript code with synchronous and asynchronous behavior 

An action can be synchronous on some inputs and asynchronous on others, as shown in the following example.

function main(params) {
if (params.payload) {
// asynchronous activation
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve({ done: true });
}, 2000);
})
} else {
// synchronous activation
return {done: true};
}
}





 Example: Calling an external API with JavaScript 

The following example invokes the external API for the NASA Astronomy Picture of the Day (APOD) service, which provides a unique image of our universe every day.

let rp = require('request-promise')

function main(params) {
const options = {
uri: "https://api.nasa.gov/planetary/apod?api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo",
json: true
}
return rp(options)
.then(res => {
return { response: res }
})
}

A call is made to the NASA APOD API, and fields are extracted from the JSON result.
let callBack:BMSCompletionHandler = {(response: Response?, error: NSError?) in
if error == nil {
print ("Response: (response?.responseText), no error")
} else {
print ("Error: (error)")
}
}
request.send(completionHandler: callBack)



The Request class is a simple way to make an HTTP request and get the response after the request is completed. If you want more flexibility and control than what you can get from the Request class, you can use the BMSURLSession class. Some features of the BMSURLSession class include monitoring progress of uploads, and pausing or canceling requests. To get the responses, you can select either completion handlers or delegates.

The BMSURLSession class is available for iOS only.

For complete usage examples, see the BMSCore GitHub [README](https://github.com/ibm-bluemix-mobile-services/bms-clientsdk-swift-core).





 Cordova 



1. Make sure that you have [imported the Client SDK and initialized it](https://cloud.ibm.com/docs/cli/sdk?topic=cli-sdk_BMSClientinit-BMSClient-cordova) in your Cordova app.
2. Create a network request.

var success = function(data) {
console.log("success", data);
}
var failure = function(error)
{console.log("failure", error);
}
var request = new BMSRequest("<your application route>", BMSRequest.GET);
request.send(success, failure);
).get_result()['session_id']

 {: codeblock java}

CreateSessionOptions createSessionOptions = new CreateSessionOptions.Builder(assistantId).build(); SessionResponse session = service.createSession(createSessionOptions).execute().getResult(); String sessionId = session.getSessionId();

1. Use the v2 [Send user input to assistant](https://cloud.ibm.com/apidocs/assistant/assistant-v2message){: external} method to send user input to the assistant. Instead of specifying the workspace ID as you did with the v1 API, you specify the assistant ID and the session ID:

 {: codeblock javascript}
service
.message({
assistant_id: assistantId,
session_id: sessionId,
input: messageInput
})

 {: codeblock python}

response = service.message( assistant_id, session_id, input = message_input ).get_result()

 {: codeblock java}
MessageInput input = new MessageInput.Builder().text(inputText).build();
MessageOptions messageOptions = new MessageOptions.Builder(assistantId, sessionId)
.input(input)
.build();
MessageResponse response = service.message(messageOptions)
.execute()
.getResult();

The basic message structure has not changed; in particular, the user input is still sent as input.text.



1. After a conversation ends, use the v2 [Delete session](https://cloud.ibm.com/apidocs/assistant/assistant-v2deletesession) method to delete the session.



service .deleteSession({ assistant_id: assistantId, session_id: sessionId, })

 {: codeblock python}
service.delete_session(
assistant_id = assistant_id,
session_id = session_id
)
For example, an action <namespace_ID>/demo/hello is referenced as <namespace_ID>/demo/hello.json to receive a .json response. \n For content type .json, the full return object is returned, similar to {resOne: "some text", resTwo: 42}. \n For .html, .svg, or .text, the content of the property that is called body is returned, similar to .http. If you want to use one response object for multiple content types, you can add the corresponding properties into the return object and remove the body property. The return object is then similar to {html: "<p>The html response</p>", text: "text response"}. \n If no content type is specified, the .http extension is assumed, and the content of the property that is called body is returned, for example, {body: "the return message"}.





 Query and body parameters as input 

The action receives query parameters as well as parameters in the request body. The precedence order for merging parameters is: package parameters, action parameters, query parameter, and body parameters. Each of these parameters can override any previous values if overlap occurs. As an example, /demo/hello.http?name=Jane can pass the argument {name: "Jane"} to the action.





 Form data 

In addition to the standard application/json, web actions can receive URL encoded form data application/x-www-form-urlencoded data as input.





 Activations that use multiple HTTP verbs 

A web action can be invoked through any of these HTTP methods: GET, POST, PUT, PATCH, and DELETE, as well as HEAD and OPTIONS.





 Non-JSON body and raw HTTP entity handling 

A web action can accept an HTTP request body other than a JSON object, and can elect to always receive such values as opaque values (plain text when not binary file, or base64 encoded string otherwise).







 Creating a web action 

To create a web action:



1. Save the following JavaScript code as hello.js.

function main({name}) {
var msg = 'You did not tell me who you are.'
findOptions.bookmark(response.getBookmark());
response = service.postFind(findOptions.build()).execute().getResult();
}
const { CloudantV1 } = require('@ibm-cloud/cloudant');

const service = CloudantV1.newInstance({});

async function paginate(pageSize) {
let requestParams = {
db: 'cities',
selector: {country: {'$eq': 'US'}},
limit: pageSize,
}
let findResult = (await service.postFind(requestParams)).result;
while (findResult.docs.length > 0) {
let documents = findResult.docs;
console.log(documents);
// The bookmark of the next request becomes the bookmark of this response
requestParams.bookmark = findResult.bookmark;
findResult = (await service.postFind(requestParams)).result;
}
}

paginate(5)
request_params = dict(
db='cities',
selector={'country': {'$eq': 'US'}},
limit=5,
)
response = service.post_find(request_params).get_result()

while len(response'docs']) > 0:
documents = response'docs']
print(json.dumps(documents, indent=2))
 The bookmark of the next request becomes the bookmark of this response
request_params'bookmark'] = response'bookmark']
response = service.post_find(request_params).get_result()
findOptions := service.NewPostFindOptions(
"cities",
mapstring]interface{}{
"country": mapstring]!!! bool{
"$eq": "US",
It doesn't return any state to host and returns only result. This function is an IBM EP11 extension to the standard PKCS #11 specification and is a combination of the SignInit and Sign functions. It enables you to complete a signing operation with a single call instead of a series of calls.

Enterprise PKCS #11 over gRPC

Enterprise PKCS #11





 Description Binds to EP11 m_SignSingle. 
 Parameters message SignSingleRequest { bytes PrivKey = 1; Mechanism Mech = 2; bytes Data = 3; } message SignSingleResponse { bytes Signature = 4; } 
 Return values Wraps EP11 error into message Grep11Error. 



Code snippets



* Golang code snippet

msgHash := sha256.Sum256([]byte("This data needs to be signed"))
SignSingleRequest := &pb.SignSingleRequest {
PrivKey: GenerateKeyPairResponse.PrivKeyBytes,
Mech: &pb.Mechanism{Mechanism: ep11.CKM_SHA256_RSA_PKCS},
Data: msgHash[:],
}

SignSingleResponse, err := cryptoClient.SignSingle(context.Background(), SignSingleRequest)
* JavaScript code snippet

client.SignSingle({
Mech: {
Mechanism: ep11.CKM_ECDSA
},
PrivKey: key,
Data: digest
}, (err, response) => {
callback(err, response);
});







 VerifyInit 

The VerifyInit function initializes a verification operation. You need to call this function first to verify a signature.

Enterprise PKCS #11 over gRPC

Enterprise PKCS #11

PKCS #11





 Description Binds to EP11 m_VerifyInit, which is an implementation of PKCS #11 C_VerifyInit.
Any response made by the callout is saved to the return variable. You can rename the variable that is automatically added to the Return variable field for you. If the callout results in an error, this variable is set to null.

The generated variable name has the syntax webhook_result_n, where the appended _n is incremented each time you add a webhook callout to a dialog node. This naming convention ensures that context variable names are unique across the dialog skill. If you change the name, be sure to use a unique name.
7. In the conditional responses section, two response conditions are added automatically, one response to show when the webhook callout is successful and a return variable is sent back. And one response to show when the callout fails. You can edit these responses, and add more conditional responses to the node.



* If the callout returns a response, and you know the format of the JSON response, then you can edit the dialog node response to include only the section of the response that you want to share with users.

For example, the Language Translator service returns an object like this:

{
"translations":[
{"translation":"¿Cómo estás?"}
],
"word_count":3,
"character_count":12
}

Use a SpEL expression that extracts only the translated text value.



Conditional responses example

 Condition Response 

 $webhook_result_1 Your words in Spanish: . 
 anything_else The call to the external application failed. Please try again later. 



If you use the recommended format for the response and the translation response shown earlier is returned, the assistant's response to the user would be: Your words in Spanish: ¿Cómo estás?
* If you want to provide a specific response if the callout returns an empty string, meaning the call is successful, but the value returned is an empty string, you can add a conditional response that has a condition with syntax like this:

$webhook_result_1.size() == 0



8. When you are done, click the X to close the node. Your changes are automatically saved.