Using GRPC only connecting to dialog flow Streamin

2019-08-11 12:00发布

问题:

I'm trying to use DialogFlow API v2 with Unity.

Since there's no official SDK for Unity yet I used the Grpc beta unity SDK and the generated C# code I created with Protobuf and protoc from Grpc tools

The Grpc beta unity sdk is hidden in this link. https://packages.grpc.io/ just click a build ID and you will find a built unity package.

I imported Google.Apis.Auth.OAuth2 and Grpc.Auth which weren't included in the official Grpc unity beta sdk.

Then I wrote this code which seems to work fine except that await responseStream.MoveNext() is stuck.

I believe the main reason is I'm not sure where to set the path to the end point which is '/v2/projects/project-id/agent/intents'

    GoogleCredential credential = GoogleCredential.FromJson(privateKey);

    Grpc.Core.Channel channel = new Grpc.Core.Channel("dialogflow.googleapis.com", credential.ToChannelCredentials());

    var client = new SessionsClient(channel);

    CallOptions options = new CallOptions();
    var duplexStream = client.StreamingDetectIntent();

    var responseHandlerTask = System.Threading.Tasks.Task.Run(async () =>
    {
        IAsyncEnumerator<StreamingDetectIntentResponse> responseStream = duplexStream.ResponseStream;
        while (await responseStream.MoveNext())//stuck here
        {
            StreamingDetectIntentResponse response = responseStream.Current;
        }
        // The response stream has completed
    });

    // Send requests to the server
    bool done = false;
    while (!done)
    {
        // Initialize a request
        var queryInput = new QueryInput();
        queryInput.AudioConfig = new InputAudioConfig();
        queryInput.AudioConfig.LanguageCode = "ja";
        queryInput.AudioConfig.SampleRateHertz = 141000;
        queryInput.AudioConfig.AudioEncoding = AudioEncoding.Linear16;

        StreamingDetectIntentRequest request = new StreamingDetectIntentRequest
        {
            Session = "",
            QueryInput = queryInput,
        };
        var bytes = File.ReadAllBytes("test.wav");
        request.InputAudio = Google.Protobuf.ByteString.CopyFrom(bytes);
        try
        {
            await duplexStream.RequestStream.WriteAsync(request);
        }
        catch (System.Exception e)
        {
            context.Post(state =>
            {
                Debug.LogErrorFormat("{0}\n{1}\n{2}\n{3}", e.Message, e.HelpLink, e.Source, e.StackTrace);
            }, null);
        }

        done = true;
    }

    await duplexStream.RequestStream.CompleteAsync();
    await responseHandlerTask;

Thanks for advance.

回答1:

I didn't add correction session to the request. The following fixed it.

StreamingDetectIntentRequest request = new StreamingDetectIntentRequest
{
    Session = "projects/project-id/agent/sessions/sessionid",
    QueryInput = queryInput,
};