Öndery 742188c3bb feat(agent): report accurate aggregated token usage and propagate session/user + input/output to Langfuse for agent runs (#16420)
### What problem does this PR solve?

_Briefly describe what this PR aims to solve. Include background context
that will help reviewers understand the purpose of the PR._

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
- [x] New Feature (non-breaking change which adds functionality)
- [x] Other (please describe):

## Summary

Agent (Canvas) runs previously did not surface token usage in the SSE
stream, and RAGFlow's own Langfuse generations for agent runs were
missing the prompt/completion split and the session/user correlation.
This made it impossible for an external caller (or Langfuse) to
reconcile an agent turn's cost with the upstream provider (e.g.
OpenRouter), because a single turn can issue several distinct LLM calls
(query rewriting / cross-language translation, multi-round tool
reasoning, nested sub-agents, and the final answer).

This PR introduces a per-run token usage sink so that **every** LLM call
in a run is aggregated and reported once, and enriches Langfuse
generations with the prompt/completion split plus session/user
attributes.

## What changes

### 1. Per-run token usage sink (`common/token_utils.py`)

- Adds two `contextvars`: `token_usage_sink` (a mutable per-run
accumulator) and `langfuse_run_attrs` (session_id/user_id for the run).
- Adds `record_run_token_usage(...)` (thread-safe via a lock, because
`thread_pool_exec` copies the context into worker threads that share the
sink dict) and `usage_from_response(...)` which extracts a
`{prompt_tokens, completion_tokens, total_tokens}` split from
OpenAI/OpenRouter-style responses.

### 2. Provider layer captures the prompt/completion split
(`rag/llm/chat_model.py`)

- `LiteLLMBase` and `Base` now store `self.last_usage`
(prompt/completion/total) for the most recent chat call, in both the
plain and tool-calling paths.
- Streaming requests set `stream_options.include_usage = True` (LiteLLM
path) so the authoritative usage arrives on the final chunk; this is
read even on the usage-only chunk that carries no `choices`.
- Fixes a multi-round accounting bug in `*_with_tools`: token totals
were **overwritten** by each round (`total_tokens = tol`) instead of
accumulated, undercounting multi-round tool conversations. Each round is
now committed to a running aggregate.

### 3. LLMBundle reports usage once, per call
(`api/db/services/llm_service.py`)

- New `_report_usage(total_tokens)` records the call's usage into the
active run sink and returns the prompt/completion/total split for
Langfuse. The split is only used when it is consistent with the
authoritative total; otherwise only the total is reported.
- All three chat entry points (`async_chat`, `async_chat_streamly`,
`async_chat_streamly_delta`) now emit `usage_details` with
`input`/`output`/`total` instead of total-only.
- `_start_langfuse_observation` now applies `session_id`/`user_id` from
the per-run context (`langfuse_run_attrs`) so agent-run generations are
correctly grouped, even though agent LLMBundles are constructed without
those attributes.

### 4. Canvas installs the sink and emits the aggregate
(`agent/canvas.py`)

- `Canvas.run()` installs a fresh `token_usage_sink` and
`langfuse_run_attrs` (from `user_id`/`session_id`) at the start of every
turn.
- `message_end` now includes an aggregated `usage` object:
`{prompt_tokens, completion_tokens, total_tokens, calls}` covering all
LLM calls in the run.

### 5. Pass session id into the run
(`api/db/services/canvas_service.py`)

- `completion()` forwards `session_id` to `Canvas.run()` for Langfuse
session correlation.

## Why a context variable

LLM calls in an agent run originate from many places that each build
their own `LLMBundle` (e.g. `cross_languages`/`keyword_extraction`
helpers, the Agent component, and nested sub-agents invoked as tools). A
run-scoped context variable is the only non-invasive chokepoint that
captures all of them exactly once, including nested agents (which run in
the same async context) and thread-pool tools (the executor copies the
context).

## Behavior / compatibility

