← back to invincible-jha__agent-session-linker

Function bodies 227 total

All specs Real LLM only Function bodies
ContextWindowManager.__init__ method · python · L44-L62 (19 LOC)
src/agent_session_linker/middleware/context_window.py
    def __init__(
        self,
        max_tokens: int = 4000,
        max_segments: int = 50,
        role_separator: str = ": ",
        segment_separator: str = "\n\n",
    ) -> None:
        if max_tokens < 1:
            raise ValueError(f"max_tokens must be >= 1, got {max_tokens!r}.")
        if max_segments < 1:
            raise ValueError(f"max_segments must be >= 1, got {max_segments!r}.")

        self.max_tokens = max_tokens
        self.max_segments = max_segments
        self.role_separator = role_separator
        self.segment_separator = segment_separator

        self._window: deque[ContextSegment] = deque()
        self._token_total: int = 0
ContextWindowManager.add method · python · L68-L97 (30 LOC)
src/agent_session_linker/middleware/context_window.py
    def add(self, segment: ContextSegment) -> None:
        """Append a segment to the window, evicting old segments if needed.

        Token count is taken from ``segment.token_count`` when non-zero,
        otherwise estimated from content length.

        Parameters
        ----------
        segment:
            The segment to append.
        """
        segment_tokens = segment.token_count or _estimate_tokens(segment.content)

        # If a single segment is larger than the entire budget, accept it
        # as a lone entry (the window holds at least one segment always).
        if segment_tokens > self.max_tokens and not self._window:
            self._window.append(segment)
            self._token_total += segment_tokens
            return

        # Evict from the front until there is room.
        while self._window and (
            self._token_total + segment_tokens > self.max_tokens
            or len(self._window) >= self.max_segments
        ):
            evicted = sel
ContextWindowManager.get_window method · python · L99-L119 (21 LOC)
src/agent_session_linker/middleware/context_window.py
    def get_window(self) -> str:
        """Render the current window as a formatted string.

        Each segment is rendered as ``"<ROLE>: <content>"`` with segments
        separated by ``self.segment_separator``.

        Returns
        -------
        str
            Formatted context window string.  Empty string when the window
            is empty.
        """
        if not self._window:
            return ""

        parts: list[str] = []
        for segment in self._window:
            role_label = segment.role.upper()
            parts.append(f"{role_label}{self.role_separator}{segment.content}")

        return self.segment_separator.join(parts)
ContextWindowManager.get_segments method · python · L121-L129 (9 LOC)
src/agent_session_linker/middleware/context_window.py
    def get_segments(self) -> list[ContextSegment]:
        """Return a copy of the current window as an ordered list.

        Returns
        -------
        list[ContextSegment]
            Segments from oldest to newest.
        """
        return list(self._window)
ContextWindowManager.token_count method · python · L131-L139 (9 LOC)
src/agent_session_linker/middleware/context_window.py
    def token_count(self) -> int:
        """Return the current cumulative token count in the window.

        Returns
        -------
        int
            Total estimated tokens for all segments in the window.
        """
        return self._token_total
ContextWindowManager.__repr__ method · python · L149-L154 (6 LOC)
src/agent_session_linker/middleware/context_window.py
    def __repr__(self) -> str:
        return (
            f"ContextWindowManager("
            f"segments={len(self._window)}, "
            f"tokens={self._token_total}/{self.max_tokens})"
        )
SessionMiddleware.__init__ method · python · L40-L47 (8 LOC)
src/agent_session_linker/middleware/session_middleware.py
    def __init__(
        self,
        manager: SessionManager,
        auto_create: bool = True,
    ) -> None:
        self._manager = manager
        self.auto_create = auto_create
        self._active_sessions: dict[str, SessionState] = {}
