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
1 change: 0 additions & 1 deletion bot/tests/test_chat_functionality.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from pathlib import Path

import pytest

from vikingbot.bus.events import OutboundMessage
from vikingbot.bus.queue import MessageBus
from vikingbot.channels.chat import ChatChannel, ChatChannelConfig
Expand Down
5 changes: 3 additions & 2 deletions bot/vikingbot/agent/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
import base64
import mimetypes
import platform
import time as _time
from datetime import datetime
from pathlib import Path
from typing import Any

from loguru import logger
import time as _time
from datetime import datetime

from vikingbot.agent.memory import MemoryStore
from vikingbot.agent.skills import SkillsLoader
Expand Down
11 changes: 9 additions & 2 deletions bot/vikingbot/agent/loop.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
"""Agent loop: the core processing engine."""

from __future__ import annotations

import asyncio
import json
import time
from pathlib import Path
from typing import TYPE_CHECKING

from loguru import logger

Expand All @@ -24,6 +27,10 @@
from vikingbot.utils.helpers import cal_str_tokens
from vikingbot.utils.tracing import trace

if TYPE_CHECKING:
from vikingbot.config.schema import ExecToolConfig
from vikingbot.cron.service import CronService


class AgentLoop:
"""
Expand Down Expand Up @@ -87,7 +94,7 @@ def __init__(
... max_iterations=30,
... )
"""
from vikingbot.config.schema import ExecToolConfig
from vikingbot.config.schema import ExecToolConfig # noqa: F811

self.bus = bus
self.provider = provider
Expand Down Expand Up @@ -305,7 +312,7 @@ async def execute_single_tool(idx: int, tool_call):
results = await asyncio.gather(*tool_tasks)

# Stage 3: Process results sequentially in original order
for idx, tool_call, result, tool_execute_duration in results:
for _idx, tool_call, result, tool_execute_duration in results:
args_str = json.dumps(tool_call.arguments, ensure_ascii=False)
logger.info(f"[TOOL_CALL]: {tool_call.name}({args_str[:200]})")
logger.info(f"[RESULT]: {str(result)[:600]}")
Expand Down
3 changes: 1 addition & 2 deletions bot/vikingbot/agent/memory.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
"""Memory system for persistent agent memory."""

from openviking.async_client import logger
from vikingbot.config.loader import load_config
from pathlib import Path
from typing import Any

from vikingbot.config.loader import load_config
from vikingbot.openviking_mount.ov_server import VikingClient
from vikingbot.utils.helpers import ensure_dir

Expand Down
8 changes: 4 additions & 4 deletions bot/vikingbot/channels/dingtalk.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
import time
from typing import Any

from loguru import logger
import httpx
from loguru import logger

from vikingbot.bus.events import OutboundMessage
from vikingbot.bus.queue import MessageBus
Expand All @@ -15,11 +15,11 @@

try:
from dingtalk_stream import (
DingTalkStreamClient,
Credential,
AckMessage,
CallbackHandler,
CallbackMessage,
AckMessage,
Credential,
DingTalkStreamClient,
)
from dingtalk_stream.chatbot import ChatbotMessage

Expand Down
19 changes: 10 additions & 9 deletions bot/vikingbot/channels/feishu.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,17 +35,17 @@
try:
import lark_oapi as lark
from lark_oapi.api.im.v1 import (
CreateMessageRequest,
CreateMessageRequestBody,
CreateMessageReactionRequest,
CreateMessageReactionRequestBody,
CreateMessageRequest,
CreateMessageRequestBody,
Emoji,
P2ImMessageReceiveV1,
GetChatRequest,
GetImageRequest,
GetMessageResourceRequest,
P2ImMessageReceiveV1,
ReplyMessageRequest,
ReplyMessageRequestBody,
GetChatRequest,
)

FEISHU_AVAILABLE = True
Expand Down Expand Up @@ -326,7 +326,10 @@ def _parse_md_table(table_text: str) -> dict | None:
lines = [l.strip() for l in table_text.strip().split("\n") if l.strip()]
if len(lines) < 3:
return None
split = lambda l: [c.strip() for c in l.strip("|").split("|")]

def split(l: str) -> list[str]:
return [c.strip() for c in l.strip("|").split("|")]