- No public API or wire-format removal: `message_end` gains an
additional optional `usage` field; existing consumers are unaffected.
- When a provider does not return authoritative usage, behavior falls
back to the previous token estimate (total only, no split).
- Non-agent flows (Dataflow `Pipeline`, sync `Graph.run`) are untouched.

## Testing
- [x] Simple agent answer: `message_end.usage.total_tokens` matches
provider usage.
- [x] Agent with cross-language retrieval: aggregate equals the sum of
both provider calls.
- [x] Tool-calling agent (multi-round): total accumulates across rounds.
- [x] Nested agent (agent-as-tool): sub-agent tokens included in the
parent run total.
- [x] Langfuse: agent generations show input/output split and are
grouped by session/user.

---------

Co-authored-by: yzc <yuzhichang@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-02 09:35:28 +08:00
2026-07-01 13:29:28 +08:00
2026-06-29 21:20:48 +08:00
2026-06-01 10:25:56 +08:00
2026-05-29 20:37:44 +08:00
2026-06-30 22:14:11 +08:00
2023-12-12 14:13:13 +08:00
2026-04-24 10:02:22 +08:00

README in English 简体中文版自述文件 繁體版中文自述文件 日本語のREADME 한국어 README en Français Bahasa Indonesia Português(Brasil) README in Arabic Türkçe README

follow on X(Twitter) Static Badge docker pull infiniflow/ragflow:v0.26.2 Latest Release license Ask DeepWiki

Cloud | Document | Roadmap | Discord

infiniflow%2Fragflow | Trendshift
📕 Table of Contents

💡 What is RAGFlow?

RAGFlow is a leading open-source Retrieval-Augmented Generation (RAG) engine that fuses cutting-edge RAG with Agent capabilities to create a superior context layer for LLMs. It offers a streamlined RAG workflow adaptable to enterprises of any scale. Powered by a converged context engine and pre-built agent templates, RAGFlow enables developers to transform complex data into high-fidelity, production-ready AI systems with exceptional efficiency and precision.

🎮 Get Started

Try our cloud service at https://cloud.ragflow.io.

🔥 Latest Updates

  • 2026-06-15 Support multiple chat channels such as Feishu, Discord, Telegram, Line, etc.
  • 2026-04-24 Supports DeepSeek v4.
  • 2026-03-24 RAGFlow Skill on OpenClaw — Provides an official skill for accessing RAGFlow datasets via OpenClaw.
  • 2025-12-26 Supports 'Memory' for AI agent.
  • 2025-11-19 Supports Gemini 3 Pro.
  • 2025-11-12 Supports data synchronization from Confluence, S3, Notion, Discord, Google Drive.
  • 2025-10-23 Supports MinerU & Docling as document parsing methods.
  • 2025-10-15 Supports orchestrable ingestion pipeline.
  • 2025-08-08 Supports OpenAI's latest GPT-5 series models.
  • 2025-08-01 Supports agentic workflow and MCP.
  • 2025-05-23 Adds a Python/JavaScript code executor component to Agent.
  • 2025-03-19 Supports using a multi-modal model to make sense of images within PDF or DOCX files.

🎉 Stay Tuned

Star our repository to stay up-to-date with exciting new features and improvements! Get instant notifications for new releases! 🌟

🌟 Key Features

🍭 "Quality in, quality out"

  • Deep document understanding-based knowledge extraction from unstructured data with complicated formats.
  • Finds "needle in a data haystack" of literally unlimited tokens.

🍱 Template-based chunking

  • Intelligent and explainable.
  • Plenty of template options to choose from.

🌱 Grounded citations with reduced hallucinations

  • Visualization of text chunking to allow human intervention.
  • Quick view of the key references and traceable citations to support grounded answers.

🍔 Compatibility with heterogeneous data sources

  • Supports Word, slides, excel, txt, images, scanned copies, structured data, web pages, and more.

🛀 Automated and effortless RAG workflow

  • Streamlined RAG orchestration catered to both personal and large businesses.
  • Configurable LLMs as well as embedding models.
  • Multiple recall paired with fused re-ranking.
  • Intuitive APIs for seamless integration with business.

