Skip to content
chaliyPublic

About

LLM Simulation for Load Testing

Resources

Contributing

Stars

8 stars

Watchers

0 watching

Forks

Repository files navigation

CI Crates.io PyPI npm Repo: Agent Friendly

LLMSim

LLM Traffic Simulator - A lightweight, high-performance LLM API simulator for load testing, CI/CD, and local development.

Test an agent tool loop locally

Run the simulator from this checkout on a loopback address with call logging enabled.

cargo run -- serve --config examples/node/agent_tool_loop.toml

From a second terminal, run the official OpenAI SDK example. It verifies a 429 retry, four tool calls and their arguments, and the tool results sent back to LLMSim. Tool results come from fixtures.

cd examples/node
npm install
npx tsx agent_tool_loop.ts

See Call log for the assertion and reset endpoints.

Load-test realistic agent traffic

cargo run --release -- serve --host 127.0.0.1

Point your agent client at http://127.0.0.1:8080/openai/v1 and append [[llmsim:coding-agent]] to each test session's initial user message. Offer bash and a read tool, and have the test harness return fixture results to the simulator. The scenario replays 48 tool-call turns with parallel reads and long reasoning, then returns a final answer at model-like speeds. Use a distinct session label in each prompt for reproducible variation under concurrency. Read request, token, and latency metrics from /llmsim/stats.

See Scenarios for workload selection and Benchmarks for k6 load profiles.

Overview

LLMSim replicates realistic LLM API behavior without running actual models. It solves common challenges when testing LLM-integrated applications:

  • Cost: Real API calls during load tests are expensive
  • Rate Limits: Production APIs prevent realistic load testing
  • Reproducibility: Real models produce variable responses
  • Traffic Realism: LLM responses have unique characteristics (streaming, variable latency, token-based billing)

