Skip to main content
Chats enable multi-turn conversations where the model remembers previous messages and can build on the conversation context. This is perfect for building chatbots, assistants, and interactive applications.

Creating a Chat Session

Create a chat session using client.chats.create() to start a conversation:

Synchronous Non-Streaming

Send messages and receive complete responses:
Each call to send_message() retains the conversation context, so the model can reference previous messages.

Synchronous Streaming

Stream responses as they’re generated for real-time user experiences:
This is ideal for displaying responses progressively in chat interfaces.

Asynchronous Non-Streaming

Use async/await for non-blocking chat operations:

Asynchronous Streaming

Combine async operations with streaming for the best performance:

Context Retention

Chat sessions automatically maintain conversation history. The model can:
  • Reference previous messages
  • Build on earlier responses
  • Maintain consistency across turns
  • Use pronouns and context from prior exchanges

Configuration Options

You can configure chat sessions with the same options as generate_content:

Accessing Chat History

You can access the full conversation history from a chat session:

Best Practices

  • Use streaming for better user experience in chat interfaces
  • Use async for handling multiple concurrent chat sessions
  • Set system instructions to define the assistant’s personality and behavior
  • Monitor context length - long conversations may exceed token limits
  • Create new sessions when starting a new topic or conversation

Common Patterns

Chat with History Clearing

Chat with Function Calling

The chat session maintains context while supporting function calling across multiple turns.