🔎 System Architecture

🎬 Self-Hosting

📝 Prerequisites

  • CPU >= 4 cores
  • RAM >= 16 GB
  • Disk >= 50 GB
  • Docker >= 24.0.0 & Docker Compose >= v2.26.1
  • Python >= 3.13
  • gVisor: Required only if you intend to use the code executor (sandbox) feature of RAGFlow.

Tip

If you have not installed Docker on your local machine (Windows, Mac, or Linux), see Install Docker Engine.

🚀 Start up the server

  1. Ensure vm.max_map_count >= 262144:

    To check the value of vm.max_map_count:

    $ sysctl vm.max_map_count
    

    Reset vm.max_map_count to a value at least 262144 if it is not.

    # In this case, we set it to 262144:
    $ sudo sysctl -w vm.max_map_count=262144
    

    This change will be reset after a system reboot. To ensure your change remains permanent, add or update the vm.max_map_count value in /etc/sysctl.conf accordingly:

    vm.max_map_count=262144
    
  2. Clone the repo:

    $ git clone https://github.com/infiniflow/ragflow.git
    
  3. Start up the server using the pre-built Docker images:

Caution

All Docker images are built for x86 platforms. We don't currently offer Docker images for ARM64. If you are on an ARM64 platform, follow this guide to build a Docker image compatible with your system.

The command below downloads the v0.26.2 edition of the RAGFlow Docker image. See the following table for descriptions of different RAGFlow editions. To download a RAGFlow edition different from v0.26.2, update the RAGFLOW_IMAGE variable accordingly in docker/.env before using docker compose to start the server.

   $ cd ragflow/docker

   # git checkout v0.26.2
   # Optional: use a stable tag (see releases: https://github.com/infiniflow/ragflow/releases)
   # This step ensures the **entrypoint.sh** file in the code matches the Docker image version.

   # Use CPU for DeepDoc tasks:
   $ docker compose -f docker-compose.yml up -d

   # To use GPU to accelerate DeepDoc tasks:
   # sed -i '1i DEVICE=gpu' .env
   # docker compose -f docker-compose.yml up -d

Note: Prior to v0.22.0, we provided both images with embedding models and slim images without embedding models. Details as follows:

RAGFlow image tag Image size (GB) Has embedding models? Stable?
v0.21.1 ≈9 ✔️ Stable release
v0.21.1-slim ≈2 Stable release

Starting with v0.22.0, we ship only the slim edition and no longer append the -slim suffix to the image tag.

  1. Check the server status after having the server up and running:

    $ docker logs -f docker-ragflow-cpu-1
    

    The following output confirms a successful launch of the system:

    
          ____   ___    ______ ______ __
         / __ \ /   |  / ____// ____// /____  _      __
        / /_/ // /| | / / __ / /_   / // __ \| | /| / /
       / _, _// ___ |/ /_/ // __/  / // /_/ /| |/ |/ /
      /_/ |_|/_/  |_|\____//_/    /_/ \____/ |__/|__/
    
     * Running on all addresses (0.0.0.0)
    

    If you skip this confirmation step and directly log in to RAGFlow, your browser may prompt a network abnormal error because, at that moment, your RAGFlow may not be fully initialized.

  2. In your web browser, enter the IP address of your server and log in to RAGFlow.

    With the default settings, you only need to enter http://IP_OF_YOUR_MACHINE (sans port number) as the default HTTP serving port 80 can be omitted when using the default configurations.

  3. In service_conf.yaml.template, select the desired LLM factory in user_default_llm and update the API_KEY field with the corresponding API key.

    See llm_api_key_setup for more information.

    The show is on!

🔧 Configurations

