Skip to main content

Overview

This example demonstrates how to implement a streaming chat application using ONNX Runtime GenAI in C#. The ModelChat example shows how to build an interactive conversational AI that maintains context across multiple turns and streams responses in real-time.

Key Features

  • Streaming responses: Tokens are generated and displayed in real-time
  • Conversation history: Maintains chat context across multiple turns
  • Rewind capability: Option to reset to the system prompt after each exchange
  • Guided generation: Support for JSON schema and grammar-based output formatting

Complete Implementation

The following code shows the complete ModelChat function that handles streaming chat interactions:
Program.cs

Usage Example

Here’s how to run the ModelChat example:

How It Works

1. Initialize Generator

The function creates a Generator object with the specified model and parameters:

2. Process System Prompt

The system prompt is encoded and added to the generator once at the start:

3. Chat Loop

For each user message:
  1. Get user input
  2. Apply chat template
  3. Encode and append to generator
  4. Generate tokens one at a time
  5. Stream decoded tokens to console
  6. Optionally rewind to system prompt

4. Streaming Output

Tokens are decoded and displayed as they’re generated:

Key Components

GeneratorParams

Controls generation behavior:
  • max_length: Maximum sequence length
  • temperature: Sampling temperature
  • top_p: Nucleus sampling parameter
  • top_k: Top-k sampling parameter
  • do_sample: Enable random sampling

TokenizerStream

Handles streaming decoding of tokens as they’re generated, enabling real-time output display.

Guidance Support

The example supports structured output through guidance:
  • JSON Schema: Enforce JSON structure in responses
  • LARK Grammar: Use grammar rules for output formatting
  • Tool Calling: Generate function calls in specific formats

Command-Line Options

See Also