Features

  • Multi-Provider API Support - OpenAI Chat Completions, OpenResponses, Anthropic Messages, and TypeSafe System One APIs
  • Realistic Latency Simulation - Time-to-first-token (TTFT) with a long-tail (log-normal) distribution, inter-token delays, and prefill time that grows with the prompt
  • Streaming Support - Server-Sent Events (SSE) for OpenAI, OpenResponses, and Anthropic streaming formats
  • Image Generation - Simulated gpt-image ("ChatGPT Images") endpoint returning watermarked PNGs, with streaming partial images
  • Accurate Token Counting - Uses tiktoken-rs (OpenAI's tokenizer implementation)
  • Error Injection - Rate limits (429), server errors (500/503), timeouts
  • Prompt Caching - Cached-token usage for repeated prefixes, in OpenAI and Anthropic (cache_control) shapes
  • Multiple Response Generators - Lorem ipsum, echo, fixed, random, sequence
  • Model-Specific Profiles - GPT-6 tiers (Sol, Terra, Luna, Astra), GPT-5, GPT-4, Claude, Gemini, Muse latency profiles
  • Real-time Stats Dashboard - TUI dashboard with live metrics (requests, tokens, latency, errors)
  • Stats API - JSON endpoint for programmatic access to server metrics

Installation

cargo install llmsim

# Include the optional terminal dashboard
cargo install llmsim --features tui

# In-process server for Python or Node/TypeScript tests
pip install llmsim
npm install --save-dev llmsim

Demo

Console UI Demo

Usage

CLI Server

# Start with defaults (port 8080, lorem generator)
llmsim serve

# Start with real-time stats dashboard (TUI)
# Requires installing/building with `--features tui`
llmsim serve --tui

# All options
llmsim serve \
  --port 8080 \
  --host 0.0.0.0 \
  --generator lorem \
  --target-tokens 150 \
  --tui

# Using config file
llmsim serve --config config.toml

Stats Dashboard

The --tui flag launches an interactive terminal dashboard showing real-time metrics:

  • Requests: Total, active, streaming vs non-streaming, requests/sec
  • Tokens: Prompt, completion, total, tokens/sec
  • Latency: Average, min, max response times
  • Errors: Total errors, rate limits (429), server errors (5xx), timeouts
  • Charts: RPS and token rate sparklines, model distribution

Controls: q to quit, r to force refresh.

From Python and TypeScript tests

The llmsim packages on PyPI and npm start the same server inside your test process on a free port. See docs/bindings.md.

from openai import OpenAI
from llmsim import Server

with Server(generator="echo", latency="instant") as sim:
    client = OpenAI(base_url=sim.openai_base_url, api_key="unused")
import OpenAI from "openai";
import { Server } from "llmsim";

await using sim = await Server.start({ generator: "echo", latency: "instant" });
const client = new OpenAI({ baseURL: sim.openaiBaseUrl, apiKey: "unused" });

As a Library

use llmsim::{
    openai::{ChatCompletionRequest, Message},
    generator::LoremGenerator,
    latency::LatencyProfile,
};

// Create a latency profile
let latency = LatencyProfile::gpt5();

// Count tokens
let tokens = llmsim::count_tokens("Hello, world!", "gpt-5").unwrap();

// Generate responses
let generator = LoremGenerator::new(100);
let response = generator.generate(&request);

Cargo features

The crate is split into optional features so library consumers only pull in what they use. The defaults (["cli"]) give the full binary, so cargo build, cargo run -- serve, and cargo test work out of the box.

Feature Adds Extra dependencies
tokens tokens module (token counting) tiktoken-rs
server cli module (axum router, handlers, websockets); implies tokens axum, tower-http
cli the llmsim binary; implies server clap, tracing-subscriber
tui serve --tui dashboard; implies cli tuika, ratatui

To embed only the core library modules (types, generators, latency, streaming, stats, scripts) and shed axum, tower-http, tiktoken-rs, clap, websockets, and tracing-subscriber:

[dependencies]
llmsim = { version = "0.4", default-features = false }

Note that count_tokens and the tokens module are only available with the tokens feature enabled.

To embed the HTTP server in a Rust program or test, llmsim::cli::start_server (feature server) binds and returns a handle with the real address, stats, and graceful shutdown():

let config = llmsim::cli::Config::default().merged_with_json(&serde_json::json!({
    "server": {"host": "127.0.0.1", "port": 0},
    "latency": {"profile": "instant"}
}))?;
let mut server = llmsim::cli::start_server(config).await?;
println!("{}/openai/v1", server.url());
server.shutdown().await?;

API Endpoints

OpenAI API (/openai/v1/...)

Endpoint Method Description
/openai/v1/chat/completions POST Chat completions (streaming & non-streaming)
/openai/v1/models GET List available models
/openai/v1/models/{model_id} GET Get specific model details
/openai/v1/responses POST Responses API (streaming & non-streaming)
/openai/v1/embeddings POST Embeddings (deterministic, similarity-preserving)
/openai/v1/realtime WebSocket Realtime voice sessions (server VAD, audio + transcript)
/openai/v1/responses/{id} (/cancel) GET, DELETE, POST Background responses
/openai/v1/files, /openai/v1/batches POST, GET Files and Batch API
/openai/v1/images/generations POST Image generation (gpt-image, streaming & non-streaming)

When using OpenAI SDKs, set the base URL to http://localhost:8080/openai/v1.

OpenResponses API (/openresponses/v1/...)

OpenResponses is an open-source specification for building multi-provider, interoperable LLM interfaces.

Endpoint Method Description
/openresponses/v1/responses POST Create response (streaming & non-streaming)

Anthropic API (/anthropic/v1/...)

Simulates the Anthropic Messages API with realistic Claude model profiles.

Endpoint Method Description
/anthropic/v1/messages POST Messages API (streaming & non-streaming, extended thinking)
/anthropic/v1/messages/count_tokens POST Count input tokens for a Messages request
/anthropic/v1/messages/batches POST, GET Message Batches (retrieve, cancel, results, delete)
/anthropic/v1/models GET List available Claude models
/anthropic/v1/models/{model_id} GET Get specific model details

When using Anthropic SDKs, set the base URL to http://localhost:8080/anthropic:

from anthropic import Anthropic

client = Anthropic(base_url="http://localhost:8080/anthropic", api_key="not-needed")
msg = client.messages.create(
    model="claude-opus-4-8",
    max_tokens=64,
    messages=[{"role": "user", "content": "Hello, Claude"}],
)
print(msg.content[0].text)

Runnable examples for Python, TypeScript, Go, curl, and LangChain live in examples/ (see examples/README.md).

Gemini API (/gemini/v1beta/...)

Simulates Google's Gemini API: thinking with thoughtsTokenCount, function calling, JSON schema output, SSE and JSON-array streaming, implicit caching and embeddings. Set the Google Gen AI SDK base URL to http://localhost:8080/gemini.

Endpoint Method Description
/gemini/v1beta/models/{model}:generateContent POST Generate content
/gemini/v1beta/models/{model}:streamGenerateContent POST Streaming (?alt=sse)
/gemini/v1beta/models/{model}:countTokens POST Count tokens
/gemini/v1beta/models/{model}:embedContent / :batchEmbedContents POST Embeddings
/gemini/v1beta/models GET List models

TypeSafe API (/typesafe/v1/...)

Simulates TypeSafe's System One API with the Jev model: typed questions (noul, choice, score) about a state, answered with deterministic, well-formed calibrated probabilities.

Endpoint Method Description
/typesafe/v1/systemone POST Answer noul, choice, and score questions
/typesafe/v1/models GET List Jev models and aliases

With the official typesafe-sdk, set the base URL to http://localhost:8080/typesafe:

from typesafe_sdk import Noul, TypeSafeClient

with TypeSafeClient(base_url="http://localhost:8080/typesafe", api_key="not-needed") as client:
    response = client.system_one(
        state="Help! My payouts have been failing for 3 days.",
        questions={"is_urgent": Noul(instructions="Does this convey urgency?")},
    )
    print(response.nouls["is_urgent"].noul)

LLMSim endpoints

Endpoint Method Description
/health GET Health check
/llmsim/stats GET Real-time server statistics (JSON)

Configuration

TOML Config File

[server]
port = 8080
host = "0.0.0.0"

[latency]
profile = "gpt5"
# Custom values (optional):
# ttft_mean_ms = 600
# ttft_stddev_ms = 150
# tbt_mean_ms = 40
# tbt_stddev_ms = 12
# prefill_us_per_token = 50   # added to TTFT per input token; 0 disables

[response]
generator = "lorem"
target_tokens = 100
# auto_tool_calls = false   # call an offered tool even with tool_choice auto
# Named load-test scenarios, picked per message with [[llmsim:<name>]]
# (see docs/scenarios.md):
# scenarios_path = "examples/scenarios"

[errors]
rate_limit_rate = 0.01
server_error_rate = 0.001
timeout_rate = 0.0
timeout_after_ms = 30000
# overload_burst_rate = 0.001  # chance a burst starts; every request then fails
# overload_burst_ms = 10000    # (529 on Anthropic, 503 on OpenAI) for this long

[rate_limits]                  # per API key; 0 = unlimited
# requests_per_minute = 500
# tokens_per_minute = 200000

[batch]
# completion_ms = 2000         # batches report completed after this long

[validation]
# enforce_limits = true        # 400 over context window / max output tokens
# strict_models = false        # 404 for model ids llmsim has no profile for

[models]
available = [
  "gpt-5",
  "gpt-5-mini",
  "gpt-4o",
  "claude-opus",
]

Note: The config file format moved from YAML to TOML in this release. To migrate an existing config.yaml, replace section headers like server: with [server], change key: value to key = value, quote strings, and convert lists. See benchmarks/config/*.toml for working examples.

Supported Models

Family Models
GPT-5 gpt-5, gpt-5-pro, gpt-5-mini, gpt-5-nano, gpt-5-codex, gpt-5.1, gpt-5.2, gpt-5.3-codex, gpt-5.4, gpt-5.5, gpt-5.6 (Sol/Terra/Luna)
GPT-6 gpt-6-astra, gpt-6-sol, gpt-6-luna, gpt-6.1-sol
O-Series o1, o1-mini, o3, o3-mini, o4-mini
GPT-4 gpt-4, gpt-4-turbo, gpt-4o, gpt-4o-mini, gpt-4.1
Claude claude-opus, claude-sonnet, claude-haiku, claude-fable (4.x and 5.x, through Fable 5.1, Opus 5.5, Sonnet 5.5, and Haiku 5.5)
Gemini gemini-2.0-flash, gemini-2.5-pro, gemini-3 / 3.1 previews, gemini-3.5 through gemini-3.8 flash
DeepSeek deepseek-chat, deepseek-reasoner, deepseek-v4-pro, deepseek-flash
TypeSafe jev-latest, jev-preview, jev-1.13.0 (System One, /typesafe/v1/systemone)

The Anthropic endpoints (/anthropic/v1/...) use the real Anthropic API model IDs (dash-separated, e.g. claude-opus-4-8, claude-sonnet-4-6, claude-haiku-4-5, claude-opus-5-5, claude-fable-5-1), including dated-snapshot and -latest aliases. List them via GET /anthropic/v1/models.

Latency Profiles

Profile TTFT Mean TBT Mean
sol (GPT-5.6+/GPT-6 Sol, measured) 2000ms 22ms
terra (GPT-5.6+/GPT-6 Terra) 2400ms 14ms
luna (GPT-5.6+/GPT-6 Luna, measured) 2900ms 9ms
astra (GPT-6 Astra) 3500ms 30ms
muse-spark (measured) 12700ms 7ms
gpt-5 600ms 40ms
gpt-5-mini 300ms 20ms
gpt-4 800ms 50ms
gpt-4o 400ms 25ms
o-series 2000ms 30ms
claude-opus 1000ms 60ms
claude-sonnet 500ms 30ms
claude-haiku 200ms 15ms
jev 150ms — (single verdict)
instant 0ms 0ms
fast 10ms 1ms

The profile is picked from the request's model id unless [latency] sets one. TTFT is log-normal around the mean (a few slow starts), and every input token adds prefill_us_per_token (default 50 µs) to it, so a 200k-token prompt starts about 10 s later. instant and fast skip both. See knowledge/simulation/latency.md.

Use Cases

  • Load Testing - Simulate thousands of concurrent LLM requests, replaying realistic agent conversations with scenarios
  • CI/CD Pipelines - Fast, deterministic tests for LLM integrations
  • Local Development - Develop without API keys or costs
  • Chaos Engineering - Test behavior under failure scenarios
  • Cost Estimation - Estimate token usage before production

Requirements

  • Rust 1.83+ (for building from source)
  • OR Docker

License

MIT License - see LICENSE for details.

Contributing

See CONTRIBUTING.md for contribution guidelines.

About

LLM Simulation for Load Testing

Resources

Contributing

Stars

8 stars

Watchers

0 watching

Forks

Releases

Sponsor this project

Packages

Contributors

Languages