When it comes to system configurations, you will need to manage the following files:

  • .env: Keeps the fundamental setups for the system, such as SVR_HTTP_PORT, MYSQL_PASSWORD, and MINIO_PASSWORD.
  • service_conf.yaml.template: Configures the back-end services. The environment variables in this file will be automatically populated when the Docker container starts. Any environment variables set within the Docker container will be available for use, allowing you to customize service behavior based on the deployment environment.
  • docker-compose.yml: The system relies on docker-compose.yml to start up.

The ./docker/README file provides a detailed description of the environment settings and service configurations which can be used as ${ENV_VARS} in the service_conf.yaml.template file.

To update the default HTTP serving port (80), go to docker-compose.yml and change 80:80 to <YOUR_SERVING_PORT>:80.

Updates to the above configurations require a reboot of all containers to take effect:

$ docker compose -f docker-compose.yml up -d

Switch doc engine from Elasticsearch to Infinity

RAGFlow uses Elasticsearch by default for storing full text and vectors. To switch to Infinity, follow these steps:

  1. Stop all running containers:

    $ docker compose -f docker/docker-compose.yml down -v
    

Warning

-v will delete the docker container volumes, and the existing data will be cleared.

  1. Set DOC_ENGINE in docker/.env to infinity.

  2. Start the containers:

    $ docker compose -f docker-compose.yml up -d
    

Warning

Switching to Infinity on a Linux/arm64 machine is not yet officially supported.

🔧 Build a Docker image

This image is approximately 2 GB in size and relies on external LLM and embedding services.

git clone https://github.com/infiniflow/ragflow.git
cd ragflow/
docker build --platform linux/amd64 -f Dockerfile -t infiniflow/ragflow:nightly .

Or if you are behind a proxy, you can pass proxy arguments:

docker build --platform linux/amd64 \
  --build-arg http_proxy=http://YOUR_PROXY:PORT \
  --build-arg https_proxy=http://YOUR_PROXY:PORT \
  -f Dockerfile -t infiniflow/ragflow:nightly .

🔨 Launch service from source for development

Important

After cloning the repository for the first time, run lefthook install once from the repo root to enable local Git hooks.

  1. Install uv, or skip this step if it is already installed:

    pipx install uv
    
  2. Clone the source code and install Python dependencies:

    git clone https://github.com/infiniflow/ragflow.git
    cd ragflow/
    uv sync --python 3.13 # install RAGFlow dependent python modules
    uv run python3 ragflow_deps/download_deps.py
    lefthook install
    
  3. Launch the dependent services (MinIO, Elasticsearch, Redis, and MySQL) using Docker Compose:

    docker compose -f docker/docker-compose-base.yml up -d
    

    Add the following line to /etc/hosts to resolve all hosts specified in docker/.env to 127.0.0.1:

    127.0.0.1       es01 infinity mysql minio redis sandbox-executor-manager
    
  4. If you cannot access HuggingFace, set the HF_ENDPOINT environment variable to use a mirror site:

    export HF_ENDPOINT=https://hf-mirror.com
    
  5. If your operating system does not have jemalloc, please install it as follows:

    # Ubuntu
    sudo apt-get install libjemalloc-dev
    # CentOS
    sudo yum install jemalloc
    # OpenSUSE
    sudo zypper install jemalloc
    # macOS
    sudo brew install jemalloc
    
  6. Launch backend service:

    source .venv/bin/activate
    export PYTHONPATH=$(pwd)
    bash docker/launch_backend_service.sh
    
  7. Install frontend dependencies:

    cd web
    npm install
    
  8. Launch frontend service:

    npm run dev
    

    The following output confirms a successful launch of the system:

  9. Stop RAGFlow front-end and back-end service after development is complete:

    pkill -f "ragflow_server.py|task_executor.py"
    

📚 Documentation

📜 Roadmap

See the RAGFlow Roadmap 2026

🏄 Community

🙌 Contributing

RAGFlow flourishes via open-source collaboration. In this spirit, we embrace diverse contributions from the community. If you would like to be a part, review our Contribution Guidelines first.

Languages
Go 39%
Python 34.8%
TypeScript 20.1%
C++ 5%
C 0.5%
Other 0.4%