Skip to content

The platform for continuously improving AI agents.

1.9 KB
Raw Blame
import json
import re
from os.path import commonprefix

FULL = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
PARTIAL = re.compile(r"[0-9a-f]{8}-[0-9a-f-]{1,27}")
STRUCTURAL = set("}],\"' \n\t")


def shown(messages):
    """Every identifier present in the text an agent has been sent."""
    return set(FULL.findall(json.dumps(messages, default=str)))


def restore(text, known):
    whole = FULL.match(text)
    # A dropped closing quote leaves what followed inside the value, starting with the
    # delimiter that should have come after it.
    if whole and text[36:37] and text[36] in STRUCTURAL:
        return whole.group()
    if whole or not PARTIAL.fullmatch(text):
        return text
    matches = [identifier for identifier in known() if dropped(text, identifier)]
    return matches[0] if len(matches) == 1 else text


def dropped(damaged, identifier):
    """Whether ``damaged`` is ``identifier`` with one run of characters left out."""
    kept = len(commonprefix([damaged, identifier]))
    return identifier.endswith(damaged[kept:])


def repair(arguments, messages):
    """Restore identifiers a model damaged while copying them into tool arguments.

    Trailing punctuation is removed from a complete identifier. An identifier with one run
    of characters left out is completed only when exactly one identifier the agent was shown
    fits it; anything else is left for validation to reject.
    """
    cache = []

    def known():
        if not cache:
            cache.append(shown(messages))
        return cache[0]

    def walk(value):
        if isinstance(value, dict):
            return {key: walk(item) for key, item in value.items()}
        if isinstance(value, list):
            return [walk(item) for item in value]
        if isinstance(value, str) and len(value) > 9:
            return restore(value, known)
        return value

    return walk(arguments)