Skip to content

Live Multi-Turn Conversation

This example assumes using Google.Gemini; is in scope and apiKey contains your Google.Gemini API key.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using var client = new GeminiClient(apiKey);

try
{
    using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));

    // Demonstrates a multi-turn conversation using sequential text exchanges.
    await using var session = await client.ConnectLiveAsync(CreateLiveConfig(), cancellationToken: cts.Token);

    // First turn: tell the model a fact.
    await session.SendTextAsync("My name is Alice", cts.Token);

    await foreach (var message in session.ReadEventsAsync(cts.Token))
    {
        if (message.ServerContent?.TurnComplete == true)
        {
            break;
        }
    }

    // Second turn: ask the model to recall the fact.
    await session.SendTextAsync("What is my name?", cts.Token);

    bool receivedResponse = false;
    await foreach (var message in session.ReadEventsAsync(cts.Token))
    {
        if (message.ServerContent?.ModelTurn?.Parts is { Count: > 0 })
        {
            receivedResponse = true;
        }

        if (message.ServerContent?.TurnComplete == true)
        {
            break;
        }
    }

}
catch (WebSocketException ex)
{
}
catch (OperationCanceledException)
{
}