Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions agents/_example/tools/example_tool.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from backend.utils.tool import Tool, Response
from backend.utils.tool import Response, Tool

# this is an example tool class
# don't forget to include instructions in the system prompt by creating
# don't forget to include instructions in the system prompt by creating
# agent.system.tool.example_tool.md file in prompts directory of your agent
# see /backend/tools folder for all default tools

Expand Down
4 changes: 2 additions & 2 deletions agents/_example/tools/response.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from backend.utils.tool import Tool, Response
from backend.utils.tool import Response, Tool

# example of a tool redefinition
# the original response tool is in backend/tools/response.py
Expand All @@ -20,4 +20,4 @@ async def after_execution(self, response, **kwargs):

if self.loop_data and "log_item_response" in self.loop_data.params_temporary:
log = self.loop_data.params_temporary["log_item_response"]
log.update(finished=True) # mark the message as finished
log.update(finished=True) # mark the message as finished
26 changes: 10 additions & 16 deletions backend/core/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
import string
import threading
from collections import OrderedDict
from collections.abc import Awaitable, Callable, Coroutine
from dataclasses import dataclass, field
from datetime import datetime, timezone
from datetime import UTC, datetime
from enum import Enum
from typing import Any, Awaitable, Callable, Coroutine, Dict, Literal
from typing import Any

from langchain_core.messages import BaseMessage, SystemMessage
from langchain_core.prompts import ChatPromptTemplate
Expand All @@ -18,23 +19,16 @@
from backend.utils import context as context_helper
from backend.utils import (
dirty_json,
errors,
extension,
files,
history,
)
from backend.utils import log as Log
from backend.utils import (
print_style,
subagents,
tokens,
)
from backend.utils import log as Log
from backend.utils.defer import DeferredTask
from backend.utils.dirty_json import DirtyJson
from backend.utils.errors import (
HandledException,
InterventionException,
RepairableException,
)
from backend.utils.extension import call_extensions, extensible
from backend.utils.extract_tools import json_parse_dirty, load_classes_from_file
Expand Down Expand Up @@ -94,11 +88,11 @@ def __init__(
self.paused = paused
self.streaming_agent = streaming_agent
self.task: DeferredTask | None = None
self.created_at = created_at or datetime.now(timezone.utc)
self.created_at = created_at or datetime.now(UTC)
self.type = type
AgentContext._counter += 1
self.no = AgentContext._counter
self.last_message = last_message or datetime.now(timezone.utc)
self.last_message = last_message or datetime.now(UTC)

# initialize agent at last (context is complete now)
self.ctx = ctx or Agent(0, self.config, self)
Expand Down Expand Up @@ -284,7 +278,7 @@ def run_task(self, func: Callable[..., Coroutine[Any, Any, Any]], *args: Any, **
@extensible
async def _process_chain(self, agent: "Agent", msg: "UserMessage|str", user=True):
try:
msg_template = (
(
agent.hist_add_user_message(msg) # type: ignore
if user
else agent.hist_add_tool_result(
Expand Down Expand Up @@ -327,7 +321,7 @@ class AgentConfig:
code_exec_ssh_port: int = 55022
code_exec_ssh_user: str = "root"
code_exec_ssh_pass: str = ""
additional: Dict[str, Any] = field(default_factory=dict)
additional: dict[str, Any] = field(default_factory=dict)


@dataclass
Expand Down Expand Up @@ -627,7 +621,7 @@ def set_data(self, field: str, value):

@extensible
def hist_add_message(self, ai: bool, content: history.MessageContent, tokens: int = 0):
self.last_message = datetime.now(timezone.utc)
self.last_message = datetime.now(UTC)
# Allow extensions to process content before adding to history
content_data = {"content": content}
asyncio.run(self.call_extensions("hist_add_before", content_data=content_data, ai=ai))
Expand Down Expand Up @@ -925,7 +919,7 @@ async def handle_response_stream(self, stream: str):
parsed=response,
)

except Exception as e:
except Exception:
pass

@extensible
Expand Down
9 changes: 5 additions & 4 deletions backend/core/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,18 @@
"""

import asyncio
from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Callable, Dict, List
from typing import Any


@dataclass
class Event:
"""Represents an event in the system."""

name: str
data: Dict[str, Any]
data: dict[str, Any]
timestamp: datetime
source: str = "unknown"

Expand All @@ -25,7 +26,7 @@ class EventManager:
"""Manages event subscription and publishing."""

def __init__(self):
self._subscribers: Dict[str, List[Callable]] = {}
self._subscribers: dict[str, list[Callable]] = {}
self._lock = asyncio.Lock()

async def subscribe(self, event_name: str, callback: Callable[[Event], None]) -> None:
Expand Down Expand Up @@ -65,7 +66,7 @@ async def publish(self, event: Event) -> None:
if tasks:
await asyncio.gather(*tasks, return_exceptions=True)

def get_subscribed_events(self) -> List[str]:
def get_subscribed_events(self) -> list[str]:
"""Get list of all subscribed event names."""
return list(self._subscribers.keys())

Expand Down
7 changes: 3 additions & 4 deletions backend/core/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,12 @@
the application to provide better error handling and debugging.
"""

from typing import Any, Optional


class CtxAIException(Exception):
"""Base exception class for all Ctx AI framework exceptions."""

def __init__(self, message: str, details: Optional[dict] = None):
def __init__(self, message: str, details: dict | None = None):
super().__init__(message)
self.message = message
self.details = details or {}
Expand Down Expand Up @@ -63,7 +62,7 @@ class RateLimitException(CtxAIException):
"""Exception raised when rate limits are exceeded."""

def __init__(
self, message: str, retry_after: Optional[int] = None, details: Optional[dict] = None
self, message: str, retry_after: int | None = None, details: dict | None = None
):
super().__init__(message, details)
self.retry_after = retry_after
Expand All @@ -73,7 +72,7 @@ class TimeoutException(CtxAIException):
"""Exception raised when operations timeout."""

def __init__(
self, message: str, timeout_seconds: Optional[float] = None, details: Optional[dict] = None
self, message: str, timeout_seconds: float | None = None, details: dict | None = None
):
super().__init__(message, details)
self.timeout_seconds = timeout_seconds
Loading
Loading