Repobility · code-quality intelligence · https://repobility.com
SessionMiddleware.before_request method · python · L53-L87 (35 LOC)
src/agent_session_linker/middleware/session_middleware.py
    def before_request(self, session_id: str) -> SessionState:
        """Load (or create) the session for ``session_id``.

        The loaded session is cached in-memory for the duration of the
        request and returned for immediate use.

        Parameters
        ----------
        session_id:
            The session identifier for the incoming request.

        Returns
        -------
        SessionState
            The existing or newly created session.

        Raises
        ------
        SessionNotFoundError
            If ``auto_create`` is False and no session exists for
            ``session_id``.
        """
        if self._manager.session_exists(session_id):
            session = self._manager.load_session(session_id)
            logger.debug("SessionMiddleware: loaded session %r", session_id)
        elif self.auto_create:
            session = self._manager.create_session()
            # Force the session ID to match the requested one.
            session.session_
SessionMiddleware.after_request method · python · L89-L137 (49 LOC)
src/agent_session_linker/middleware/session_middleware.py
    def after_request(
        self,
        session_id: str,
        new_context: list[ContextSegment] | str | None = None,
    ) -> str:
        """Persist the session and optionally append new context.

        If ``new_context`` is provided the segments (or single text string)
        are appended to the session before it is saved.

        Parameters
        ----------
        session_id:
            The session identifier used in the preceding ``before_request``
            call.
        new_context:
            Context to append before saving.  May be:
            - A list of ``ContextSegment`` objects appended directly.
            - A plain string added as a single ``"assistant"`` segment.
            - None to save without any new context.

        Returns
        -------
        str
            The ``session_id`` under which the session was saved.

        Raises
        ------
        KeyError
            If ``before_request`` was not called for ``session_id`` in this
     
SessionMiddleware.get_active method · python · L139-L152 (14 LOC)
src/agent_session_linker/middleware/session_middleware.py
    def get_active(self, session_id: str) -> SessionState | None:
        """Return the currently active (in-flight) session, if any.

        Parameters
        ----------
        session_id:
            Session identifier to look up.

        Returns
        -------
        SessionState | None
            The cached session state, or None if not currently active.
        """
        return self._active_sessions.get(session_id)
SessionMiddleware.clear_active method · python · L154-L165 (12 LOC)
src/agent_session_linker/middleware/session_middleware.py
    def clear_active(self, session_id: str) -> None:
        """Discard the cached active session without saving.

        Useful for rolling back a request cycle that encountered an error.

        Parameters
        ----------
        session_id:
            Session identifier to discard.
        """
        self._active_sessions.pop(session_id, None)
        logger.debug("SessionMiddleware: cleared active session %r", session_id)
PluginNotFoundError.__init__ method · python · L55-L62 (8 LOC)
src/agent_session_linker/plugins/registry.py
    def __init__(self, name: str, registry_name: str) -> None:
        self.plugin_name = name
        self.registry_name = registry_name
        super().__init__(
            f"Plugin {name!r} is not registered in the {registry_name!r} registry. "
            f"Available plugins: {name!r} was not found. "
            "Check that the package is installed and its entry-points are declared."
        )
PluginAlreadyRegisteredError.__init__ method · python · L68-L74 (7 LOC)
src/agent_session_linker/plugins/registry.py
    def __init__(self, name: str, registry_name: str) -> None:
        self.plugin_name = name
        self.registry_name = registry_name
        super().__init__(
            f"Plugin {name!r} is already registered in the {registry_name!r} registry. "
            "Use a unique name or explicitly deregister the existing entry first."
        )
PluginRegistry.register method · python · L100-L147 (48 LOC)
src/agent_session_linker/plugins/registry.py
    def register(self, name: str) -> Callable[[type[T]], type[T]]:
        """Return a class decorator that registers the decorated class.

        Parameters
        ----------
        name:
            The unique string key for this plugin.

        Returns
        -------
        Callable[[type[T]], type[T]]
            A decorator that registers the class and returns it unchanged,
            allowing it to remain usable as a normal class.

        Raises
        ------
        PluginAlreadyRegisteredError
            If ``name`` is already in use in this registry.
        TypeError
            If the decorated class does not subclass ``base_class``.

        Example
        -------
        ::

            @registry.register("my-plugin")
            class MyPlugin(BasePlugin):
                ...
        """

        def decorator(cls: type[T]) -> type[T]:
            if name in self._plugins:
                raise PluginAlreadyRegisteredError(name, self._name)
            if not (
PluginRegistry.register_class method · python · L149-L182 (34 LOC)
src/agent_session_linker/plugins/registry.py
    def register_class(self, name: str, cls: type[T]) -> None:
        """Register a class directly without using the decorator syntax.

        This is useful for programmatic registration, such as inside
        ``load_entrypoints``.

        Parameters
        ----------
        name:
            The unique string key for this plugin.
        cls:
            The class to register. Must subclass ``base_class``.

        Raises
        ------
        PluginAlreadyRegisteredError
            If ``name`` is already registered.
        TypeError
            If ``cls`` is not a subclass of ``base_class``.
        """
        if name in self._plugins:
            raise PluginAlreadyRegisteredError(name, self._name)
        if not (isinstance(cls, type) and issubclass(cls, self._base_class)):
            raise TypeError(
                f"Cannot register {cls!r} under {name!r}: "
                f"it must be a subclass of {self._base_class.__name__}."
            )
        self._plugins[na
If a scraper extracted this row, it came from Repobility (https://repobility.com)
PluginRegistry.deregister method · python · L184-L200 (17 LOC)
src/agent_session_linker/plugins/registry.py
    def deregister(self, name: str) -> None:
        """Remove a plugin from the registry.

        Parameters
        ----------
        name:
            The key previously passed to ``register``.

        Raises
        ------
        PluginNotFoundError
            If ``name`` is not currently registered.
        """
        if name not in self._plugins:
            raise PluginNotFoundError(name, self._name)
        del self._plugins[name]
        logger.debug("Deregistered plugin %r from registry %r", name, self._name)
PluginRegistry.get method · python · L206-L227 (22 LOC)
src/agent_session_linker/plugins/registry.py
    def get(self, name: str) -> type[T]:
        """Return the class registered under ``name``.

        Parameters
        ----------
        name:
            The key used when registering the plugin.

        Returns
        -------
        type[T]
            The registered class (not an instance).

        Raises
        ------
        PluginNotFoundError
            If no plugin is registered under ``name``.
        """
        try:
            return self._plugins[name]
        except KeyError:
            raise PluginNotFoundError(name, self._name) from None
PluginRegistry.list_plugins method · python · L229-L237 (9 LOC)
src/agent_session_linker/plugins/registry.py
    def list_plugins(self) -> list[str]:
        """Return a sorted list of all registered plugin names.

        Returns
        -------
        list[str]
            Plugin names in alphabetical order.
        """
        return sorted(self._plugins)
PluginRegistry.__repr__ method · python · L247-L252 (6 LOC)
src/agent_session_linker/plugins/registry.py
    def __repr__(self) -> str:
        return (
            f"PluginRegistry(name={self._name!r}, "
            f"base_class={self._base_class.__name__}, "
            f"plugins={self.list_plugins()})"
        )
PluginRegistry.load_entrypoints method · python · L258-L311 (54 LOC)
src/agent_session_linker/plugins/registry.py
    def load_entrypoints(self, group: str) -> None:
        """Discover and register plugins declared as package entry-points.

        Iterates over all installed distributions that declare entry-points
        in ``group``. Each entry-point value is imported and registered
        under the entry-point name.

        Plugins that are already registered (e.g., from a previous call)
        are skipped with a debug-level log entry rather than raising an
        error. This makes repeated calls to ``load_entrypoints`` idempotent.

        Parameters
        ----------
        group:
            The entry-point group name, e.g. "agent_session_linker.plugins".

        Example
        -------
        In a downstream package's ``pyproject.toml``::

            [agent_session_linker.plugins]
            my-processor = "my_package.processors:MyProcessor"

        Then at runtime::

            registry.load_entrypoints("agent_session_linker.plugins")
        """
        entry_points = import
EnhancedLangChainImporter.__init__ method · python · L71-L78 (8 LOC)
src/agent_session_linker/portability/usf_enhanced.py
    def __init__(
        self,
        extract_tool_calls: bool = True,
        enrich_working_memory: bool = True,
    ) -> None:
        self._extract_tool_calls = extract_tool_calls
        self._enrich_working_memory = enrich_working_memory
        self._base = LangChainImporter()
EnhancedLangChainImporter.import_session method · python · L80-L150 (71 LOC)
src/agent_session_linker/portability/usf_enhanced.py
    def import_session(self, data: dict[str, object]) -> UniversalSession:
        """Convert a LangChain memory dict to an enhanced :class:`UniversalSession`.

        Parameters
        ----------
        data:
            LangChain memory dict (same structure accepted by
            :class:`~agent_session_linker.portable.importers.LangChainImporter`).

        Returns
        -------
        UniversalSession
            With ``framework_source="langchain_enhanced"`` and optional
            enrichment.
        """
        # Base import
        session = self._base.import_session(data)

        # Enrich working memory with input_variables
        working_memory = dict(session.working_memory)
        if self._enrich_working_memory:
            input_vars: dict[str, object] = dict(data.get("input_variables") or {})
            working_memory.update(input_vars)

        # Extract tool calls -> task states
        task_state: list[USFTaskState] = list(session.task_state)
        if self.
EnhancedCrewAIImporter.__init__ method · python · L178-L185 (8 LOC)
src/agent_session_linker/portability/usf_enhanced.py
    def __init__(
        self,
        include_crew_metadata: bool = True,
        map_agents_to_entities: bool = True,
    ) -> None:
        self._include_crew_metadata = include_crew_metadata
        self._map_agents_to_entities = map_agents_to_entities
        self._base = CrewAIImporter()
Want this analysis on your repo? https://repobility.com/scan/
EnhancedCrewAIImporter.import_session method · python · L187-L256 (70 LOC)
src/agent_session_linker/portability/usf_enhanced.py
    def import_session(self, data: dict[str, object]) -> UniversalSession:
        """Convert a CrewAI context dict to an enhanced :class:`UniversalSession`.

        Parameters
        ----------
        data:
            CrewAI context dict.  The top-level may include:

            - ``"crew_name"`` (str): Name of the crew.
            - ``"crew_id"`` (str): Unique crew identifier.
            - ``"agents"`` (list of dicts): Agent definitions.
            - ``"context"`` (dict): As consumed by the base importer.
            - ``"task_results"`` (list): As consumed by the base importer.

        Returns
        -------
        UniversalSession
            With ``framework_source="crewai_enhanced"``.
        """
        session = self._base.import_session(data)

        # Crew metadata
        metadata: dict[str, object] = {"base_framework": "crewai"}
        if self._include_crew_metadata:
            if crew_name := data.get("crew_name"):
                metadata["crew_name"] = str(c
SessionPortabilityKit.__init__ method · python · L283-L290 (8 LOC)
src/agent_session_linker/portability/usf_enhanced.py
    def __init__(self, enhanced: bool = True) -> None:
        self._enhanced = enhanced
        if enhanced:
            self._langchain_importer: object = EnhancedLangChainImporter()
            self._crewai_importer: object = EnhancedCrewAIImporter()
        else:
            self._langchain_importer = LangChainImporter()
            self._crewai_importer = CrewAIImporter()
SessionPortabilityKit.import_langchain method · python · L297-L309 (13 LOC)
src/agent_session_linker/portability/usf_enhanced.py
    def import_langchain(self, data: dict[str, object]) -> UniversalSession:
        """Import a LangChain memory dict.

        Parameters
        ----------
        data:
            LangChain memory dict.

        Returns
        -------
        UniversalSession
        """
        return self._langchain_importer.import_session(data)
SessionPortabilityKit.import_crewai method · python · L311-L323 (13 LOC)
src/agent_session_linker/portability/usf_enhanced.py
    def import_crewai(self, data: dict[str, object]) -> UniversalSession:
        """Import a CrewAI context dict.

        Parameters
        ----------
        data:
            CrewAI context dict.

        Returns
        -------
        UniversalSession
        """
        return self._crewai_importer.import_session(data)
SessionPortabilityKit.export_to_json method · python · L325-L338 (14 LOC)
src/agent_session_linker/portability/usf_enhanced.py
    def export_to_json(self, session: UniversalSession) -> str:
        """Export a :class:`UniversalSession` to JSON.

        Parameters
        ----------
        session:
            The session to export.

        Returns
        -------
        str
            JSON representation.
        """
        return session.to_json()
SessionPortabilityKit.import_json method · python · L341-L353 (13 LOC)
src/agent_session_linker/portability/usf_enhanced.py
    def import_json(json_str: str) -> UniversalSession:
        """Import a USF session from a JSON string.

        Parameters
        ----------
        json_str:
            JSON string previously produced by :meth:`export_to_json`.

        Returns
        -------
        UniversalSession
        """
        return UniversalSession.from_json(json_str)
SessionExporter.export method · python · L40-L53 (14 LOC)
src/agent_session_linker/portable/exporters.py
    def export(self, session: UniversalSession) -> dict[str, object]:
        """Convert *session* to the target framework's native dict format.

        Parameters
        ----------
        session:
            A :class:`UniversalSession` to export.

        Returns
        -------
        dict[str, object]
            Framework-native representation of the session.
        """
        ...  # pragma: no cover
_usf_role_to_langchain_type function · python · L61-L80 (20 LOC)
src/agent_session_linker/portable/exporters.py
def _usf_role_to_langchain_type(role: str) -> str:
    """Map a USF role string to the corresponding LangChain message type.

    Parameters
    ----------
    role:
        One of ``"user"``, ``"assistant"``, ``"system"``, ``"tool"``.

    Returns
    -------
    str
        LangChain message type string.
    """
    mapping: dict[str, str] = {
        "user": "human",
        "assistant": "ai",
        "system": "system",
        "tool": "function",
    }
    return mapping.get(role, role)
About: code-quality intelligence by Repobility · https://repobility.com
LangChainExporter.export method · python · L103-L122 (20 LOC)
src/agent_session_linker/portable/exporters.py
    def export(self, session: UniversalSession) -> dict[str, object]:
        """Convert *session* to LangChain memory format.

        Parameters
        ----------
        session:
            Source :class:`UniversalSession`.

        Returns
        -------
        dict[str, object]
            LangChain-compatible memory dict.
        """
        messages: list[dict[str, object]] = [
            self._convert_message(msg) for msg in session.messages
        ]
        return {
            "messages": messages,
            "memory_variables": dict(session.working_memory),
        }
LangChainExporter._convert_message method · python · L124-L129 (6 LOC)
src/agent_session_linker/portable/exporters.py
    def _convert_message(self, msg: USFMessage) -> dict[str, object]:
        return {
            "type": _usf_role_to_langchain_type(msg.role),
            "content": msg.content,
            "additional_kwargs": dict(msg.metadata),
        }
CrewAIExporter.export method · python · L162-L196 (35 LOC)
src/agent_session_linker/portable/exporters.py
    def export(self, session: UniversalSession) -> dict[str, object]:
        """Convert *session* to CrewAI context format.

        Parameters
        ----------
        session:
            Source :class:`UniversalSession`.

        Returns
        -------
        dict[str, object]
            CrewAI-compatible context dict.
        """
        context: dict[str, object] = {
            "session_id": session.session_id,
            "framework_source": session.framework_source,
            "messages": [self._convert_message(msg) for msg in session.messages],
            "working_memory": dict(session.working_memory),
            "entities": [
                {
                    "name": entity.name,
                    "entity_type": entity.entity_type,
                    "value": entity.value,
                    "confidence": entity.confidence,
                }
                for entity in session.entities
            ],
        }
        task_results: list[dict[str, object]] =
CrewAIExporter._convert_message method · python · L198-L204 (7 LOC)
src/agent_session_linker/portable/exporters.py
    def _convert_message(self, msg: USFMessage) -> dict[str, object]:
        return {
            "role": msg.role,
            "content": msg.content,
            "timestamp": msg.timestamp.isoformat(),
            "metadata": dict(msg.metadata),
        }
CrewAIExporter._convert_task method · python · L206-L212 (7 LOC)
src/agent_session_linker/portable/exporters.py
    def _convert_task(self, task: USFTaskState) -> dict[str, object]:
        return {
            "task_id": task.task_id,
            "status": task.status,
            "progress": task.progress,
            "result": task.result,
        }
OpenAIExporter.export method · python · L240-L259 (20 LOC)
src/agent_session_linker/portable/exporters.py
    def export(self, session: UniversalSession) -> dict[str, object]:
        """Convert *session* to OpenAI thread format.

        Parameters
        ----------
        session:
            Source :class:`UniversalSession`.

        Returns
        -------
        dict[str, object]
            OpenAI-compatible thread dict.
        """
        messages: list[dict[str, object]] = [
            self._convert_message(msg) for msg in session.messages
        ]
        return {
            "thread_id": session.session_id,
            "messages": messages,
        }
SessionImporter.import_session method · python · L44-L62 (19 LOC)
src/agent_session_linker/portable/importers.py
    def import_session(self, data: dict[str, object]) -> UniversalSession:
        """Convert framework-native *data* to a :class:`UniversalSession`.

        Parameters
        ----------
        data:
            Framework-native session dict.

        Returns
        -------
        UniversalSession
            A fully validated USF session.

        Raises
        ------
        ValueError
            If *data* is missing required fields or contains invalid values.
        """
        ...  # pragma: no cover
_parse_timestamp function · python · L74-L95 (22 LOC)
src/agent_session_linker/portable/importers.py
def _parse_timestamp(value: object) -> datetime:
    """Parse *value* into a timezone-aware UTC datetime.

    Parameters
    ----------
    value:
        A datetime object, an ISO-8601 string, or ``None``.

    Returns
    -------
    datetime
        UTC-aware datetime; defaults to UTC now when *value* is falsy.
    """
    if not value:
        return _utc_now()
    if isinstance(value, datetime):
        dt = value
    else:
        dt = datetime.fromisoformat(str(value))
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=timezone.utc)
    return dt
Repobility · code-quality intelligence · https://repobility.com
_langchain_type_to_usf_role function · python · L98-L118 (21 LOC)
src/agent_session_linker/portable/importers.py
def _langchain_type_to_usf_role(msg_type: str) -> str:
    """Map a LangChain message type to a USF role.

    Parameters
    ----------
    msg_type:
        LangChain type string, e.g. ``"human"``, ``"ai"``, ``"system"``.

    Returns
    -------
    str
        USF role string.
    """
    mapping: dict[str, str] = {
        "human": "user",
        "ai": "assistant",
        "system": "system",
        "function": "tool",
        "tool": "tool",
    }
    return mapping.get(msg_type, "user")
LangChainImporter.import_session method · python · L148-L197 (50 LOC)
src/agent_session_linker/portable/importers.py
    def import_session(self, data: dict[str, object]) -> UniversalSession:
        """Convert a LangChain memory dict to a :class:`UniversalSession`.

        Parameters
        ----------
        data:
            LangChain memory dict.

        Returns
        -------
        UniversalSession
            A validated USF session with ``framework_source="langchain"``.

        Raises
        ------
        ValueError
            If a message entry is missing required fields.
        """
        raw_messages: list[object] = data.get("messages") or []
        messages: list[USFMessage] = []
        for entry in raw_messages:
            if not isinstance(entry, dict):
                raise ValueError(f"Each message must be a dict, got {type(entry).__name__!r}")
            msg_type = entry.get("type") or "human"
            content = entry.get("content", "")
            timestamp = _parse_timestamp(entry.get("timestamp"))
            metadata: dict[str, object] = dict(entry.get("addition
CrewAIImporter.import_session method · python · L232-L318 (87 LOC)
src/agent_session_linker/portable/importers.py
    def import_session(self, data: dict[str, object]) -> UniversalSession:
        """Convert a CrewAI context dict to a :class:`UniversalSession`.

        Parameters
        ----------
        data:
            CrewAI context dict.

        Returns
        -------
        UniversalSession
            A validated USF session with ``framework_source="crewai"``.

        Raises
        ------
        ValueError
            If nested structures contain invalid values.
        """
        context: dict[str, object] = dict(data.get("context") or {})
        task_results: list[object] = data.get("task_results") or []

        session_id: str = str(context.get("session_id") or uuid4())

        raw_messages: list[object] = context.get("messages") or []
        messages: list[USFMessage] = []
        for entry in raw_messages:
            if not isinstance(entry, dict):
                raise ValueError(f"Each message must be a dict, got {type(entry).__name__!r}")
            role = str(entry.
OpenAIImporter.import_session method · python · L344-L400 (57 LOC)
src/agent_session_linker/portable/importers.py
    def import_session(self, data: dict[str, object]) -> UniversalSession:
        """Convert an OpenAI thread dict to a :class:`UniversalSession`.

        Parameters
        ----------
        data:
            OpenAI thread dict.

        Returns
        -------
        UniversalSession
            A validated USF session with ``framework_source="openai"``.

        Raises
        ------
        ValueError
            If a message entry is missing required fields.
        """
        thread_id: str = str(data.get("thread_id") or uuid4())
        raw_messages: list[object] = data.get("messages") or []

        messages: list[USFMessage] = []
        for entry in raw_messages:
            if not isinstance(entry, dict):
                raise ValueError(f"Each message must be a dict, got {type(entry).__name__!r}")
            role = str(entry.get("role") or "user")
            if role not in {"user", "assistant", "system", "tool"}:
                role = "user"

            raw_ts = en
USFMessage.__post_init__ method · python · L66-L71 (6 LOC)
src/agent_session_linker/portable/usf.py
    def __post_init__(self) -> None:
        valid_roles = {"user", "assistant", "system", "tool"}
        if self.role not in valid_roles:
            raise ValueError(
                f"USFMessage.role must be one of {sorted(valid_roles)!r}, got {self.role!r}"
            )
USFTaskState.__post_init__ method · python · L124-L134 (11 LOC)
src/agent_session_linker/portable/usf.py
    def __post_init__(self) -> None:
        valid_statuses = {"pending", "in_progress", "completed", "failed"}
        if self.status not in valid_statuses:
            raise ValueError(
                f"USFTaskState.status must be one of {sorted(valid_statuses)!r}, "
                f"got {self.status!r}"
            )
        if not (0.0 <= self.progress <= 1.0):
            raise ValueError(
                f"USFTaskState.progress must be in [0.0, 1.0], got {self.progress!r}"
            )
_message_to_dict function · python · L142-L148 (7 LOC)
src/agent_session_linker/portable/usf.py
def _message_to_dict(msg: USFMessage) -> dict[str, object]:
    return {
        "role": msg.role,
        "content": msg.content,
        "timestamp": msg.timestamp.isoformat(),
        "metadata": msg.metadata,
    }
_message_from_dict function · python · L151-L164 (14 LOC)
src/agent_session_linker/portable/usf.py
def _message_from_dict(data: dict[str, object]) -> USFMessage:
    ts_raw = data["timestamp"]
    if isinstance(ts_raw, datetime):
        timestamp = ts_raw
    else:
        timestamp = datetime.fromisoformat(str(ts_raw))
    if timestamp.tzinfo is None:
        timestamp = timestamp.replace(tzinfo=timezone.utc)
    return USFMessage(
        role=data["role"],
        content=data["content"],
        timestamp=timestamp,
        metadata=dict(data.get("metadata") or {}),
    )
If a scraper extracted this row, it came from Repobility (https://repobility.com)
_entity_to_dict function · python · L167-L173 (7 LOC)
src/agent_session_linker/portable/usf.py
def _entity_to_dict(entity: USFEntity) -> dict[str, object]:
    return {
        "name": entity.name,
        "entity_type": entity.entity_type,
        "value": entity.value,
        "confidence": entity.confidence,
    }
_entity_from_dict function · python · L176-L182 (7 LOC)
src/agent_session_linker/portable/usf.py
def _entity_from_dict(data: dict[str, object]) -> USFEntity:
    return USFEntity(
        name=data["name"],
        entity_type=data["entity_type"],
        value=data["value"],
        confidence=float(data["confidence"]),
    )
_task_state_to_dict function · python · L185-L191 (7 LOC)
src/agent_session_linker/portable/usf.py
def _task_state_to_dict(task: USFTaskState) -> dict[str, object]:
    return {
        "task_id": task.task_id,
        "status": task.status,
        "progress": task.progress,
        "result": task.result,
    }
‹ prevpage 3 / 5next ›