Add streaming support and change the explorer push call to be async.

This commit is contained in:
Hemang
2025-02-04 12:09:14 +01:00
parent be934bc07c
commit 9c3937183e
2 changed files with 231 additions and 47 deletions
+28 -14
View File
@@ -3,13 +3,14 @@
import os
from typing import Any, Dict, List
from fastapi import HTTPException
from invariant_sdk.client import Client
import httpx
from invariant_sdk.types.push_traces import PushTracesRequest
DEFAULT_API_URL = "https://explorer.invariantlabs.ai"
PUSH_ENDPOINT = "/api/v1/push/trace"
def push_trace(
async def push_trace(
messages: List[Dict[str, Any]],
dataset_name: str,
invariant_authorization: str,
@@ -19,19 +20,32 @@ def push_trace(
Args:
messages (List[Dict[str, Any]]): List of messages to push.
dataset_name (str): Name of the dataset.
invariant_authorization (str): Authorization token.
invariant_authorization (str): Authorization token from the
invariant-authorization header.
Returns:
Dict[str, str]: Response containing the trace ID.
"""
api_url = os.getenv("INVARIANT_API_URL", DEFAULT_API_URL)
api_key = invariant_authorization.split("Bearer ")[1]
client = Client(api_url=api_url, api_key=api_key)
try:
# TODO: Change this to the async version once that is available
push_trace_response = client.create_request_and_push_trace(
messages=messages, dataset=dataset_name
api_url = os.getenv("INVARIANT_API_URL", DEFAULT_API_URL).rstrip("/")
request = PushTracesRequest(messages=messages, dataset=dataset_name)
async with httpx.AsyncClient() as client:
explorer_push_request = client.build_request(
"POST",
f"{api_url}{PUSH_ENDPOINT}",
json=request.to_json(),
headers={
"Authorization": f"{invariant_authorization}",
"Accept": "application/json",
},
)
return {"trace_id": push_trace_response.id[0]}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) from e
try:
response = await client.send(explorer_push_request)
response.raise_for_status()
return response.json()
except httpx.HTTPStatusError as e:
print(f"Failed to push trace: {e.response.text}")
return {"error": str(e)}
except Exception as e:
print(f"Unexpected error pushing trace: {str(e)}")
return {"error": str(e)}