我想在使用obj-c编写的应用程序中使用对话框流服务。使用api.ai库已有一段时间了,但似乎找不到用于对话框流v2(beta1) apis的obj-c库。我的代理已经升级到v2,但是api.ai内部使用的是/v1/端点,我需要使用特定于v2beta1的特性,比如访问知识库。(https://cloud.google.com/dialogflow/docs/reference/rpc/google.cloud.dialogflow.v2beta1#queryparameters - knowledge_base_names)。对话框流API是一个标准的REST,所以我所需要的只是OAuth2.0 & REST客户端,但是编写代码听起来就像重新发明轮子。
请指点。谢谢
发布于 2020-02-08 21:33:17
我不认为有专门为Dialogflow v2编写的库;但是,库google-api-objectivec-client-for-rest是谷歌提供的一个通用库,它简化了使用Rest的代码。
此库将被更新以与对话框V2一起使用。为了使用它,您需要将Rest与库中的“查询”( API方法)和“对象”(API类型)匹配,这并不困难,因为名称基本上是相同的。
例如,detectIntent方法全名为:
projects.agent.sessions.detectIntent
在库中,它等同于查询:
GTLRDialogflowQuery_ProjectsAgentSessionsDetectIntent
下面是一个detectIntent请求的示例:
// Create the service
GTLRDialogflowService *service = [[GTLRDialogflowService alloc] init];
// Create the request object (The JSON payload)
GTLRDialogflow_GoogleCloudDialogflowV2DetectIntentRequest *request =
[GTLRDialogflow_GoogleCloudDialogflowV2DetectIntentRequest object];
// Set the information in the request object
request.inputAudio = myInputAudio;
request.outputAudioConfig = myOutputAudioConfig;
request.queryInput = myQueryInput;
request.queryParams = myQueryParams;
// Create a query with session (Path parameter) and the request object
GTLRDialogflowQuery_ProjectsAgentSessionsDetectIntent *query =
[GTLRDialogflowQuery_ProjectsAgentSessionsDetectIntent queryWithObject:request
session:@"session"];
// Create a ticket with a callback to fetch the result
GTLRServiceTicket *ticket =
[service executeQuery:query
completionHandler:^(GTLRServiceTicket *callbackTicket,
GTLRDialogflow_GoogleCloudDialogflowV2DetectIntentResponse *detectIntentResponse,
NSError *callbackError) {
// This callback block is run when the fetch completes.
if (callbackError != nil) {
NSLog(@"Fetch failed: %@", callbackError);
} else {
// The response from the agent
NSLog(@"%@", detectIntentResponse.queryResult.fulfillmentText);
}
}];您可以在库维基中找到更多的信息和示例。最后,库还有一个使用的示例代码,它可以稀释它在GCP服务中的使用。
我认为,如果没有一个用于对话框流V2的特定库,那么在从头开始实现它之前,这可能是下一个尝试。
编辑
哎呀,我错过了为对话框生成的服务不包含v2beta1这一事实。
在这种情况下,需要额外的第一步,即使用对话框流v2beta1 DiscoveryDocument和ServiceGenerator为v2beta1创建服务接口。然后你就可以像我前面提到的那样继续工作了。
发布于 2020-02-22 02:04:30
按照@Tlaquetzal的例子,我最后做了如下的事情
在荚文件
pod 'GoogleAPIClientForREST'
pod 'JWT'如上文所述,使用ServiceGenerator和发现文件生成一组DialogFlow v2beta1类。命令行
./ServiceGenerator --outputDir . --verbose --gtlrFrameworkName GTLR --addServiceNameDir yes --guessFormattedNames https://dialogflow.googleapis.com/\$discovery/rest?version=v2beta1并将它们添加到项目中。
#import "DialogflowV2Beta1/GTLRDialogflow.h"下一步是生成JWT令牌。我用过这个图书馆的在Objective中JSON Web令牌实现。我想使用服务帐户连接。
NSInteger unixtime = [[NSNumber numberWithDouble: [[NSDate date] timeIntervalSince1970]] integerValue];
NSInteger expires = unixtime + 3600; //expire in one hour
NSString *iat = [NSString stringWithFormat:@"%ld", unixtime];
NSString *exp = [NSString stringWithFormat:@"%ld", expires];
NSDictionary *payload = @{
@"iss": @"<YOUR-SERVICE-ACCOUNT-EMAIL>",
@"sub": @"<YOUR-SERVICE-ACCOUNT-EMAIL>",
@"aud": @"https://dialogflow.googleapis.com/",
@"iat": iat,
@"exp": exp
};
NSDictionary *headers = @{
@"alg" : @"RS256",
@"typ" : @"JWT",
@"kid" : @"<KID FROM YOUR SERVICE ACCOUNT FILE>"
};
NSString *algorithmName = @"RS256";
NSData *privateKeySecretData = [[[NSDataAsset alloc] initWithName:@"<IOS-ASSET-NAME-JSON-SERVICE-ACCOUNT-FILE>"] data];
NSString *passphraseForPrivateKey = @"<PASSWORD-FOR-PRIVATE-KEY-IN-CERT-JSON>";
JWTBuilder *builder = [JWTBuilder encodePayload:payload].headers(headers).secretData(privateKeySecretData).privateKeyCertificatePassphrase(passphraseForPrivateKey).algorithmName(algorithmName);
NSString *token = builder.encode;
// check error
if (builder.jwtError == nil) {
JwtToken *jwtToken = [[JwtToken alloc] initWithToken:token expires:expires];
success(jwtToken);
}
else {
// error occurred.
MSLog(@"ERROR. jwtError = %@", builder.jwtError);
failure(builder.jwtError);
}当生成令牌时,可以使用它一个小时(或上面指定的时间)。
要调用对话框流,需要定义项目路径。若要为调用创建项目路径,请将其附加到唯一会话标识符下面的代码中。会话就像对话框流的会话,因此不同的用户应该使用不同的会话ids。
#define PROJECTPATH @"projects/<YOUR-PROJECT-NAME>/agent/sessions/"进行对话框调用
// Create the service
GTLRDialogflowService *service = [[GTLRDialogflowService alloc] init];
//authorise with token
service.additionalHTTPHeaders = @{
@"Authorization" : [NSString stringWithFormat:@"Bearer %@", self.getToken.token]
};
// Create the request object (The JSON payload)
GTLRDialogflow_GoogleCloudDialogflowV2beta1DetectIntentRequest *request = [GTLRDialogflow_GoogleCloudDialogflowV2beta1DetectIntentRequest object];
//create query
GTLRDialogflow_GoogleCloudDialogflowV2beta1QueryInput *queryInput = [GTLRDialogflow_GoogleCloudDialogflowV2beta1QueryInput object];
//text query
GTLRDialogflow_GoogleCloudDialogflowV2beta1TextInput *userText = [GTLRDialogflow_GoogleCloudDialogflowV2beta1TextInput object];
userText.text = question;
userText.languageCode = LANGUAGE;
queryInput.text = @"YOUR QUESTION TO dialogflow agent"; //userText;
// Set the information in the request object
//request.inputAudio = myInputAudio;
//request.outputAudioConfig = myOutputAudioConfig;
request.queryInput = queryInput;
//request.queryParams = myQueryParams;
//Create API project path with session
NSString *pathAndSession = [NSString stringWithFormat:@"%@%@", PROJECTPATH, [self getSession]];
// Create a query with session (Path parameter) and the request object
GTLRDialogflowQuery_ProjectsAgentSessionsDetectIntent *query = [GTLRDialogflowQuery_ProjectsAgentSessionsDetectIntent queryWithObject:request session:pathAndSession];
// Create a ticket with a callback to fetch the result
// GTLRServiceTicket *ticket =
[service executeQuery:query
completionHandler:^(GTLRServiceTicket *callbackTicket, GTLRDialogflow_GoogleCloudDialogflowV2beta1DetectIntentResponse *detectIntentResponse, NSError *callbackError) {
// This callback block is run when the fetch completes.
if (callbackError != nil) {
NSLog(@"error");
NSLog(@"Fetch failed: %@", callbackError);
//TODO: Register failure with analytics
failure( callbackError );
}
else {
// NSLog(@"Success");
// The response from the agent
// NSLog(@"%@", detectIntentResponse.queryResult.fulfillmentText);
NSString *response = detectIntentResponse.queryResult.fulfillmentText;
success( response );
}
}];这是一个基本的实现,但工作和演示的好处。祝好运
https://stackoverflow.com/questions/60015399
复制相似问题