Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ Calls record `service_tier` separately from `requested_service_tier`: requesting

Interrupted Anthropic streams retain available input/cache usage and message IDs, plus `http_request_id` when the SDK exposes it. `usage_complete: false` marks observed usage as incomplete; it does not establish the final charge or mean the request was free.

Search usage is retained independently of text capture: OpenAI search-call counts, Anthropic server-tool usage, and Google grounding-query counts. Perplexity Responses capture uses invocation counters, with search-result items as a fallback. Clients using `https://api.perplexity.ai` are detected automatically; use `metergraph.wrap(client, provider="perplexity")` when a gateway hides the provider. Perplexity Agent and legacy Sonar calls are identified separately. Agent search type is recorded when explicitly set on the tool; missing evidence remains unknown. Prices are resolved by the receiver.
Search usage is retained independently of text capture: OpenAI search-call counts, Anthropic server-tool usage, and Google grounding-query counts. Perplexity Responses capture uses invocation counters, with search-result items as a fallback. Clients using `https://api.perplexity.ai` are detected automatically; use `metergraph.wrap(client, provider="perplexity")` when a gateway hides the provider. Perplexity Agent and legacy Sonar calls are identified separately. Agent requests without a model use the native response model when available; explicit request models stay unchanged. Requested and served preset identifiers are retained as `requested_effort` and `served_effort`, including when text capture is disabled. Agent search type is recorded when explicitly set on the tool; missing evidence remains unknown. Prices are resolved by the receiver.


## OpenTelemetry GenAI export
Expand Down
3 changes: 3 additions & 0 deletions python/src/metergraph/_capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

from ._model_evidence import model_evidence
from ._retrieval import retrieval_usage
from ._perplexity_retrieval import perplexity_attribution

