Skip to content

Conversation

@mostlygeek
Copy link
Owner

@mostlygeek mostlygeek commented Jul 23, 2025

Fix #198

  • use llama-server's timings info if available in response body
  • send "-1" for token/sec when not able to accurately calculate performance
  • optimize streaming body search for metrics information

Summary by CodeRabbit

  • New Features

    • Added a "timings" field to chat completion responses, providing detailed timing metrics for both streaming and non-streaming modes.
  • Improvements

    • Enhanced metrics handling to support both new timing metrics and existing usage statistics, ensuring more accurate activity tracking.
    • Improved processing of streaming responses for more reliable metrics extraction.
  • Style

    • Updated activity page to display "unknown" for negative speed values, improving clarity in speed formatting.
    • Changed the activity page speed column label from "Processing Speed" to "Generation Speed".
  • Tests

    • Improved test reliability by adding early returns after metric assertions to prevent misleading failures.

- use llama-server's `timings` info if available in response body
- send "-1" for token/sec when not able to accurately calculate
  performance
- optimize streaming body search for metrics information
@coderabbitai
Copy link

coderabbitai bot commented Jul 23, 2025

"""

Walkthrough

This change updates the simple-responder server to include a "timings" field with fixed values in its JSON responses for both streaming and non-streaming chat completions. The proxy's metrics middleware is updated to parse timing information from either the new "timings" field or the legacy "usage" field, prioritizing the last usage data in streaming responses. The Activity page in the UI now displays "unknown" for negative token speeds and renames the speed column. Tests were improved to avoid panics by early returning if metrics are empty.

Changes

File(s) Change Summary
misc/simple-responder/simple-responder.go Adds a "timings" object with fixed llama.cpp-like timing metrics to JSON responses for streaming and non-streaming completions.
proxy/metrics_middleware.go Enhances metrics parsing to support "timings" JSON structure; reverses streaming response line processing; extracts accurate tokens/sec and duration; updates method signature to return success boolean.
ui/src/pages/Activity.tsx Moves formatting helpers to module scope; updates formatSpeed to return "unknown" for negative speeds; renames speed column label.
proxy/proxymanager_test.go Adds early returns after metrics assertions in streaming and non-streaming tests to prevent panics on empty metrics.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant SimpleResponder
    participant Proxy
    participant UI

    Client->>SimpleResponder: POST /v1/chat/completions (streaming or non-streaming)
    SimpleResponder-->>Client: JSON response including "timings" field
    Client->>Proxy: Receives response stream or full response
    Proxy->>Proxy: parseAndRecordMetrics (use "timings" if present, else "usage")
    Proxy-->>UI: Updates metrics data
    UI->>UI: Displays token speed ("unknown" if negative)
Loading

Estimated code review effort

2 (~20 minutes)

Possibly related PRs


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bbc8372 and bfe477d.

📒 Files selected for processing (2)
  • proxy/metrics_middleware.go (1 hunks)
  • proxy/proxymanager_test.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • proxy/metrics_middleware.go
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: run-tests
🔇 Additional comments (2)
proxy/proxymanager_test.go (2)

711-713: LGTM! Good defensive programming practice.

The early return after the empty metrics assertion prevents potential panics when accessing the last metric element later in the test. This improves test robustness.


746-748: LGTM! Consistent defensive programming practice.

Similar to the non-streaming test, this early return prevents potential panics when accessing metrics[len(metrics)-1] if no metrics were recorded. This maintains consistency and improves test safety.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between accd652 and 87cb157.

📒 Files selected for processing (3)
  • misc/simple-responder/simple-responder.go (2 hunks)
  • proxy/metrics_middleware.go (1 hunks)
  • ui/src/pages/Activity.tsx (1 hunks)
🔇 Additional comments (6)
ui/src/pages/Activity.tsx (2)

4-14: Good refactor: Moving formatting functions to module scope.

Moving these utility functions outside the component prevents unnecessary recreations on each render, improving performance. The functions are pure and stateless, making this an appropriate optimization.


8-10: Excellent handling of negative token speeds.

The updated logic to return "unknown" for negative speeds aligns perfectly with the PR objective of displaying meaningful information when token per second metrics cannot be accurately calculated.

misc/simple-responder/simple-responder.go (2)

81-88: Good addition of llama.cpp compatible timing metrics.

The "timings" object with llama.cpp-style fields provides more accurate timing information for the metrics system. The fixed test values are appropriate for a mock server environment.


113-119: Consistent timing metrics for non-streaming responses.

The addition maintains consistency between streaming and non-streaming response formats, ensuring the metrics middleware can parse timing information from both response types.

proxy/metrics_middleware.go (2)

70-102: Excellent dual-format parsing with proper fallback logic.

The implementation correctly prioritizes the more accurate "timings" data while falling back to "usage" data when timings aren't available. The default value of -1.0 for tokensPerSecond aligns perfectly with the PR objective of indicating when metrics cannot be accurately calculated.


105-141: Smart optimization: Reverse iteration for streaming responses.

The backward iteration through response lines is an excellent optimization that finds the final/most complete metrics data more efficiently. The explicit SSE parsing with proper "data:" prefix checking and "[DONE]" handling makes the code more robust.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
proxy/metrics_middleware.go (1)

71-74: Remove early return to support timings-only responses

The current implementation returns early if the "usage" field doesn't exist, preventing metrics recording when only "timings" data is available. This contradicts the PR objective of using timings information when available.

Apply this fix:

-	usage := jsonData.Get("usage")
-	if !usage.Exists() {
-		return
-	}
+	// Process metrics if either timings or usage data exists
+	if !jsonData.Get("timings").Exists() && !jsonData.Get("usage").Exists() {
+		return
+	}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 87cb157 and bbc8372.

📒 Files selected for processing (2)
  • proxy/metrics_middleware.go (1 hunks)
  • ui/src/pages/Activity.tsx (2 hunks)
🧬 Code Graph Analysis (1)
proxy/metrics_middleware.go (1)
proxy/metrics_monitor.go (1)
  • TokenMetrics (12-20)
🚧 Files skipped from review as they are similar to previous changes (1)
  • ui/src/pages/Activity.tsx
🧰 Additional context used
🧬 Code Graph Analysis (1)
proxy/metrics_middleware.go (1)
proxy/metrics_monitor.go (1)
  • TokenMetrics (12-20)

@mostlygeek mostlygeek merged commit 01d4838 into main Jul 23, 2025
3 checks passed
@mostlygeek mostlygeek deleted the fix-token-count-198 branch July 23, 2025 06:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Inaccurate tok/sec in Activity Page

2 participants