Class: LlmCostTracker::Parsers::Anthropic
- Inherits:
-
Base
- Object
- Base
- LlmCostTracker::Parsers::Anthropic
show all
- Defined in:
- lib/llm_cost_tracker/parsers/anthropic.rb
Constant Summary
collapse
- HOSTS =
%w[api.anthropic.com].freeze
Class Method Summary
collapse
Instance Method Summary
collapse
Methods inherited from Base
#auto_enable_stream_usage?, #model_for, #safe_json_parse, #streaming_request?
#match_uri?, #parsed_uri, #path_matches?, #uri_matches?
Class Method Details
.match?(url) ⇒ Boolean
12
13
14
|
# File 'lib/llm_cost_tracker/parsers/anthropic.rb', line 12
def match?(url)
match_uri?(url, hosts: HOSTS, path_includes: "/v1/messages")
end
|
.provider_names ⇒ Object
16
17
18
|
# File 'lib/llm_cost_tracker/parsers/anthropic.rb', line 16
def provider_names
%w[anthropic]
end
|
Instance Method Details
#parse(request_body:, response_status:, response_body:) ⇒ Object
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
# File 'lib/llm_cost_tracker/parsers/anthropic.rb', line 21
def parse(request_body:, response_status:, response_body:, **)
return nil unless response_status == 200
response = safe_json_parse(response_body)
usage = response["usage"]
return nil unless usage
request = safe_json_parse(request_body)
cache_read = usage["cache_read_input_tokens"].to_i
Event.build(
provider: "anthropic",
provider_response_id: response["id"],
pricing_mode: pricing_mode(request: request, usage: usage),
model: response["model"] || request["model"],
token_usage: token_usage(usage: usage, cache_read: cache_read),
usage_source: :response,
service_line_items: service_line_items(usage)
)
end
|
#parse_stream(response_status:, request_body: nil, events: []) ⇒ Object
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
# File 'lib/llm_cost_tracker/parsers/anthropic.rb', line 42
def parse_stream(response_status:, request_body: nil, events: [], **)
return nil unless response_status == 200
request = safe_json_parse(request_body)
model = find_event_value(events) { |data| data.dig("message", "model") } || request["model"]
usage = stream_usage(events)
response_id = find_event_value(events) { |data| data.dig("message", "id") || data["id"] }
if usage
build_stream_result(
model: model,
usage: usage,
response_id: response_id,
pricing_mode: pricing_mode(request: request, usage: usage)
)
else
build_unknown_stream_usage(
provider: "anthropic",
model: model,
provider_response_id: response_id,
pricing_mode: pricing_mode(request: request, usage: usage)
)
end
end
|
#provider_for(_request_url) ⇒ Object
67
68
69
|
# File 'lib/llm_cost_tracker/parsers/anthropic.rb', line 67
def provider_for(_request_url)
"anthropic"
end
|