coolhand 0.11.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +43 -0
- data/README.md +14 -1
- data/docs/anthropic.md +15 -16
- data/docs/configuration.md +8 -6
- data/docs/declared_workloads.md +24 -1
- data/docs/feedback.md +33 -1
- data/docs/openai.md +2 -0
- data/docs/savings.md +95 -0
- data/lib/coolhand/api_service.rb +45 -68
- data/lib/coolhand/base_interceptor.rb +28 -15
- data/lib/coolhand/configuration.rb +6 -0
- data/lib/coolhand/declared_context.rb +29 -7
- data/lib/coolhand/default_intercept_path_patterns.yml +2 -2
- data/lib/coolhand/errors.rb +2 -1
- data/lib/coolhand/feedback_service.rb +49 -2
- data/lib/coolhand/log_queue.rb +222 -16
- data/lib/coolhand/net_http_interceptor.rb +22 -10
- data/lib/coolhand/optimization_feedback_link_service.rb +3 -8
- data/lib/coolhand/post_delivery.rb +139 -0
- data/lib/coolhand/read_requests.rb +9 -0
- data/lib/coolhand/response_warnings.rb +11 -4
- data/lib/coolhand/savings_service.rb +33 -0
- data/lib/coolhand/string_body_redactor.rb +60 -11
- data/lib/coolhand/version.rb +1 -1
- data/lib/coolhand/write_requests.rb +3 -3
- data/lib/coolhand.rb +18 -5
- metadata +5 -2
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 9906b58a2849265b01a3e2136f8fb71e42d60616082575d18b80f9b158c8e14f
|
|
4
|
+
data.tar.gz: 9225209cb6d52fadca9617ce83cb7c623af6b684730802b596530975996eaac0
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: b0415471072c6bd6123eeb70a1562415353e5bc54e91e022f7e9f52fd06912ddead12af018e27e995248578b783e3a03548722477f2cbe90e299e363f90c2cdc
|
|
7
|
+
data.tar.gz: 55b55edd36d5ebb2d537d9dccbf9b3ce54b1180849e66cff3b3d29ff3e400e7c9b320dda48461fc025ba2468f13376b1cccfedd6743ed69185b1b50b68cf139b
|
data/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,49 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.13.0] - 2026-11-25
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
- `create_feedback(client_unique_id:)` now waits for its own log ([#233](https://github.com/Coolhand-Labs/coolhand-ruby/pull/233)). Logs are sent in the background, so feedback used to need a `Coolhand.flush` first or it could arrive before the log it refers to. Feedback that carries a `client_unique_id` now waits (up to 5 seconds) for the queued log with that id to finish sending, and only that log: unrelated traffic doesn't delay it. No `Coolhand.flush` is needed any more, and `docs/feedback.md`, `docs/declared_workloads.md` and `docs/anthropic.md` drop the workaround. This only covers logs queued in the same process; feedback sent from a different process still needs its log delivered first.
|
|
14
|
+
- `create_feedback(..., raise_on_error: true)` raises `Coolhand::HttpError` (with `status` and `body`) or `Coolhand::Error` instead of returning `nil` ([#234](https://github.com/Coolhand-Labs/coolhand-ruby/pull/234)). Fields can be passed as a Hash or as bare keywords. The success message now names the identifier used (for example `Client Unique ID: order-42.1`) instead of `ID: N/A`.
|
|
15
|
+
- Logs sent from the background queue retry transient failures (connect failure or timeout, HTTP 429, 502 or 503) twice with a short backoff ([#234](https://github.com/Coolhand-Labs/coolhand-ruby/pull/234)). A read timeout, connection reset or 504 is not retried, because the server may have stored the log and a retry could duplicate it.
|
|
16
|
+
|
|
17
|
+
### Changed
|
|
18
|
+
- **Behavior change:** if the log for a `client_unique_id` failed to send, `create_feedback` now logs a warning and returns `nil` without posting (or raises `Coolhand::Error` with `raise_on_error: true`), instead of sending feedback Coolhand can't match to a log ([#233](https://github.com/Coolhand-Labs/coolhand-ruby/pull/233)). The failed id is remembered (last 1,000) until a later log with that id sends successfully. If the log is still sending after 5 seconds, the feedback is sent anyway with a warning. Feedback without a `client_unique_id` behaves as before.
|
|
19
|
+
- **Behavior change:** `Coolhand.flush` returns `false` (once, until the next flush that drains) when a log was not delivered ([#234](https://github.com/Coolhand-Labs/coolhand-ruby/pull/234)): a send that failed after its retries, a queued job that raised, or a log dropped from a full queue. Code that treated `flush == true` as always-true will now see `false` after a lost log. A 2xx response with a blank or non-JSON body now counts as delivered. `create_feedback(hash, unknown_keyword: ...)` now raises `ArgumentError`, since a stray keyword next to a Hash is almost certainly a misspelled option.
|
|
20
|
+
- Redaction now also covers JSON that fails to parse ([#231](https://github.com/Coolhand-Labs/coolhand-ruby/pull/231)). A streamed response cut off mid-line (the `stream_incomplete` case) or a malformed JSON text body used to be logged as received, credentials included. The value of every credential-named string pair in it is now replaced with `[REDACTED]` in place, including a value cut off before its closing quote, and the rest of the partial text is kept. URL-valued fields and the `client_secret` object form are still only handled in JSON that parses (see `docs/configuration.md`).
|
|
21
|
+
- A Google `intercept_path_patterns` entry (such as `:generateContent`) now matches only at the end of the request path ([#229](https://github.com/Coolhand-Labs/coolhand-ruby/pull/229)). Before, any `googleapis.com` path that merely contained the pattern was captured, for example a Cloud Storage object named `notes:generateContent.txt`. If you added a custom pattern that is not a path suffix, it no longer matches.
|
|
22
|
+
- Errors raised by host code during `Net::HTTP#request` other than your streaming block (for example a custom `body_stream` whose `read` raises) are now logged with only their class and `[redacted: not a transport error]` as the message ([#228](https://github.com/Coolhand-Labs/coolhand-ruby/pull/228)). Transport errors keep their message, and `SocketError` (DNS failures) is now one of them.
|
|
23
|
+
- Hardening ([#230](https://github.com/Coolhand-Labs/coolhand-ruby/pull/230)): a `Bearer` authorization header is always logged as `Bearer [REDACTED]`, the body of a failed Coolhand API response is stripped of control, bidi and zero-width characters before it reaches your stdout or an `HttpError` message (`HttpError#body` stays the raw, length-capped body, so treat it as untrusted), and GET requests that read from Coolhand now have a 5 second `write_timeout`.
|
|
24
|
+
- Docs: `docs/configuration.md` notes that `exclude_api_patterns` is case-sensitive on purpose and what to do behind a case-insensitive gateway, and `docs/openai.md` notes that the batch processor keeps each input item's capped request body in memory until the output file is read ([#229](https://github.com/Coolhand-Labs/coolhand-ruby/pull/229)).
|
|
25
|
+
- Internal: the POST logic moved from `ApiService` into `Coolhand::PostDelivery` ([#234](https://github.com/Coolhand-Labs/coolhand-ruby/pull/234)).
|
|
26
|
+
|
|
27
|
+
### Fixed
|
|
28
|
+
- Credentials in URL-valued headers are redacted. A header value that holds a URL (`Location`, `Referer`, `Link`, an upload-URL header) went to Coolhand as is, so a presigned signature or API key in its query string was logged even though the request URL itself was scrubbed. They now go through the same query-string scrub as the request URL.
|
|
29
|
+
- A 2xx response from Coolhand whose body is the JSON literal `null` now counts as a delivered log, like a blank or non-JSON 2xx body. Before, it made the send look failed, so `Coolhand.flush` returned `false` and a `create_feedback` waiting on that `client_unique_id` was skipped, even though Coolhand had stored the log.
|
|
30
|
+
- `Coolhand.configuration.inspect` no longer prints the API key, so `p config` or a logged config object can't leak it.
|
|
31
|
+
- An exception raised by host code whose own `#message` or `#status` raises no longer replaces the host's original error while Coolhand records it.
|
|
32
|
+
- The logged URL no longer drops the `/` before a slash-less request path ([#235](https://github.com/Coolhand-Labs/coolhand-ruby/pull/235)). Requests that reach `Net::HTTP` with a path such as `v1/messages` (the Anthropic SDK's Bedrock client does this) were logged as `https://bedrock-runtime.us-east-1.amazonaws.comv1/messages`, which broke provider classification downstream. The same URL feeds the intercept check, so host and path matching now also work for slash-less paths, which were silently skipped before.
|
|
33
|
+
|
|
34
|
+
### Dependencies
|
|
35
|
+
- `ruby/setup-ruby` bumped to 1.343.0 in CI and the publish workflow ([#224](https://github.com/Coolhand-Labs/coolhand-ruby/pull/224)).
|
|
36
|
+
- `rubygems/release-gem` bumped to 1.4.2 in the publish workflow ([#225](https://github.com/Coolhand-Labs/coolhand-ruby/pull/225)).
|
|
37
|
+
|
|
38
|
+
## [0.12.0] - 2026-11-23
|
|
39
|
+
|
|
40
|
+
### Added
|
|
41
|
+
- `Coolhand.savings_service.get_realized_savings` ([#220](https://github.com/Coolhand-Labs/coolhand-ruby/pull/220)) reads the client's realized savings (`GET /api/v2/savings`): what requests on the current templates cost versus the deprecated versions they replaced, in total and per workload. It takes no parameters and returns one Symbol-keyed Hash. A non-2xx response raises `Coolhand::HttpError`; a `503` means the figure could not be computed right now and is not zero savings. Needs the private API key. See [Reading Realized Savings](docs/savings.md).
|
|
42
|
+
- `Coolhand.with_context(client_unique_id: "abc.1") { ... }` ([#222](https://github.com/Coolhand-Labs/coolhand-ruby/pull/222)) stamps your own id on every log captured in the block, so `create_feedback(client_unique_id: "abc.1")` has a log-side id to match. It nests like the other fields (innermost wins, restored on exit) and works without a workload or template. The id is sent as top-level `llm_request_log.client_unique_id`, not inside `declared`. **Note:** exact matching needs the matching Coolhand server change ([Coolhand-Labs/coolhand#2316](https://github.com/Coolhand-Labs/coolhand/pull/2316)), which stores `client_unique_id` on logs and matches feedback by it before any text matching. Until it is deployed to your Coolhand instance, the id is sent but not stored or matched. See [Declared Workloads](docs/declared_workloads.md).
|
|
43
|
+
|
|
44
|
+
### Changed
|
|
45
|
+
- An invalid `client_unique_id` (not a String, blank, over 255 characters, or containing control or invisible characters) is ignored and logged rather than raised, so a bad correlation id never breaks your LLM call or risks a 422 on the log ([#222](https://github.com/Coolhand-Labs/coolhand-ruby/pull/222)).
|
|
46
|
+
- Docs: `docs/anthropic.md` "Request Correlation" no longer references the nonexistent `Thread.current[:coolhand_current_request_id]` or `FeedbackService.new(Coolhand.configuration)`, and `docs/feedback.md` documents the `client_unique_id` flow ([#222](https://github.com/Coolhand-Labs/coolhand-ruby/pull/222)).
|
|
47
|
+
- Internal: the "response was not a JSON object" check now lives in `ReadRequests#ensure_json_object!`, shared by the savings and optimization feedback link services ([#220](https://github.com/Coolhand-Labs/coolhand-ruby/pull/220)).
|
|
48
|
+
- The `/finish-release` skill may use `gh pr merge --admin` only to bypass the "only maintainers can merge" ruleset, after a plain merge is refused and every check is green ([#217](https://github.com/Coolhand-Labs/coolhand-ruby/pull/217)).
|
|
49
|
+
|
|
50
|
+
### Dependencies
|
|
51
|
+
- `ruby/setup-ruby` bumped to 1.338.0 in CI and the publish workflow ([#218](https://github.com/Coolhand-Labs/coolhand-ruby/pull/218)).
|
|
52
|
+
|
|
10
53
|
## [0.11.0] - 2026-11-06
|
|
11
54
|
|
|
12
55
|
### Added
|
data/README.md
CHANGED
|
@@ -117,6 +117,18 @@ step[:metrics][:notes]
|
|
|
117
117
|
|
|
118
118
|
For the parameters, `metrics` fields and errors, see [Reading Step Templates →](docs/step-templates.md).
|
|
119
119
|
|
|
120
|
+
### Realized savings
|
|
121
|
+
|
|
122
|
+
`Coolhand.savings_service.get_realized_savings` returns what you saved by switching templates or models, in total and per workload, with the same private API key. It takes no parameters; a `503` means the figure could not be computed right now and is not zero savings.
|
|
123
|
+
|
|
124
|
+
```ruby
|
|
125
|
+
savings = Coolhand.savings_service.get_realized_savings
|
|
126
|
+
savings[:total] # USD saved against the deprecated versions
|
|
127
|
+
savings[:percent] # share of what they would have cost
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
For the return value, errors, and joining it with workload metrics, see [Reading Realized Savings →](docs/savings.md).
|
|
131
|
+
|
|
120
132
|
### Cost and performance metrics
|
|
121
133
|
|
|
122
134
|
Pass `include_metrics: true` to `search_templates` (or `search_workloads`) for the dashboard's cost and performance numbers, over a rolling `days_back` window or an explicit `since:` / `until:` one. `search_logs` carries each log's `cost` and can sort and filter by it. `failure_summary` rolls failed requests up by error pattern and template, and `search_logs(error_contains:)` lists the logs behind a pattern.
|
|
@@ -521,7 +533,7 @@ The monitor handles errors gracefully:
|
|
|
521
533
|
- Failed API logging attempts are logged to console but don't interrupt your application
|
|
522
534
|
- Invalid API keys will be reported but won't crash your app
|
|
523
535
|
- Network issues are handled with appropriate error messages
|
|
524
|
-
- The read methods (`search_templates`, `get_template`, `list_step_templates`, `get_step_template`, `search_workloads`, `search_logs`, `get_log`, `failure_summary`, `search_help_articles`, `get_help_article`, `list_help_categories`), the feedback-link methods and the `upsert` methods are the exception — they raise `Coolhand::Error` (`Coolhand::HttpError` for non-2xx responses); see [Reading Templates →](docs/template-search.md), [Reading Step Templates →](docs/step-templates.md), [Reading Workloads →](docs/workload-search.md), [Reading Logs →](docs/log-search.md), [Linking Feedback →](docs/feedback-links.md) and [Declared Workloads →](docs/declared_workloads.md)
|
|
536
|
+
- The read methods (`search_templates`, `get_template`, `list_step_templates`, `get_step_template`, `search_workloads`, `get_realized_savings`, `search_logs`, `get_log`, `failure_summary`, `search_help_articles`, `get_help_article`, `list_help_categories`), the feedback-link methods and the `upsert` methods are the exception — they raise `Coolhand::Error` (`Coolhand::HttpError` for non-2xx responses); see [Reading Templates →](docs/template-search.md), [Reading Step Templates →](docs/step-templates.md), [Reading Workloads →](docs/workload-search.md), [Reading Realized Savings →](docs/savings.md), [Reading Logs →](docs/log-search.md), [Linking Feedback →](docs/feedback-links.md) and [Declared Workloads →](docs/declared_workloads.md)
|
|
525
537
|
|
|
526
538
|
## Documentation
|
|
527
539
|
|
|
@@ -530,6 +542,7 @@ The monitor handles errors gracefully:
|
|
|
530
542
|
- **[Reading Templates](docs/template-search.md)** — Search LLM request templates and fetch a single one, prompt patterns included, using the private API key
|
|
531
543
|
- **[Reading Step Templates](docs/step-templates.md)** — List the skills and recurring steps detected in captured agent sessions, with run and efficiency metrics, using the private API key
|
|
532
544
|
- **[Reading Workloads](docs/workload-search.md)** — List workloads with optional cost and performance metrics over a rolling or explicit time window
|
|
545
|
+
- **[Reading Realized Savings](docs/savings.md)** — Fetch the saving realized by switching templates or models, in total and per workload, and join it with workload metrics
|
|
533
546
|
- **[Reading Logs](docs/log-search.md)** — Search logs with per-log cost, filter and sort by cost, and fetch one log with its cost breakdown
|
|
534
547
|
- **[Reading the Help Center](docs/help-center.md)** — Search and read Coolhand's help center articles and list its sections, with no API key required
|
|
535
548
|
- **[Linking Feedback](docs/feedback-links.md)** — Link feedback to an optimization as evidence, singly or in bulk, using the private API key
|
data/docs/anthropic.md
CHANGED
|
@@ -305,32 +305,31 @@ threads.each(&:join)
|
|
|
305
305
|
|
|
306
306
|
### Request Correlation
|
|
307
307
|
|
|
308
|
-
|
|
308
|
+
Tag a request with your own id, then send feedback against it:
|
|
309
309
|
|
|
310
310
|
```ruby
|
|
311
311
|
client = Anthropic::Client.new
|
|
312
312
|
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
request_id = Thread.current[:coolhand_current_request_id]
|
|
323
|
-
puts "Logged to Coolhand with ID: #{request_id}"
|
|
313
|
+
Coolhand.with_context(client_unique_id: "support-ticket-123.1") do
|
|
314
|
+
client.messages(
|
|
315
|
+
parameters: {
|
|
316
|
+
model: "claude-3-sonnet-20240229",
|
|
317
|
+
max_tokens: 1000,
|
|
318
|
+
messages: [{ role: "user", content: "Hello" }]
|
|
319
|
+
}
|
|
320
|
+
)
|
|
321
|
+
end
|
|
324
322
|
|
|
325
|
-
#
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
llm_request_log_id: request_id,
|
|
323
|
+
# The log is tagged with the id above, so feedback can be matched to that request
|
|
324
|
+
Coolhand.feedback_service.create_feedback(
|
|
325
|
+
client_unique_id: "support-ticket-123.1",
|
|
329
326
|
sentiment: "like",
|
|
330
327
|
explanation: "Great response quality"
|
|
331
328
|
)
|
|
332
329
|
```
|
|
333
330
|
|
|
331
|
+
See [Declaring workloads and templates](declared_workloads.md#linking-feedback-to-a-request) for the id rules.
|
|
332
|
+
|
|
334
333
|
## Troubleshooting
|
|
335
334
|
|
|
336
335
|
### Debug Mode
|
data/docs/configuration.md
CHANGED
|
@@ -52,8 +52,9 @@ Besides headers and URLs, Coolhand redacts credentials in the JSON body of both
|
|
|
52
52
|
Limits:
|
|
53
53
|
- A secret that is part of a URL's path (for example `https://actions.zapier.com/mcp/SECRET/sse`) cannot be detected generically and is sent as is.
|
|
54
54
|
- Parsed JSON objects and arrays are walked as described above. Subtrees nested more than 100 levels deep are replaced with `[REDACTED]`.
|
|
55
|
-
- A raw String body is checked in two cases: JSON text (e.g. a webhook body that is a JSON string) is parsed, redacted and re-serialized, and the JSON object/array payload on each `data:` line of a streamed (server-sent event) response is redacted the same way. A JSON payload is always re-serialized (compact, a repeated key keeps its last value), even when nothing in it was redacted, so its whitespace and string escapes may differ from the original and numbers are normalized to double precision (integers of any size are kept). Provider streams are compact JSON already, so they usually come through identical.
|
|
56
|
-
-
|
|
55
|
+
- A raw String body is checked in two cases (plus the fallback for JSON that does not parse, next): JSON text (e.g. a webhook body that is a JSON string) is parsed, redacted and re-serialized, and the JSON object/array payload on each `data:` line of a streamed (server-sent event) response is redacted the same way. A JSON payload is always re-serialized (compact, a repeated key keeps its last value), even when nothing in it was redacted, so its whitespace and string escapes may differ from the original and numbers are normalized to double precision (integers of any size are kept). Provider streams are compact JSON already, so they usually come through identical.
|
|
56
|
+
- JSON that does not parse, typically a stream cut off mid-line (see [Abandoned Streams](#abandoned-streams-stream_incomplete)), cannot be re-serialized, so it is kept as received except that the value of every credential-named string pair (the same key list and name matching as above) is replaced with `[REDACTED]` in place, including a value that was cut off before its closing quote. Only the key list is scrubbed: redactions that depend on the structure around a key are applied only to JSON that parses, namely URL-valued fields (so the userinfo and secret query parameters of any URL field in such a body are logged as received), the `client_secret` object form and the Realtime `{"value", "expires_at"}` ephemeral key, MCP tool `headers` maps, and Azure `data_sources`. The scan relies on the quoting being well formed up to the cut (as in any truncated stream), so a value after an unescaped quote inside an earlier string is not found, and only whitespace is recognized between a key, its colon and its value, so a pair with a JSON comment in between (some JSON parser versions accept them) is not found.
|
|
57
|
+
- Everything else in a String is sent as received: plain text, `[DONE]`, `event:`/`id:`/`retry:` and comment lines, a `data:` line that is not a JSON object or array, a JSON payload split across several `data:` lines (the continuation lines are not scanned), and newline-delimited JSON streams (no `data:` prefix), except that a whole body starting with `{` or `[` that does not parse as one document, such as a newline-delimited stream, gets the credential-named string scrub described above. Secrets inside free text such as model output are never detected.
|
|
57
58
|
- A String JSON payload nested more than 100 levels deep is replaced with `{"_coolhand_capture_skipped": "nesting_too_deep"}` (as JSON text, since it replaces text). If redacting a payload (or a whole String body) fails for any reason, it is replaced with `{"_coolhand_capture_skipped": "redaction_failed"}` rather than logged unchecked.
|
|
58
59
|
- Streamed bodies are capped by `max_captured_body_bytes` (see [Body Capture Limits](#body-capture-limits)) before redaction, so an over-limit stream is logged as the `body_too_large` placeholder and never scanned.
|
|
59
60
|
|
|
@@ -70,10 +71,11 @@ end
|
|
|
70
71
|
```
|
|
71
72
|
|
|
72
73
|
**How it behaves:**
|
|
73
|
-
- The queue is bounded at 1,000 pending logs. If Coolhand is down long enough to fill it, the *oldest* pending log is dropped (with a log line) rather than blocking your app or growing memory.
|
|
74
|
+
- The queue is bounded at 1,000 pending logs. If Coolhand is down long enough to fill it, the *oldest* pending log is dropped (with a log line) rather than blocking your app or growing memory; the next `Coolhand.flush` then returns `false`.
|
|
74
75
|
- The bound is on the *number* of pending logs, not their size: each holds its captured response body in memory until sent, so a long Coolhand outage under heavy traffic with large responses can hold a lot of memory. Batch jobs use their own lane, so a long-running batch never delays or evicts per-request logs.
|
|
75
76
|
- A forked process (Puma/Unicorn workers, Spring) starts its own worker automatically.
|
|
76
|
-
- Pending logs are flushed at process exit (up to 5 seconds in total, so a batch job still running at exit may be only partly logged). In a short-lived script, or to wait explicitly, call `Coolhand.flush(timeout: 5)` — it returns `true` once everything has been sent.
|
|
77
|
+
- Pending logs are flushed at process exit (up to 5 seconds in total, so a batch job still running at exit may be only partly logged). In a short-lived script, or to wait explicitly, call `Coolhand.flush(timeout: 5)` — it returns `true` once everything has been sent, and `false` if the timeout elapsed first **or** a log could not be delivered (see the retry bullet below).
|
|
78
|
+
- A queued log send that fails with a transient error (a connect failure or connect timeout, or HTTP 429/502/503) is retried twice with a short backoff (so during an outage each queued log can hold its lane for a few extra seconds). Failures where the log may already be stored (a read timeout, a connection reset, a 504) and other 4xx errors are not retried. A log that could not be delivered (a send that failed after retries, a queued job that raised, or a log dropped because the queue was full) makes the next `Coolhand.flush` return `false` (once; it reports failures since the previous flush). Inline sends (`async_logging = false`) are never retried.
|
|
77
79
|
- OpenAI and Vertex batch results are processed as a single background job per batch.
|
|
78
80
|
- `config.debug_mode` always runs inline so printed payloads appear in order.
|
|
79
81
|
- Logs queued but not yet sent are lost if the process is killed hard (`kill -9`, OOM). Set `async_logging = false` if you need delivery before each call returns.
|
|
@@ -138,7 +140,7 @@ Path-anchoring is also how the Azure defaults work: multi-service hosts like `co
|
|
|
138
140
|
|
|
139
141
|
**Note on Azure ML managed online endpoints:** `inference.ml.azure.com` and `inference.ml.azure.us` are intentionally captured *without* a path anchor. Every Azure ML managed online endpoint scores at `/score` regardless of what model sits behind it, so there's no path that distinguishes an LLM deployment from a tabular or vision one — this gem chooses to capture broadly rather than silently miss LLM deployments. If that over-captures for your setup, override `intercept_addresses` to a custom list omitting these two entries.
|
|
140
142
|
|
|
141
|
-
A small number of Google API endpoints use a colon-suffixed path (e.g. `.../gemini-pro:generateContent`) with no host of their own. Those live in the separate `intercept_path_patterns` setting (default: `Coolhand::Configuration::DEFAULT_INTERCEPT_PATH_PATTERNS`) and, unlike `intercept_addresses`, are only checked against the path of requests whose host is already `googleapis.com` or a subdomain of it — and only when `intercept_addresses` still includes at least one `googleapis.com` host. If you override `intercept_addresses` to a list with no Google hosts, `intercept_path_patterns` has no effect and Google API traffic is not captured at all.
|
|
143
|
+
A small number of Google API endpoints use a colon-suffixed path (e.g. `.../gemini-pro:generateContent`) with no host of their own. Those live in the separate `intercept_path_patterns` setting (default: `Coolhand::Configuration::DEFAULT_INTERCEPT_PATH_PATTERNS`) and, unlike `intercept_addresses`, are only checked against the end of the path of requests whose host is already `googleapis.com` or a subdomain of it (a request matches when its normalized path, query string excluded, ends with the pattern; a Cloud Storage object whose name merely contains `:generateContent` mid-name is not captured, though one whose name ends with it still is) — and only when `intercept_addresses` still includes at least one `googleapis.com` host. If you override `intercept_addresses` to a list with no Google hosts, `intercept_path_patterns` has no effect and Google API traffic is not captured at all.
|
|
142
144
|
|
|
143
145
|
`intercept_addresses` is a required allow-list — nothing is captured unless its host matches an entry here. Because of that, `config.intercept_addresses = []` is **not** a supported way to disable capture (it's ignored, with a warning logged, and the previous value is kept). To disable capture entirely, use `config.enabled = false` or `config.capture = false` instead — see [Capture Control](#capture-control) below.
|
|
144
146
|
|
|
@@ -154,7 +156,7 @@ Coolhand.configure do |config|
|
|
|
154
156
|
end
|
|
155
157
|
```
|
|
156
158
|
|
|
157
|
-
Before `exclude_api_patterns`, path-anchored `intercept_addresses` entries (like `api.cohere.com/v2/chat`, see above) and `intercept_path_patterns` are compared, the request path is normalized for matching only (the URL that is sent and logged is unchanged): repeated `/` are collapsed, `.` and `..` segments are resolved (never above the root), and percent-escapes of unreserved characters (`A-Z a-z 0-9 - . _ ~`) are decoded, so `/openai//files`, `/openai/./files` and `/openai/%66iles` are excluded just like `/openai/files`. Reserved escapes such as `%2F` stay encoded, and path matching remains case-sensitive. Your own patterns are compared literally, so write them in normalized form; an exclude pattern also fails closed, matching if either the raw or the normalized path contains it.
|
|
159
|
+
Before `exclude_api_patterns`, path-anchored `intercept_addresses` entries (like `api.cohere.com/v2/chat`, see above) and `intercept_path_patterns` are compared, the request path is normalized for matching only (the URL that is sent and logged is unchanged): repeated `/` are collapsed, `.` and `..` segments are resolved (never above the root), and percent-escapes of unreserved characters (`A-Z a-z 0-9 - . _ ~`) are decoded, so `/openai//files`, `/openai/./files` and `/openai/%66iles` are excluded just like `/openai/files`. Reserved escapes such as `%2F` stay encoded, and path matching remains case-sensitive. Case-sensitivity is deliberate, and the default patterns are written in the providers' canonical lowercase spelling; we have not verified that every covered provider rejects differently-cased paths. If a provider, or a gateway in front of it, routes paths case-insensitively, add the extra spellings to `exclude_api_patterns` yourself. Your own patterns are compared literally, so write them in normalized form; an exclude pattern also fails closed, matching if either the raw or the normalized path contains it.
|
|
158
160
|
|
|
159
161
|
Unlike `intercept_addresses`, `exclude_api_patterns` genuinely supports `= []` — since it only narrows an allow-list that already passed, an empty deny-list just means "exclude nothing," which is safe.
|
|
160
162
|
|
data/docs/declared_workloads.md
CHANGED
|
@@ -24,6 +24,7 @@ end
|
|
|
24
24
|
| `reporter` | String | Who is making the declaration, e.g. the library or app. Used when a record is first created. |
|
|
25
25
|
| `workload` | Hash: `id`, `key`, `name`, `description` | Needs an `id` or a `key`. Other keys are ignored. |
|
|
26
26
|
| `template` | Hash: `id`, `key`, `name` | Needs an `id` or a `key`. Other keys are ignored. |
|
|
27
|
+
| `client_unique_id` | String | Your own id for the request, so feedback can find it. See [Linking feedback to a request](#linking-feedback-to-a-request). |
|
|
27
28
|
|
|
28
29
|
- `id` refers to an existing record. `key` is a stable string of your choosing; Coolhand finds or creates the record with that key. On a template, `id` wins over `key`.
|
|
29
30
|
- `name`, `description` and `reporter` are used only when a record is **first created**. Declaring never renames or re-attributes an existing record; use `upsert` for that. A display name that is already taken gets a numeric suffix, and names such as "Unmatched" are reserved.
|
|
@@ -35,7 +36,7 @@ end
|
|
|
35
36
|
|
|
36
37
|
### Nesting
|
|
37
38
|
|
|
38
|
-
Blocks nest. Each field (`reporter`, `workload`, `template`) is taken from the innermost block that sets it, and fields an inner block leaves out are inherited (with the one exception below):
|
|
39
|
+
Blocks nest. Each field (`reporter`, `workload`, `template`, `client_unique_id`) is taken from the innermost block that sets it, and fields an inner block leaves out are inherited (with the one exception below):
|
|
39
40
|
|
|
40
41
|
```ruby
|
|
41
42
|
Coolhand.with_context(reporter: "my-app", workload: { key: "Parser#call" }) do
|
|
@@ -49,6 +50,28 @@ A template belongs to a workload, so an inner block that declares a `workload` w
|
|
|
49
50
|
|
|
50
51
|
A `workload` or `template` Hash is replaced as a whole, not merged key by key. An inner `workload: { key: "b" }` inside an outer `workload: { id: "a" }` declares only `b`, rather than a mix of `id` and `key`.
|
|
51
52
|
|
|
53
|
+
### Linking feedback to a request
|
|
54
|
+
|
|
55
|
+
`client_unique_id` stamps an id of your own on every log captured in the block. Pass the same id to `create_feedback` so the feedback can be matched to that request exactly, instead of by fuzzy `original_output` comparison.
|
|
56
|
+
|
|
57
|
+
```ruby
|
|
58
|
+
Coolhand.with_context(workload: { key: "Triage#call" }, client_unique_id: "abc.1") do
|
|
59
|
+
client.chat(...) # logged with client_unique_id "abc.1"
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
Coolhand.feedback_service.create_feedback(
|
|
63
|
+
client_unique_id: "abc.1",
|
|
64
|
+
sentiment: "dislike",
|
|
65
|
+
revised_output: "..."
|
|
66
|
+
)
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
- It must be a non-blank String of at most 255 characters with no control or invisible characters. An invalid value is **ignored** rather than raised: your block still runs and the call is logged, just without the id.
|
|
70
|
+
- Use an id that is unique per request (e.g. `"<call_id>.<n>"`). Every call inside the block carries the same id, so wrap one LLM call per block when you need to tell them apart.
|
|
71
|
+
- Logs are sent in the background by default, so `create_feedback(client_unique_id:)` waits (up to 5 seconds) for the log with that id to finish sending before it sends the feedback; no `Coolhand.flush` is needed. If that log failed to send (remembered until a log with that id is sent successfully), the feedback is skipped and `create_feedback` returns `nil`. This only covers logs queued in the same process; when feedback is sent from another process, make sure the log was delivered first. Pass `raise_on_error: true` to get an exception instead of `nil` (see [docs/feedback.md](feedback.md#knowing-whether-feedback-was-delivered)).
|
|
72
|
+
- It travels as `llm_request_log.client_unique_id`, not inside `declared`, and it works without a `workload` or `template`.
|
|
73
|
+
- Matching happens on the Coolhand server, so whether the id is honoured depends on the server version. What happens when two logs share an id is also decided by the server.
|
|
74
|
+
|
|
52
75
|
### Threads and background logging
|
|
53
76
|
|
|
54
77
|
The context is thread-local, like `Coolhand.with_capture`. It is also fiber-local, so it does not carry into threads, fibers, `Enumerator#next` blocks or async tasks you start inside the block; calls made there are captured without a declaration. The identity is read on the thread that made the LLM call, before the log is queued, so it survives `async_logging` (the default).
|
data/docs/feedback.md
CHANGED
|
@@ -27,6 +27,38 @@ feedback_service.create_feedback(
|
|
|
27
27
|
)
|
|
28
28
|
```
|
|
29
29
|
|
|
30
|
+
To link feedback to a specific request without storing the log ID, tag the request with your own id first:
|
|
31
|
+
|
|
32
|
+
```ruby
|
|
33
|
+
Coolhand.with_context(client_unique_id: 'order-42.1') do
|
|
34
|
+
client.chat(...) # logged with client_unique_id 'order-42.1'
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
feedback_service.create_feedback(client_unique_id: 'order-42.1', sentiment: 'like')
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Logs are sent in the background, so `create_feedback` holds the feedback until the log with that `client_unique_id` has finished sending (up to 5 seconds), then sends it. You don't need to call `Coolhand.flush` first. If that log's send failed (the failure is remembered for later `create_feedback` calls with that id, until a log with it is sent successfully), the feedback is not sent and `create_feedback` returns `nil`, because Coolhand never received the log. When several logs share an id, it waits for all of them and sends if any one was delivered. This ordering only covers logs queued in the same process; if you send feedback from a different process (a background job, say), make sure the log has been delivered first.
|
|
41
|
+
|
|
42
|
+
---
|
|
43
|
+
|
|
44
|
+
## Knowing whether feedback was delivered
|
|
45
|
+
|
|
46
|
+
By default `create_feedback` never raises: on any failure (non-2xx response, network error, missing API key) it logs the problem, unless `config.silent` is set, and returns `nil`. On success it returns the parsed response, so `nil` means the feedback was not stored (or, in `debug_mode`, was deliberately not sent).
|
|
47
|
+
|
|
48
|
+
Pass `raise_on_error: true` when you need to tell lost feedback from delivered feedback, for example to retry:
|
|
49
|
+
|
|
50
|
+
```ruby
|
|
51
|
+
begin
|
|
52
|
+
feedback_service.create_feedback(client_unique_id: 'order-42.1', sentiment: 'like', raise_on_error: true)
|
|
53
|
+
rescue Coolhand::HttpError => e
|
|
54
|
+
e.status # 422, 500, ...: the API's answer (e.body has the response body)
|
|
55
|
+
rescue Coolhand::Error => e
|
|
56
|
+
# no API key, or a network error
|
|
57
|
+
end
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Feedback is never retried automatically, because repeating the POST could store it twice; retrying is up to you. With a `client_unique_id`, `create_feedback` already waits for that log when it was queued in the same process, and with `raise_on_error: true` it raises a `Coolhand::Error` instead of returning `nil` when that log failed to send. A `client_unique_id` that matches no log yet is the common reason to retry feedback sent from another process: make sure the log was delivered first (`Coolhand.flush` in the process that logged it returns `false` when a queued log was not delivered: it failed to send after retrying transient errors, raised in its job, or was dropped from a full queue).
|
|
61
|
+
|
|
30
62
|
---
|
|
31
63
|
|
|
32
64
|
## Field Reference
|
|
@@ -41,7 +73,7 @@ These fields identify which LLM request the feedback refers to. Use the most spe
|
|
|
41
73
|
|---|---|---|
|
|
42
74
|
| `llm_request_log_id` | Exact | Hashid returned when the original request was logged (a raw integer FK is also still accepted for backward compatibility). Most reliable. |
|
|
43
75
|
| `llm_provider_unique_id` | Exact | The provider's own request ID (e.g. `x-request-id` from Anthropic or OpenAI). |
|
|
44
|
-
| `client_unique_id` | Exact | Your own
|
|
76
|
+
| `client_unique_id` | Exact | Your own identifier for the request. Stamp it on the log with [`Coolhand.with_context(client_unique_id:)`](declared_workloads.md#linking-feedback-to-a-request), then pass the same value here. |
|
|
45
77
|
| `original_output` | Fuzzy | The raw text the LLM produced. Used for fuzzy matching when no ID is available — less reliable. |
|
|
46
78
|
|
|
47
79
|
### Quality Signals
|
data/docs/openai.md
CHANGED
|
@@ -71,6 +71,8 @@ Each batch item is logged with `source_api: "openai"` and the `model` from the i
|
|
|
71
71
|
|
|
72
72
|
Each item's request body and response body are capped separately by [`max_captured_body_bytes`](configuration.md#body-capture-limits): one over the limit is logged as a `{"_coolhand_capture_skipped" => "body_too_large", ...}` placeholder (the item itself is still logged, and `model` is still taken from the full request body). See [Body Capture Limits](configuration.md#body-capture-limits) for the other placeholders. When the OpenAI client returns a result file as a String or IO, it is read and parsed one JSONL line at a time; a client that returns the file already parsed (`ruby-openai` does) has loaded it in full before Coolhand sees it. A malformed line is skipped and counted in an error log, and the other lines are still processed.
|
|
73
73
|
|
|
74
|
+
To match each output line to its request, Coolhand keeps every input item's (capped) request body in memory until the output file has been read, so peak memory in the process that handled the webhook scales with the size of the batch input (OpenAI limits an input file to 200 MB and 50,000 requests). The work normally runs on the background log queue (inline when `async_logging` is `false` or `debug_mode` is on), and either way it shares your web process's memory. If that matters for very large batches, lower [`max_captured_body_bytes`](configuration.md#body-capture-limits) (an item over the limit is kept as a small placeholder) or run the webhook on a worker process with headroom.
|
|
75
|
+
|
|
74
76
|
The batch ID from the webhook payload and the batch's input/output file IDs are used in calls to the OpenAI API with your `OPENAI_API_KEY`, so they are format-checked first (`batch_...` and `file-...`/`file_...`, letters, digits, `_` and `-` only). An event or batch whose IDs don't match is ignored with an error in `Rails.logger`.
|
|
75
77
|
|
|
76
78
|
## Signature header and secret rotation
|
data/docs/savings.md
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# Reading Realized Savings
|
|
2
|
+
|
|
3
|
+
`Coolhand::SavingsService#get_realized_savings` returns the saving your client has realized by
|
|
4
|
+
switching templates or models: what the requests served by the current templates cost, versus what the
|
|
5
|
+
same requests would have cost on the deprecated versions they replaced. It is the figure the dashboard
|
|
6
|
+
shows. It wraps `GET /api/v2/savings` and is read-only.
|
|
7
|
+
|
|
8
|
+
**Auth:** requires your **private** API key. The public key is rejected exactly like an invalid key.
|
|
9
|
+
|
|
10
|
+
**Scoping:** the client is always derived from your API key. There is deliberately no `client_id`
|
|
11
|
+
keyword, and no keyword of any kind.
|
|
12
|
+
|
|
13
|
+
**Window:** the comparison covers deprecations from the last three months, fixed server-side. It is
|
|
14
|
+
not tied to a request window, so there is no `days_back`. The result is cached server-side for an hour.
|
|
15
|
+
|
|
16
|
+
```ruby
|
|
17
|
+
require "coolhand"
|
|
18
|
+
|
|
19
|
+
Coolhand.configure do |config|
|
|
20
|
+
config.api_key = ENV.fetch("COOLHAND_PRIVATE_API_KEY")
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
savings = Coolhand.savings_service.get_realized_savings
|
|
24
|
+
savings[:total] # => 4.5372 (USD)
|
|
25
|
+
savings[:percent] # => 79.7
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Return value
|
|
29
|
+
|
|
30
|
+
A Symbol-keyed Hash:
|
|
31
|
+
|
|
32
|
+
```ruby
|
|
33
|
+
{
|
|
34
|
+
total: 4.5372, # the saving, USD
|
|
35
|
+
cost_at_previous_versions: 5.6912, # the baseline the saving is measured against, USD
|
|
36
|
+
percent: 79.7, # total as a share of the baseline, one decimal; 0.0 when the baseline is 0
|
|
37
|
+
workloads: [
|
|
38
|
+
{
|
|
39
|
+
id: "xwjm0lgsdmy4", # workload hashid, same as search_workloads
|
|
40
|
+
name: "Help Center Article Suggester",
|
|
41
|
+
savings: 2.0437,
|
|
42
|
+
cost_at_previous_versions: 3.0402,
|
|
43
|
+
active_requests: 182
|
|
44
|
+
}
|
|
45
|
+
]
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Money values are USD floats rounded to 4 decimals. `workloads` lists only workloads with a template
|
|
50
|
+
deprecated in the last three months, and every row always carries all five keys. A client with nothing
|
|
51
|
+
to compare gets `{ total: 0.0, cost_at_previous_versions: 0.0, percent: 0.0, workloads: [] }`, which is
|
|
52
|
+
real zero savings.
|
|
53
|
+
|
|
54
|
+
## Errors
|
|
55
|
+
|
|
56
|
+
`Coolhand::HttpError` carries `#status` and `#body` on a non-2xx response.
|
|
57
|
+
|
|
58
|
+
| status | when |
|
|
59
|
+
|---|---|
|
|
60
|
+
| `401` | No API key, an invalid key, or the public key. |
|
|
61
|
+
| `503` | The comparison could not be computed right now. Retryable. |
|
|
62
|
+
|
|
63
|
+
**A `503` is not zero savings.** Do not map it to zeros; show it as an error and retry.
|
|
64
|
+
`Coolhand::Error` covers no API key configured, a transport failure, and a body that is not a JSON
|
|
65
|
+
object.
|
|
66
|
+
|
|
67
|
+
## Combining it with workload metrics
|
|
68
|
+
|
|
69
|
+
`savings` is **not windowed**, but a workload's `metrics` from
|
|
70
|
+
`search_workloads(include_metrics: true, days_back: N)` are. A workload's `savings` can therefore exceed
|
|
71
|
+
its windowed `metrics[:total_cost]`; do not read the two as a ratio over the same period. Join the two
|
|
72
|
+
on `id` to build a per-workload ROI view:
|
|
73
|
+
|
|
74
|
+
```ruby
|
|
75
|
+
# Archived and system workloads can still carry realized savings, so include them or their rows go unmatched.
|
|
76
|
+
workloads = Coolhand.workload_service.search_workloads(
|
|
77
|
+
include_metrics: true, days_back: 30, include_archived: true, include_system: true, per: 100
|
|
78
|
+
).workloads
|
|
79
|
+
savings = Coolhand.savings_service.get_realized_savings
|
|
80
|
+
|
|
81
|
+
savings_by_id = savings[:workloads].to_h { |row| [row[:id], row] }
|
|
82
|
+
|
|
83
|
+
roi = workloads.map do |workload|
|
|
84
|
+
{
|
|
85
|
+
id: workload[:id],
|
|
86
|
+
name: workload[:name],
|
|
87
|
+
spend_last_30_days: workload.dig(:metrics, :total_cost), # windowed
|
|
88
|
+
realized_savings: savings_by_id.dig(workload[:id], :savings) || 0 # not windowed
|
|
89
|
+
}
|
|
90
|
+
end
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
This reads one page of up to 100 workloads; `search_workloads` is paged (`page`, `per`), so repeat the
|
|
94
|
+
call while `pagination.has_next_page` is true for a client with more. The `get_client_roi_summary` MCP
|
|
95
|
+
tool performs the same join over the two endpoints.
|
data/lib/coolhand/api_service.rb
CHANGED
|
@@ -5,6 +5,8 @@ require "uri"
|
|
|
5
5
|
require "json"
|
|
6
6
|
require_relative "collector"
|
|
7
7
|
require_relative "errors"
|
|
8
|
+
require_relative "log_queue"
|
|
9
|
+
require_relative "post_delivery"
|
|
8
10
|
require_relative "read_requests"
|
|
9
11
|
require_relative "response_warnings"
|
|
10
12
|
|
|
@@ -14,11 +16,23 @@ module Coolhand
|
|
|
14
16
|
# log and return nil.
|
|
15
17
|
include ReadRequests
|
|
16
18
|
include ResponseWarnings
|
|
19
|
+
include PostDelivery
|
|
17
20
|
|
|
18
21
|
# Caps how much of a failed response body is interpolated into a log line or an exception
|
|
19
22
|
# message. Without it an oversized body from a proxy or gateway becomes the message.
|
|
20
23
|
ERROR_BODY_LIMIT = 2000
|
|
21
24
|
|
|
25
|
+
# How much of a failed response body is sanitized before it is cut to ERROR_BODY_LIMIT
|
|
26
|
+
# characters (a character is at most 4 bytes).
|
|
27
|
+
ERROR_BODY_SCAN_BYTES = ERROR_BODY_LIMIT * 4
|
|
28
|
+
|
|
29
|
+
FEEDBACK_ID_LABELS = {
|
|
30
|
+
llm_request_log_id: "LLM Request Log ID",
|
|
31
|
+
llm_provider_unique_id: "Provider Unique ID",
|
|
32
|
+
client_unique_id: "Client Unique ID"
|
|
33
|
+
}.freeze
|
|
34
|
+
private_constant :FEEDBACK_ID_LABELS
|
|
35
|
+
|
|
22
36
|
attr_reader :api_endpoint
|
|
23
37
|
|
|
24
38
|
def initialize(endpoint = "v2/llm_request_logs")
|
|
@@ -38,7 +52,7 @@ module Coolhand
|
|
|
38
52
|
log JSON.pretty_generate(sanitize_payload_for_json(payload))
|
|
39
53
|
nil
|
|
40
54
|
else
|
|
41
|
-
result = send_request(payload, "✅ Successfully sent request metadata")
|
|
55
|
+
result = send_request(payload, "✅ Successfully sent request metadata", background: LogQueue.worker_thread?)
|
|
42
56
|
log_response_warnings(result)
|
|
43
57
|
result
|
|
44
58
|
end
|
|
@@ -78,53 +92,6 @@ module Coolhand
|
|
|
78
92
|
}
|
|
79
93
|
end
|
|
80
94
|
|
|
81
|
-
def send_request(payload, success_message)
|
|
82
|
-
return nil if missing_api_key?
|
|
83
|
-
|
|
84
|
-
uri = URI.parse(@api_endpoint)
|
|
85
|
-
http = Net::HTTP.new(uri.host, uri.port)
|
|
86
|
-
http.use_ssl = (uri.scheme == "https")
|
|
87
|
-
# Bound worst-case latency: with async_logging off this call happens inline in
|
|
88
|
-
# the intercepted request's path (otherwise it ties up the background log
|
|
89
|
-
# worker), so a slow/unreachable Coolhand backend must not hang for Ruby's
|
|
90
|
-
# ~60s Net::HTTP defaults (a stalled upload hits write_timeout).
|
|
91
|
-
http.open_timeout = 5
|
|
92
|
-
http.read_timeout = 5
|
|
93
|
-
http.write_timeout = 5
|
|
94
|
-
|
|
95
|
-
request = Net::HTTP::Post.new(uri.request_uri)
|
|
96
|
-
apply_headers(request, create_request_options(payload))
|
|
97
|
-
|
|
98
|
-
# Clean payload and ensure UTF-8 encoding before JSON generation
|
|
99
|
-
cleaned_payload = sanitize_payload_for_json(payload)
|
|
100
|
-
json_body = JSON.generate(cleaned_payload)
|
|
101
|
-
|
|
102
|
-
# Ensure the request body is properly encoded as UTF-8
|
|
103
|
-
request.body = json_body.force_encoding("UTF-8")
|
|
104
|
-
|
|
105
|
-
begin
|
|
106
|
-
# This request goes through the same patched Net::HTTP as the host
|
|
107
|
-
# app's real LLM calls. Without this, a base_url/intercept_addresses
|
|
108
|
-
# configuration that also matches Coolhand's own API host would
|
|
109
|
-
# re-intercept this log-shipping call, generating a second log
|
|
110
|
-
# request that itself gets intercepted, and so on — unbounded
|
|
111
|
-
# request amplification.
|
|
112
|
-
response = Coolhand.without_capture { http.request(request) }
|
|
113
|
-
|
|
114
|
-
if response.is_a?(Net::HTTPSuccess)
|
|
115
|
-
result = JSON.parse(response.body, symbolize_names: true)
|
|
116
|
-
log success_message
|
|
117
|
-
result
|
|
118
|
-
else
|
|
119
|
-
log "❌ Request failed: #{response.code} - #{format_error_body(response.body)}"
|
|
120
|
-
nil
|
|
121
|
-
end
|
|
122
|
-
rescue StandardError => e
|
|
123
|
-
log "❌ Request error: #{e.message}"
|
|
124
|
-
nil
|
|
125
|
-
end
|
|
126
|
-
end
|
|
127
|
-
|
|
128
95
|
def log(*args)
|
|
129
96
|
puts args.join(" ") unless silent
|
|
130
97
|
end
|
|
@@ -133,8 +100,10 @@ module Coolhand
|
|
|
133
100
|
log("═" * 60) unless silent
|
|
134
101
|
end
|
|
135
102
|
|
|
136
|
-
|
|
137
|
-
|
|
103
|
+
# Returns the parsed response, or nil on failure (and in debug mode, where nothing is sent). With
|
|
104
|
+
# `raise_on_error`, a failure raises {Coolhand::HttpError} / {Coolhand::Error} instead.
|
|
105
|
+
def create_feedback(feedback, collection_method = nil, raise_on_error: false)
|
|
106
|
+
return reject_missing_key(raise_on_error) if !debug_mode? && missing_api_key?
|
|
138
107
|
|
|
139
108
|
normalized = normalize_feedback_sentiment(feedback)
|
|
140
109
|
feedback_with_collector = add_collector_to_data(normalized, collection_method)
|
|
@@ -151,10 +120,8 @@ module Coolhand
|
|
|
151
120
|
log JSON.pretty_generate(payload)
|
|
152
121
|
nil
|
|
153
122
|
else
|
|
154
|
-
result = send_request(
|
|
155
|
-
|
|
156
|
-
"✅ Successfully created feedback with ID: #{feedback[:llm_request_log_id] || 'N/A'}"
|
|
157
|
-
)
|
|
123
|
+
result = send_request(payload, "✅ Successfully created feedback #{feedback_identifier(feedback)}".strip,
|
|
124
|
+
raise_on_error: raise_on_error)
|
|
158
125
|
|
|
159
126
|
log_separator
|
|
160
127
|
|
|
@@ -179,10 +146,7 @@ module Coolhand
|
|
|
179
146
|
log JSON.pretty_generate(payload)
|
|
180
147
|
nil
|
|
181
148
|
else
|
|
182
|
-
result = send_request(
|
|
183
|
-
payload,
|
|
184
|
-
"✅ Successfully logged to API"
|
|
185
|
-
)
|
|
149
|
+
result = send_request(payload, "✅ Successfully logged to API", background: LogQueue.worker_thread?)
|
|
186
150
|
|
|
187
151
|
puts "✅ Successfully logged to API with ID: #{result[:id]}" if result && !silent
|
|
188
152
|
|
|
@@ -220,9 +184,12 @@ module Coolhand
|
|
|
220
184
|
def format_error_body(body)
|
|
221
185
|
return nil if body.nil?
|
|
222
186
|
|
|
223
|
-
|
|
187
|
+
# The body is server-controlled and ends up on the host's stdout, so strip control characters.
|
|
188
|
+
# Only a bounded prefix is sanitized, so a multi-megabyte body costs no more than a small one.
|
|
189
|
+
raw = body.to_s
|
|
190
|
+
text = strip_control_characters(raw.byteslice(0, ERROR_BODY_SCAN_BYTES))
|
|
224
191
|
return "#{text[0..200]}... [HTML error page truncated]" if text.include?("<!DOCTYPE html>")
|
|
225
|
-
return text if text.length <= ERROR_BODY_LIMIT
|
|
192
|
+
return text if text.length <= ERROR_BODY_LIMIT && raw.bytesize <= ERROR_BODY_SCAN_BYTES
|
|
226
193
|
|
|
227
194
|
"#{text[0, ERROR_BODY_LIMIT]}... [truncated]"
|
|
228
195
|
end
|
|
@@ -276,17 +243,27 @@ module Coolhand
|
|
|
276
243
|
feedback.except(:like).merge(sentiment: sentiment)
|
|
277
244
|
end
|
|
278
245
|
|
|
246
|
+
# The identifier the feedback is matched by, as [field, value]; nil when it has none.
|
|
247
|
+
def feedback_match(feedback)
|
|
248
|
+
field = FEEDBACK_ID_LABELS.keys.find { |name| feedback[name] }
|
|
249
|
+
[field, feedback[field]] if field
|
|
250
|
+
end
|
|
251
|
+
|
|
252
|
+
# For the success message; "" when the feedback has no identifier.
|
|
253
|
+
def feedback_identifier(feedback)
|
|
254
|
+
field, value = feedback_match(feedback)
|
|
255
|
+
field ? "(#{FEEDBACK_ID_LABELS[field]}: #{value})" : ""
|
|
256
|
+
end
|
|
257
|
+
|
|
258
|
+
def feedback_announcement(feedback)
|
|
259
|
+
field, value = feedback_match(feedback)
|
|
260
|
+
field ? "\n📝 CREATING FEEDBACK for #{FEEDBACK_ID_LABELS[field]}: #{value}" : "\n📝 CREATING FEEDBACK"
|
|
261
|
+
end
|
|
262
|
+
|
|
279
263
|
def log_feedback_info(feedback)
|
|
280
264
|
return if silent
|
|
281
265
|
|
|
282
|
-
|
|
283
|
-
if feedback[:llm_request_log_id]
|
|
284
|
-
puts "\n📝 CREATING FEEDBACK for LLM Request Log ID: #{feedback[:llm_request_log_id]}"
|
|
285
|
-
elsif feedback[:llm_provider_unique_id]
|
|
286
|
-
puts "\n📝 CREATING FEEDBACK for Provider Unique ID: #{feedback[:llm_provider_unique_id]}"
|
|
287
|
-
else
|
|
288
|
-
puts "\n📝 CREATING FEEDBACK"
|
|
289
|
-
end
|
|
266
|
+
puts feedback_announcement(feedback)
|
|
290
267
|
|
|
291
268
|
puts "💬 Sentiment: #{feedback[:sentiment]}" if feedback[:sentiment]
|
|
292
269
|
|