Skip to content

The platform for continuously improving AI agents.

7.8 KB
Raw Blame
import json
from itertools import islice

import tiktoken
from django.db.models import Q

from agent_runtime.observations import compact
from overbae.core.errors import InputValidationError
from overbae.models import ResearchAction
from overbae.services import (
    context_graph,
    research_context_authorship,
    research_evidence,
    research_notes,
    research_requests,
)


def brief(agent):
    assignment = agent.assignment
    specification = research_context_authorship.project_record(
        assignment,
        f"research_assignment:{assignment.pk}",
        {"specification": assignment.specification},
    )["specification"]
    instructions = [
        {
            "event": event.pk,
            "text": event.payload.get("instructions") or event.payload.get("message"),
        }
        for event in assignment.events.filter(
            Q(kind="resumed") | Q(kind="agent_message", payload__sender="user")
        ).order_by("pk")
    ]
    return research_notes.project_delegation(
        assignment,
        {
            "delegation_provenance": research_notes.delegation(agent),
            "objective": specification.get("objective", ""),
            "current_request": research_requests.current(agent),
            "task": specification.get("task", {}),
            "acceptance": specification.get("acceptance", {}),
            "constraints": specification.get("constraints", {}),
            "your_task": agent.task,
            "user_instructions": instructions,
            "automation_evidence": list(
                assignment.events.filter(kind="trigger_evidence")
                .order_by("pk")
                .values("id", "payload")
            ),
            "working_notes": research_notes.record(agent),
        },
    )


def history(agent, request):
    actions = ResearchAction.objects.filter(agent__assignment=agent.assignment).exclude(
        tool__in={"history", "inspect_action"}
    )
    actions = actions.filter(tool=request.tool) if request.tool else actions.exclude(tool="model")
    if request.state:
        actions = actions.filter(state=request.state)
    # History searches must match the current projection, never hidden retained values.
    from overbae.services.research_tools import source_boundary

    boundary = source_boundary(agent.assignment)
    records = (
        (
            action,
            research_evidence.action_arguments(agent.assignment, action, boundary=boundary),
            research_evidence.action_result(agent.assignment, action, boundary=boundary),
        )
        for action in actions.order_by("created_at", "pk").iterator()
    )
    if request.query:
        query = request.query.casefold()
        records = (
            (action, arguments, result)
            for action, arguments, result in records
            if query in context_graph.canonical([arguments, result]).casefold()
        )
    page = list(islice(records, request.offset, request.offset + request.limit + 1))
    return {
        "actions": [
            {
                "receipt": str(action.pk),
                "agent": str(action.agent_id),
                "tool": action.tool,
                "state": action.state,
                "arguments": compact(arguments, text_limit=1000, items=8)
                if action.tool != "model"
                else {"model": action.arguments.get("model")},
                "result": compact(
                    result,
                    text_limit=2000,
                    items=8,
                ),
            }
            for action, arguments, result in page[: request.limit]
        ],
        "next_offset": request.offset + request.limit if len(page) > request.limit else None,
        "detail_tool": "inspect_action",
    }


def tokens(text):
    # Rows and transcripts may hold a tokenizer's control strings ("<|endoftext|>"): counted
    # here as the text they are, never refused.
    return len(tiktoken.get_encoding("o200k_base").encode(text, disallowed_special=()))


def token_count(history, tools):
    # Exact Responses items replace the normalized assistant fields on the wire.
    projected = [
        {"_responses_output": message["_responses_output"]}
        if message.get("_responses_output")
        else message
        for message in history
    ]
    return tokens(context_graph.canonical([projected, tools]))


ARCHIVED_ACTIONS = 200


def archived(message):
    if message.get("role") != "user":
        return None
    try:
        value = json.loads(message["content"])
    except (ValueError, TypeError):
        return None
    return value.get("archive") if isinstance(value, dict) else None


def ledger(messages):
    """One line per archived tool call: what ran, how it settled and where its receipt is."""
    results = {}
    for message in messages:
        if message.get("role") != "tool":
            continue
        try:
            results[message["tool_call_id"]] = json.loads(message["content"])
        except (ValueError, TypeError):
            results[message["tool_call_id"]] = {}
    entries = []
    for message in messages:
        for call in message.get("tool_calls", []):
            result = results.get(call["id"], {})
            try:
                arguments = json.loads(call["function"]["arguments"])
            except (ValueError, TypeError):
                arguments = {}
            entry = {
                "tool": call["function"]["name"],
                "operation": arguments.get("operation") or arguments.get("name"),
                "status": result.get("status"),
                "receipt": result.get("receipt"),
            }
            error = result.get("error")
            if isinstance(error, dict) and error.get("message"):
                entry["error"] = str(error["message"])[:200]
            entries.append({key: value for key, value in entry.items() if value is not None})
    return entries


def fit(history, tools, *, limit=120000, target=60000):
    """Keep the transcript append-only until it reaches ``limit``, then archive its oldest
    complete turns down to ``target`` in one step.

    The provider caches a request only as an extension of an earlier one, so trimming a
    little on every turn would forfeit the cache on every turn.
    """
    if token_count(history, tools) <= limit:
        return history
    head, body = history[:2], history[2:]
    previous = {"turns": 0, "omitted_actions": 0, "actions": []}
    if body and archived(body[0]):
        previous = archived(body[0])
        body = body[1:]
    turns = [index for index, message in enumerate(body) if message.get("role") == "assistant"]
    candidate = history
    for count, boundary in enumerate(turns[1:], 1):
        actions = previous["actions"] + ledger(body[:boundary])
        candidate = (
            head
            + [
                {
                    "role": "user",
                    "content": json.dumps(
                        {
                            "archive": {
                                "turns": previous["turns"] + count,
                                "omitted_actions": previous["omitted_actions"]
                                + max(0, len(actions) - ARCHIVED_ACTIONS),
                                "actions": actions[-ARCHIVED_ACTIONS:],
                            },
                            "instruction": "These earlier turns left the transcript. Each receipt stays readable with inspect_action, and history searches all of them. Do not repeat completed work.",
                        }
                    ),
                }
            ]
            + body[boundary:]
        )
        if token_count(candidate, tools) <= target:
            return candidate
    if token_count(candidate, tools) <= limit:
        return candidate
    raise InputValidationError(
        "The objective, current evidence and latest complete turn exceed the context budget; no conversation or notes were reset"
    )