headers = split(lines[0])
rows = [split(l) for l in lines[2:]]
columns = [
Expand Down Expand Up @@ -384,7 +387,6 @@ def _split_headings(self, content: str) -> list[dict]:
before = protected[last_end : m.start()].strip()
if before:
elements.append({"tag": "markdown", "content": before})
level = len(m.group(1))
text = m.group(2).strip()
elements.append(
{
Expand Down Expand Up @@ -703,7 +705,6 @@ async def _on_message(self, data: "P2ImMessageReceiveV1") -> None:
image_bytes = await self._download_feishu_image(image_key, message_id)
if image_bytes:
# Save to workspace/media directory
from pathlib import Path

media_dir = get_data_path() / "received"

Expand Down Expand Up @@ -762,8 +763,8 @@ async def _on_message(self, data: "P2ImMessageReceiveV1") -> None:
},
)

except Exception as e:
logger.exception(f"Error processing Feishu message")
except Exception:
logger.exception("Error processing Feishu message")

async def _extract_and_upload_images(self, content: str) -> tuple[str, list[dict]]:
"""Extract images from markdown content, upload to Feishu, and return cleaned content."""
Expand Down
1 change: 0 additions & 1 deletion bot/vikingbot/channels/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

from loguru import logger

from vikingbot.bus.events import OutboundMessage
from vikingbot.bus.queue import MessageBus
from vikingbot.channels.base import BaseChannel
from vikingbot.config.schema import BaseChannelConfig, ChannelType, Config
Expand Down
8 changes: 2 additions & 6 deletions bot/vikingbot/channels/openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,21 @@
import uuid
from datetime import datetime
from pathlib import Path
from typing import Any, AsyncGenerator, Callable, Dict, List, Optional
from typing import Any, Dict, List, Optional

from fastapi import APIRouter, Depends, Header, HTTPException, Request
from fastapi import APIRouter, Depends, FastAPI, Header, HTTPException
from fastapi.responses import StreamingResponse
from loguru import logger
from pydantic import BaseModel

from vikingbot.bus.events import InboundMessage, OutboundEventType, OutboundMessage
from vikingbot.bus.queue import MessageBus
from vikingbot.channels.base import BaseChannel
from vikingbot.channels.openapi_models import (
ChatMessage,
ChatRequest,
ChatResponse,
ChatStreamEvent,
ErrorResponse,
EventType,
HealthResponse,
MessageRole,
SessionCreateRequest,
SessionCreateResponse,
SessionDetailResponse,
Expand Down
1 change: 0 additions & 1 deletion bot/vikingbot/channels/qq.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import asyncio
from collections import deque
from typing import TYPE_CHECKING

from loguru import logger

Expand Down
10 changes: 3 additions & 7 deletions bot/vikingbot/cli/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@
import json
import os
import select
import signal
import sys
import hashlib
import time
from pathlib import Path

Expand All @@ -31,16 +29,15 @@
from vikingbot.cron.types import CronJob
from vikingbot.heartbeat.service import HeartbeatService
from vikingbot.integrations.langfuse import LangfuseClient
from vikingbot.config.loader import load_config

# Create sandbox manager
from vikingbot.sandbox.manager import SandboxManager
from vikingbot.session.manager import SessionManager
from vikingbot.utils.helpers import (
get_bridge_path,
get_history_path,
get_source_workspace_path,
set_bot_data_path,
get_history_path,
get_bridge_path,
)

app = typer.Typer(
Expand Down Expand Up @@ -471,6 +468,7 @@ async def start_console(console_port):
"""Start the console web UI in a separate thread within the same process."""
try:
import threading

from vikingbot.console.console_gradio_simple import run_console_server

def run_in_thread():
Expand Down Expand Up @@ -789,8 +787,6 @@ def cron_list(
table.add_column("Status")
table.add_column("Next Run")

import time

for job in jobs:
# Format schedule
if job.schedule.kind == "every":
Expand Down
1 change: 0 additions & 1 deletion bot/vikingbot/hooks/builtins/openviking_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@

try:
import openviking as ov

from vikingbot.openviking_mount.ov_server import VikingClient

HAS_OPENVIKING = True
Expand Down
6 changes: 3 additions & 3 deletions bot/vikingbot/integrations/langfuse.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,12 +94,12 @@ def propagate_attributes(
user_id: Optional user ID to associate with all nested observations
"""
if not self.enabled:
logger.warning(f"[LANGFUSE] propagate_attributes skipped: Langfuse client not enabled")
logger.warning("[LANGFUSE] propagate_attributes skipped: Langfuse client not enabled")
yield
return
if not self._client:
logger.warning(
f"[LANGFUSE] propagate_attributes skipped: Langfuse client not initialized"
"[LANGFUSE] propagate_attributes skipped: Langfuse client not initialized"
)
yield
return
Expand All @@ -123,7 +123,7 @@ def propagate_attributes(
yield
else:
logger.warning(
f"[LANGFUSE] propagate_attributes not available (SDK version may not support it)"
"[LANGFUSE] propagate_attributes not available (SDK version may not support it)"
)
yield
except Exception as e:
Expand Down
8 changes: 4 additions & 4 deletions bot/vikingbot/openviking_mount/viking_fuse.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@

from loguru import logger

from .mount import OpenVikingMount, MountConfig
from .mount import MountConfig, OpenVikingMount

# 尝试导入fusepy
try:
from fuse import FUSE, FuseOSError, Operations

FUSE_AVAILABLE = True
except (ImportError, OSError) as e:
except (ImportError, OSError):
FUSE_AVAILABLE = False
# 创建占位符
Operations = object
Expand All @@ -33,9 +33,9 @@

# 只有当 FUSE 可用时才定义完整的实现
if FUSE_AVAILABLE:
import errno
import os
import stat
import errno
from datetime import datetime

class OpenVikingFUSE(Operations):
Expand Down Expand Up @@ -405,7 +405,7 @@ def mount_fuse(
logger.info(f"Mounting OpenViking FUSE at: {config.mount_point}")
logger.info(f" Scope: {config.scope.value}")
logger.info(f" Read-only: {config.read_only}")
logger.info(f" Press Ctrl+C to unmount")
logger.info(" Press Ctrl+C to unmount")

try:
FUSE(
Expand Down
8 changes: 3 additions & 5 deletions bot/vikingbot/sandbox/backends/aiosandbox.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
"""AIO Sandbox backend implementation using agent-sandbox SDK."""

from pathlib import Path
from typing import TYPE_CHECKING, Any
from typing import Any

from loguru import logger

from vikingbot.sandbox.base import SandboxBackend, SandboxNotStartedError
from vikingbot.sandbox.backends import register_backend


from vikingbot.config.schema import SandboxConfig, SessionKey
from vikingbot.sandbox.backends import register_backend
from vikingbot.sandbox.base import SandboxBackend, SandboxNotStartedError


@register_backend("aiosandbox")
Expand Down
16 changes: 7 additions & 9 deletions bot/vikingbot/sandbox/backends/opensandbox.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
"""OpenSandbox backend implementation using official SDK."""

import asyncio
import atexit
import os
import subprocess
import asyncio
import time
import atexit
from datetime import timedelta
from pathlib import Path
from typing import TYPE_CHECKING, Any
from typing import Any

import httpx
from loguru import logger

from vikingbot.sandbox.base import SandboxBackend, SandboxNotStartedError
from vikingbot.sandbox.backends import register_backend


from vikingbot.config.schema import SandboxConfig, SessionKey
from vikingbot.sandbox.backends import register_backend
from vikingbot.sandbox.base import SandboxBackend, SandboxNotStartedError

# Global to track the opensandbox-server process
_OSB_SERVER_PROCESS: "subprocess.Popen | None" = None
Expand Down Expand Up @@ -152,8 +150,8 @@ async def start(self) -> None:
)

try:
from opensandbox.sandbox import Sandbox
from opensandbox.config import ConnectionConfig
from opensandbox.sandbox import Sandbox

self._connection_config = ConnectionConfig(
domain=self._server_url,
Expand All @@ -167,7 +165,7 @@ async def start(self) -> None:
volumes = None
if not self._is_vke:
# Local environment: mount host volume
from opensandbox.models.sandboxes import Volume, Host
from opensandbox.models.sandboxes import Host, Volume

volumes = [
Volume(
Expand Down
Loading
Loading