Skip to content

The platform for continuously improving AI agents.

6.8 KB
Raw Blame
import json

import openai
from asgiref.sync import sync_to_async
from django.core import signing
from django.http import HttpResponse, JsonResponse, StreamingHttpResponse
from django.views.decorators.csrf import csrf_exempt
from drf_spectacular.utils import extend_schema
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed, ValidationError
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from overbae.api.research_runtime_serializers import (
    EventProjectionSerializer,
    EventReceiptSerializer,
    MessageAcknowledgementSerializer,
    NativeDispatchSerializer,
    NativeResultSerializer,
    RuntimeBootstrapSerializer,
    RuntimeHeartbeatSerializer,
)
from overbae.core.errors import InputValidationError
from overbae.core.llms import openrouter_client
from overbae.models import ResearchAgent
from overbae.services import research_runtime


class RuntimeAuthentication(BaseAuthentication):
    def authenticate(self, request):
        scheme, _, value = request.headers.get("Authorization", "").partition(" ")
        if scheme != "Bearer" or not value:
            raise AuthenticationFailed("A research runtime token is required")
        try:
            agent, identity = research_runtime.authenticate(value)
        except (signing.BadSignature, ResearchAgent.DoesNotExist, KeyError, ValueError, TypeError):
            raise AuthenticationFailed("The research runtime token is invalid or expired") from None
        return agent.assignment.created_by, identity

    def authenticate_header(self, request):
        return "Bearer"


class RuntimeView(APIView):
    authentication_classes = [RuntimeAuthentication]
    permission_classes = [IsAuthenticated]

    def handle_exception(self, exc):
        if isinstance(exc, InputValidationError):
            exc = ValidationError(str(exc))
        return super().handle_exception(exc)


class NativeDispatchView(RuntimeView):
    @extend_schema(exclude=True)
    def post(self, request):
        incoming = NativeDispatchSerializer(data=request.data)
        incoming.is_valid(raise_exception=True)
        result = research_runtime.dispatch(request.auth, **incoming.validated_data)
        return Response(NativeResultSerializer(result).data)


class EventProjectionView(RuntimeView):
    @extend_schema(exclude=True)
    def post(self, request):
        incoming = EventProjectionSerializer(data=request.data)
        incoming.is_valid(raise_exception=True)
        saved = research_runtime.project_event(request.auth, **incoming.validated_data)
        return Response(
            EventReceiptSerializer({"event_id": saved.pk, "sequence": saved.sdk_sequence}).data
        )


class RuntimeBootstrapView(RuntimeView):
    @extend_schema(exclude=True)
    def post(self, request):
        return Response(RuntimeBootstrapSerializer(research_runtime.bootstrap(request.auth)).data)


class RuntimeHeartbeatView(RuntimeView):
    @extend_schema(exclude=True)
    def post(self, request):
        return Response(RuntimeHeartbeatSerializer(research_runtime.heartbeat(request.auth)).data)


class MessageAcknowledgementView(RuntimeView):
    @extend_schema(exclude=True)
    def post(self, request):
        incoming = MessageAcknowledgementSerializer(data=request.data)
        incoming.is_valid(raise_exception=True)
        research_runtime.acknowledge_message(request.auth, **incoming.validated_data)
        return Response(status=204)


def model_error(status, message):
    return JsonResponse({"error": {"message": message}}, status=status)


@csrf_exempt
async def model_completion(request):
    """The runner's OpenAI-compatible chat completions. Each is admitted against its run's
    model-call limit, relayed to OpenRouter, and charged to the run that made it."""
    if request.method != "POST":
        return model_error(405, "Send a POST chat completion request")
    scheme, _, value = request.headers.get("Authorization", "").partition(" ")
    try:
        if scheme != "Bearer" or not value:
            raise ValueError
        _, identity = await sync_to_async(research_runtime.authenticate_model)(value)
    except (signing.BadSignature, ResearchAgent.DoesNotExist, KeyError, ValueError, TypeError):
        return model_error(401, "The research model key is invalid or expired")
    try:
        body = json.loads(request.body)
        action, upstream = await sync_to_async(research_runtime.admit_model_call)(identity, body)
    except json.JSONDecodeError:
        return model_error(400, "Send a JSON chat completion request")
    except research_runtime.ModelCallRefusedError as exc:
        return model_error(429, f"The run allows no more model calls: {exc.detail}")
    except InputValidationError as exc:
        return model_error(400, exc.detail)
    settle = sync_to_async(research_runtime.settle_model_call)
    # OpenRouter reports what it billed only when asked.
    options = {"extra_body": {"usage": {"include": True}}}
    if not upstream.get("stream"):
        try:
            response = await openrouter_client().chat.completions.create(**upstream, **options)
        except openai.APIStatusError as exc:
            await settle(
                action, generation=None, usage=None, model=upstream["model"], error=str(exc)
            )
            return model_error(exc.status_code, "The model provider refused the request")
        except openai.OpenAIError as exc:
            await settle(
                action, generation=None, usage=None, model=upstream["model"], error=str(exc)
            )
            return model_error(502, "The model provider did not answer")
        await settle(action, generation=response.id, usage=response.usage, model=response.model)
        return HttpResponse(
            response.model_dump_json(exclude_none=True), content_type="application/json"
        )

    async def events():
        generation = usage = served = error = None
        try:
            stream = await openrouter_client().chat.completions.create(**upstream, **options)
            async for chunk in stream:
                generation = generation or chunk.id
                usage, served = chunk.usage or usage, chunk.model or served
                yield f"data: {chunk.model_dump_json(exclude_none=True)}\n\n"
            yield "data: [DONE]\n\n"
        except openai.OpenAIError as exc:
            error = str(exc)
            failure = {"error": {"message": "The model provider stopped the response"}}
            yield f"data: {json.dumps(failure)}\n\n"
        finally:
            await settle(
                action,
                generation=generation,
                usage=usage,
                model=served or upstream["model"],
                error=error,
            )

    return StreamingHttpResponse(events(), content_type="text/event-stream")