-
Notifications
You must be signed in to change notification settings - Fork 402
Expand file tree
/
Copy pathstreaming_proxy.h
More file actions
64 lines (54 loc) · 2.16 KB
/
Copy pathstreaming_proxy.h
File metadata and controls
64 lines (54 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#pragma once
#include <string>
#include <functional>
#include <nlohmann/json.hpp>
#include <httplib.h>
#include "utils/http_client.h"
#include "utils/aixlog.hpp"
#include <iomanip>
namespace lemon {
using json = nlohmann::json;
class StreamingProxy {
public:
struct TelemetryData {
int input_tokens = 0;
int output_tokens = 0;
double time_to_first_token = 0.0;
double tokens_per_second = 0.0;
void print() const {
if (input_tokens > 0 || output_tokens > 0) {
LOG(INFO, "Telemetry") << "=== Telemetry ===" << std::endl;
LOG(INFO, "Telemetry") << "Input tokens: " << input_tokens << std::endl;
LOG(INFO, "Telemetry") << "Output tokens: " << output_tokens << std::endl;
LOG(INFO, "Telemetry") << "TTFT (s): " << std::fixed << std::setprecision(3)
<< time_to_first_token << std::endl;
LOG(INFO, "Telemetry") << "TPS: " << std::fixed << std::setprecision(2)
<< tokens_per_second << std::endl;
LOG(INFO, "Telemetry") << "=================" << std::endl;
}
}
};
static void forward_sse_stream(
const std::string& backend_url,
const std::string& request_body,
httplib::DataSink& sink,
std::function<void(const TelemetryData&)> on_complete = nullptr,
long timeout_seconds = 300,
std::function<void()> on_chunk = nullptr
);
static void forward_byte_stream(
const std::string& backend_url,
const std::string& request_body,
httplib::DataSink& sink,
long timeout_seconds = 300,
std::function<void()> on_chunk = nullptr
);
// Normalize streaming chat.completion.chunk SSE deltas for OpenAI API
// compatibility. Applies:
// 1. Injects `role: "assistant"` when null/missing on assistant deltas
// 2. Injects `content: ""` alongside `reasoning_content` when absent
static std::string normalize_chat_completion_chunk(const std::string& sse_chunk);
private:
static TelemetryData parse_telemetry(const std::string& buffer);
};
} // namespace lemon