from . import _tool_definitions
from ._context import CaptureContext, snapshot
Expand Down Expand Up @@ -1165,6 +1166,8 @@ def finish(
"route_source": self.context.route_source if self.context.route else None,
"provider": self.provider,
"model": self.request.get("model"),
**(perplexity_attribution(self.endpoint, self.request, response, stream_chunks)
if self.provider == "perplexity" else {}),
**_usage(response),
**retrieval_usage(self.provider, self.endpoint, self.request, response, stream_chunks),
# Batch transport confirms billing even if the body reports a default tier.
Expand Down
25 changes: 25 additions & 0 deletions python/src/metergraph/_perplexity_retrieval.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,28 @@ def perplexity_retrieval_usage(endpoint: str, request: dict, values: list, items
types = ["fast"]
search_type = types[0] if types and all(value == types[0] for value in types) and types[0] in {"web", "fast"} else None
return {"retrieval_api": "agent", **({"web_search_calls": searches} if searches is not None else {}), **({"search_type": search_type} if search_type else {})}


def perplexity_attribution(endpoint: str, request: dict, response, chunks=None) -> dict:
"""Preset/profile requests can omit model; native responses name what served them."""
if 'responses' not in endpoint:
return {}
extra = request.get('extra_body')
request = {**request, **extra} if isinstance(extra, Mapping) else request

def text(value):
return isinstance(value, str) and bool(value.strip()) and len(value) <= 256

model = request.get('model')
missing_model = model is None or isinstance(model, str) and not model.strip()
served_effort = None
for body in [value for chunk in chunks or [] for value in (get(chunk, 'response'), chunk)] + [response]:
if missing_model and text(get(body, 'model')):
model = get(body, 'model')
if text(get(body, 'effort')):
served_effort = get(body, 'effort')
return {
**({'model': model} if text(model) else {}),
**({'requested_effort': request['effort']} if text(request.get('effort')) else {}),
**({'served_effort': served_effort} if text(served_effort) else {}),
}
43 changes: 43 additions & 0 deletions python/tests/test_search_usage.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,3 +189,46 @@ def record(request):
assert record({**settings, "tools": tools}).get("search_type") is None
assert record({"effort": "low", "extra_body": {"effort": "ultra"}}).get("search_type") is None
assert record({"extra_body": {"effort": "low", "tools": [{"type": "web_search"}]}}).get("search_type") == "fast"


def test_perplexity_preset_attribution_uses_served_model_without_content_capture():
row = provider_record('perplexity', {
'model': 'openai/example-model', 'effort': 'fast@2026-11-11.0', 'output': [],
'usage': {'input_tokens': 1000, 'output_tokens': 100,
'tool_calls_details': {'search_web': {'invocation': 2}}},
}, request={'model': None, 'effort': 'fast'})
assert row['model'] == 'openai/example-model'
assert row['requested_effort'] == 'fast'
assert row['served_effort'] == 'fast@2026-11-11.0'
assert row['web_search_calls'] == 2
assert row['search_type'] == 'fast'
assert row['request_json'] is None
assert row['response_text'] is None


def test_perplexity_attribution_preserves_models_and_reads_terminal_stream_facts():
response = {'model': 'served-model', 'effort': 'fast@2026-11-11.0'}
assert provider_record('perplexity', response, request={'model': 'requested-model'})['model'] == 'requested-model'
row = provider_record('perplexity', {}, [
{'type': 'response.completed', 'response': response}, {'type': 'response.done'},
], {'model': None, 'extra_body': {'effort': 'fast'}})
assert row['model'] == 'served-model'
assert row['requested_effort'] == 'fast'
assert row['served_effort'] == 'fast@2026-11-11.0'
for provider in ('openai', 'anthropic', 'google'):
other = provider_record(provider, response, request={'model': None, 'effort': 'fast'})
assert other['model'] is None
assert 'requested_effort' not in other
assert 'served_effort' not in other


def test_perplexity_attribution_ignores_malformed_metadata_and_legacy_responses():
for value in (None, '', ' ', 42, [], 'x' * 257):
row = provider_record('perplexity', {'model': value, 'effort': value}, request={'model': None})
assert row['model'] is None
assert 'served_effort' not in row
rows = Rows()
runtime = Runtime(rows, Options(capture_text=False))
runtime.call_state('perplexity', 'chat.completions.create', {}).finish({'model': 'served-model', 'effort': 'fast'})
assert rows.rows[0]['model'] is None
assert 'served_effort' not in rows.rows[0]
2 changes: 1 addition & 1 deletion typescript/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,6 @@ Calls record `service_tier` separately from `requested_service_tier`: requesting

Interrupted Anthropic streams retain available input/cache usage and message IDs, plus `http_request_id` when the SDK exposes it. `usage_complete: false` marks observed usage as incomplete; it does not establish the final charge or mean the request was free.

Search usage is retained independently of text capture: OpenAI search-call counts, Anthropic server-tool usage, and Google grounding-query counts. Perplexity Responses capture uses invocation counters, with search-result items as a fallback. Clients using `https://api.perplexity.ai` are detected automatically; use `wrap(client, { provider: "perplexity" })` when a gateway hides the provider. Perplexity Agent and legacy Sonar calls are identified separately. Agent search type is recorded when explicitly set on the tool; missing evidence remains unknown. Prices are resolved by the receiver.
Search usage is retained independently of text capture: OpenAI search-call counts, Anthropic server-tool usage, and Google grounding-query counts. Perplexity Responses capture uses invocation counters, with search-result items as a fallback. Clients using `https://api.perplexity.ai` are detected automatically; use `wrap(client, { provider: "perplexity" })` when a gateway hides the provider. Perplexity Agent and legacy Sonar calls are identified separately. Agent requests without a model use the native response model when available; explicit request models stay unchanged. Requested and served preset identifiers are retained as `requested_effort` and `served_effort`, including when text capture is disabled. Agent search type is recorded when explicitly set on the tool; missing evidence remains unknown. Prices are resolved by the receiver.

For other OpenAI-compatible clients, pass the actual provider name to `wrap()` (for example, `provider="deepseek"` in Python or `{ provider: "deepseek" }` in TypeScript). Capture uses the OpenAI-compatible methods while preserving that provider identity; no provider SDK dependency or routing change is added.
3 changes: 3 additions & 0 deletions typescript/src/capture.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { perplexityAttribution } from "./perplexity-retrieval.js";
import { retrievalUsage } from "./retrieval.js";
import { modelEvidence } from "./model-evidence.js";

Expand Down Expand Up @@ -935,6 +936,8 @@ export class CaptureRuntime {
route_source: state.context.route ? state.context.routeSource : undefined,
provider: state.provider,
model: state.request.model,
...(state.provider === "perplexity"
? perplexityAttribution(state.endpoint, state.request, response, extra.responseChunks) : {}),
...usage(response),
...retrievalUsage(state.provider, state.endpoint, state.request, response, extra.responseChunks),
// The Batch API confirms billing even when its body reports a default tier.
Expand Down
20 changes: 20 additions & 0 deletions typescript/src/perplexity-retrieval.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,23 @@ export function perplexityRetrievalUsage(endpoint: string, request: Record<strin
const searchType = types.length && types.every(type => type === types[0]) && ['web', 'fast'].includes(types[0]) ? types[0] : undefined;
return {retrieval_api: 'agent', ...(searches !== undefined ? {web_search_calls: searches} : {}), ...(searchType ? {search_type: searchType} : {})};
}

// Preset/profile requests can omit model; the native response names what served them.
export function perplexityAttribution(endpoint: string, request: Record<string, unknown>, response: unknown, chunks: unknown[] = []): Record<string, unknown> {
if (!endpoint.includes('responses')) return {};
const extra = request.extra_body;
if (extra && typeof extra === 'object' && !Array.isArray(extra)) request = {...request, ...extra};
const text = (value: unknown): value is string => typeof value === 'string' && value.trim().length > 0 && value.length <= 256;
const missingModel = request.model == null || typeof request.model === 'string' && !request.model.trim();
let model = request.model;
let servedEffort: unknown;
for (const body of [...chunks.flatMap(chunk => [get(chunk, 'response'), chunk]), response]) {
if (missingModel && text(get(body, 'model'))) model = get(body, 'model');
if (text(get(body, 'effort'))) servedEffort = get(body, 'effort');
}
return {
...(text(model) ? {model} : {}),
...(text(request.effort) ? {requested_effort: request.effort} : {}),
...(text(servedEffort) ? {served_effort: servedEffort} : {}),
};
}
45 changes: 45 additions & 0 deletions typescript/test/search-usage.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -153,3 +153,48 @@ test('Perplexity active effort levels supply fast search defaults',()=>{
assert.equal(record({effort:'low',extra_body:{effort:'ultra'}}).search_type,undefined);
assert.equal(record({extra_body:{effort:'low',tools:[{type:'web_search'}]}}).search_type,'fast');
});

test('Perplexity preset attribution uses native served model without content capture',()=>{
const row=providerRecord('perplexity',{
model:'openai/example-model',effort:'fast@2026-11-11.0',output:[],
usage:{input_tokens:1000,output_tokens:100,tool_calls_details:{search_web:{invocation:2}}},
},[],{model:undefined,effort:'fast'});
assert.equal(row.model,'openai/example-model');
assert.equal(row.requested_effort,'fast');
assert.equal(row.served_effort,'fast@2026-11-11.0');
assert.equal(row.web_search_calls,2);
assert.equal(row.search_type,'fast');
assert.equal(row.request_json,undefined);
assert.equal(row.response_text,undefined);
});

test('Perplexity attribution preserves explicit models and reads terminal stream facts',()=>{
const response={model:'served-model',effort:'fast@2026-11-11.0'};
assert.equal(providerRecord('perplexity',response,[],{model:'requested-model'}).model,'requested-model');
const row=providerRecord('perplexity',{},[
{type:'response.completed',response}, {type:'response.done'},
],{model:undefined,extra_body:{effort:'fast'}});
assert.equal(row.model,'served-model');
assert.equal(row.requested_effort,'fast');
assert.equal(row.served_effort,'fast@2026-11-11.0');
for (const provider of ['openai','anthropic','google']) {
const other=providerRecord(provider,response,[],{model:undefined,effort:'fast'});
assert.equal(other.model,undefined);
assert.equal(other.requested_effort,undefined);
assert.equal(other.served_effort,undefined);
}
});

test('Perplexity attribution does not invent models from malformed metadata or legacy responses',()=>{
for (const value of [null,'',' ',42,[], 'x'.repeat(257)]) {
const row=providerRecord('perplexity',{model:value,effort:value},[],{model:undefined});
assert.equal(row.model,undefined);
assert.equal(row.served_effort,undefined);
}
const rows=[];
const runtime=new CaptureRuntime({enqueue(row){rows.push(row);return true;}},
{captureText:false,appRoot:'',skipFrames:[],textMaxBytes:32});
runtime.finish(runtime.start('perplexity','chat.completions.create',{}),{model:'served-model',effort:'fast'});
assert.equal(rows[0].model,undefined);
assert.equal(rows[0].served_effort,undefined);
});
Loading