支持多模型提供商
This commit is contained in:
Generated
+1
@@ -4,6 +4,7 @@
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/.venv" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/.voidbot" />
|
||||
</content>
|
||||
<orderEntry type="jdk" jdkName="uv (VoidBot)" jdkType="Python SDK" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
|
||||
@@ -4,7 +4,7 @@ VoidBot is a minimal Python agent runtime designed around three ideas:
|
||||
|
||||
- Borrow the lightweight execution loop and session persistence style from `nanobot`.
|
||||
- Borrow the provider compatibility and gateway/runtime separation from `openclaw`.
|
||||
- Keep the first version small: direct CLI or standalone gateway, OpenAI-compatible model calls, tool loop.
|
||||
- Keep the first version small: direct CLI or standalone gateway, provider compatibility, tool loop, and persistent session state.
|
||||
|
||||
## Architecture
|
||||
|
||||
@@ -12,9 +12,9 @@ VoidBot is a minimal Python agent runtime designed around three ideas:
|
||||
CLI Agent
|
||||
-> AgentRuntime
|
||||
-> ContextBuilder
|
||||
-> SessionStore
|
||||
-> SQLite SessionStore
|
||||
-> ToolRegistry
|
||||
-> ProviderRegistry
|
||||
-> ProviderManager
|
||||
-> OpenAI Compatible Provider
|
||||
|
||||
Gateway Server
|
||||
@@ -34,7 +34,9 @@ See [docs/architecture.md](docs/architecture.md) for the layer breakdown and mes
|
||||
- Execute tools and feed tool results back into the model loop
|
||||
- Run as a direct CLI agent or through a standalone gateway process
|
||||
- Let the standalone gateway listen on HTTP, Feishu, and QQ at the same time
|
||||
- Persist sessions, messages, and session metadata in SQLite
|
||||
- Isolate transcript history by `session_id`, so each chat keeps its own context
|
||||
- Support multiple configured model endpoints and switch per session
|
||||
- Support provider presets for:
|
||||
- `openai_chatgpt`
|
||||
- `zhipu_coding_plan`
|
||||
@@ -69,46 +71,63 @@ This command is incremental:
|
||||
- it does not delete your custom fields
|
||||
- it does not overwrite values you already filled in
|
||||
|
||||
3. Edit `~/.voidbot/config.json` with your real values.
|
||||
3. Check or open the config path when needed:
|
||||
|
||||
4. Start the CLI directly:
|
||||
```bash
|
||||
uv run voidbot config path
|
||||
uv run voidbot config open
|
||||
```
|
||||
|
||||
4. Edit `~/.voidbot/config.json` with your real values.
|
||||
|
||||
5. Start the CLI directly:
|
||||
|
||||
```bash
|
||||
uv run voidbot
|
||||
```
|
||||
|
||||
5. Run one turn locally:
|
||||
6. Run one turn locally:
|
||||
|
||||
```bash
|
||||
uv run voidbot --message "Summarize this repository"
|
||||
```
|
||||
|
||||
6. Start the standalone gateway:
|
||||
7. Start the standalone gateway:
|
||||
|
||||
```bash
|
||||
uv run voidbot gateway
|
||||
```
|
||||
|
||||
7. Call the agent through the HTTP gateway:
|
||||
8. Call the agent through the HTTP gateway:
|
||||
|
||||
```bash
|
||||
uv run voidbot --via gateway --message "Summarize this repository"
|
||||
```
|
||||
|
||||
8. Run interactive mode with automatic fallback:
|
||||
9. Run interactive mode with automatic fallback:
|
||||
|
||||
```bash
|
||||
uv run voidbot --via auto
|
||||
```
|
||||
|
||||
10. Inspect stored SQLite data:
|
||||
|
||||
```bash
|
||||
uv run voidbot data dump
|
||||
```
|
||||
|
||||
## Config Fields
|
||||
|
||||
- `provider`: provider preset name
|
||||
- `api_key`: provider API key
|
||||
- `api_base`: optional override for the provider base URL
|
||||
- `model`: optional override for the model ID
|
||||
- `default_provider`: default provider id for new sessions
|
||||
- `providers`: a list of configured model endpoints
|
||||
- `providers[].id`: stable numeric or string id used for switching
|
||||
- `providers[].preset`: provider preset name
|
||||
- `providers[].api_key`: provider API key
|
||||
- `providers[].api_base`: optional base URL override
|
||||
- `providers[].model`: optional model override
|
||||
- `providers[].label`: optional display name
|
||||
- `workspace`: workspace path used by tools and context
|
||||
- `session_file`: optional JSONL transcript path
|
||||
- `database_path`: optional SQLite database path
|
||||
- `max_iterations`: max tool-call rounds in one turn
|
||||
- `history_limit`: number of previous messages to include
|
||||
- `system_prompt`: optional custom system prompt
|
||||
@@ -160,13 +179,39 @@ Platform notes:
|
||||
- Feishu: enable bot capability and subscribe to `im.message.receive_v1`.
|
||||
- QQ: enable C2C messages and group `@bot` messages for the app.
|
||||
- Every Feishu or QQ chat is mapped to its own `session_id`, so contexts do not leak across chats.
|
||||
- Model switching is stored per session, so each chat can stay on its own provider.
|
||||
|
||||
## Model Switching
|
||||
|
||||
Each configured provider has an `id`, for example:
|
||||
|
||||
```json
|
||||
{
|
||||
"default_provider": "1",
|
||||
"providers": [
|
||||
{ "id": "1", "preset": "zhipu_coding_plan", "api_key": "...", "model": "glm-4.7" },
|
||||
{ "id": "2", "preset": "openai_chatgpt", "api_key": "...", "model": "gpt-4.1-mini" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Inside a conversation, you can switch the current session model dynamically:
|
||||
|
||||
```text
|
||||
/models
|
||||
/use 2
|
||||
```
|
||||
|
||||
- `/models` lists all configured providers
|
||||
- `/use <id>` switches only the current session
|
||||
- The selected provider id is stored in SQLite session metadata
|
||||
|
||||
## User Home Layout
|
||||
|
||||
VoidBot now keeps user-level state under `~/.voidbot` by default.
|
||||
|
||||
- `~/.voidbot/config.json`: default config file
|
||||
- `~/.voidbot/session.jsonl`: default transcript base file
|
||||
- `~/.voidbot/voidbot.db`: SQLite database for sessions, metadata, and messages
|
||||
- `~/.voidbot/cli_history`: interactive CLI input history
|
||||
|
||||
Config lookup order without `--config`:
|
||||
@@ -182,6 +227,13 @@ uv run voidbot config sync
|
||||
|
||||
This command analyzes the existing JSON structure and only adds missing fields from the latest example config.
|
||||
|
||||
Useful data command:
|
||||
|
||||
```bash
|
||||
uv run voidbot data dump
|
||||
uv run voidbot data dump --session-id main
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- The model layer is deliberately OpenAI-compatible first, so adding more gateways later is straightforward.
|
||||
|
||||
+17
-3
@@ -1,10 +1,24 @@
|
||||
{
|
||||
"provider": "zhipu_coding_plan",
|
||||
"default_provider": "1",
|
||||
"providers": [
|
||||
{
|
||||
"id": "1",
|
||||
"label": "Zhipu Coding Plan",
|
||||
"preset": "zhipu_coding_plan",
|
||||
"api_key": "YOUR_API_KEY",
|
||||
"api_base": "https://open.bigmodel.cn/api/coding/paas/v4",
|
||||
"model": "glm-4.7",
|
||||
"model": "glm-4.7"
|
||||
},
|
||||
{
|
||||
"id": "2",
|
||||
"label": "OpenAI ChatGPT",
|
||||
"preset": "openai_chatgpt",
|
||||
"api_key": "YOUR_OPENAI_API_KEY",
|
||||
"model": "gpt-4.1-mini"
|
||||
}
|
||||
],
|
||||
"workspace": ".",
|
||||
"session_file": "~/.voidbot/session.jsonl",
|
||||
"database_path": "~/.voidbot/voidbot.db",
|
||||
"max_iterations": 8,
|
||||
"history_limit": 24,
|
||||
"system_prompt": "You are VoidBot, a concise coding agent. Use tools when needed, cite tool results plainly, and finish once the task is complete.",
|
||||
|
||||
+19
-4
@@ -30,7 +30,7 @@ Responsibilities:
|
||||
- Accept HTTP requests and forward them to the same runtime implementation
|
||||
- Accept Feishu and QQ messages and route them through the same runtime
|
||||
- Send the final agent reply back to the originating channel
|
||||
- Manage the user-level `~/.voidbot` home, including config sync and CLI history
|
||||
- Manage the user-level `~/.voidbot` home, including config sync, config open/path helpers, data dump, and CLI history
|
||||
|
||||
### 2. Runtime
|
||||
|
||||
@@ -42,8 +42,9 @@ Files:
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Load aligned history from JSONL
|
||||
- Keep a separate transcript file per `session_id`
|
||||
- Load aligned history from SQLite
|
||||
- Keep a separate logical session per `session_id`
|
||||
- Store per-session metadata such as the selected provider id
|
||||
- Build a stable system prompt and a volatile runtime block
|
||||
- Execute the loop:
|
||||
- call model
|
||||
@@ -51,12 +52,14 @@ Responsibilities:
|
||||
- execute tools
|
||||
- inject tool results
|
||||
- continue until final answer or iteration limit
|
||||
- Intercept built-in commands like `/models` and `/use <id>`
|
||||
|
||||
### 3. Model Compatibility Layer
|
||||
|
||||
Files:
|
||||
|
||||
- `src/voidbot/providers/base.py`
|
||||
- `src/voidbot/providers/manager.py`
|
||||
- `src/voidbot/providers/registry.py`
|
||||
- `src/voidbot/providers/compat.py`
|
||||
- `src/voidbot/providers/openai_compatible.py`
|
||||
@@ -64,6 +67,7 @@ Files:
|
||||
Responsibilities:
|
||||
|
||||
- Resolve provider presets
|
||||
- Resolve configured provider ids from the user config
|
||||
- Normalize request payload shape
|
||||
- Hide provider-specific API details behind one `chat()` method
|
||||
- Keep compatibility rules out of the runtime loop
|
||||
@@ -87,15 +91,17 @@ Responsibilities:
|
||||
```text
|
||||
CLI input
|
||||
-> InboundMessageContext
|
||||
-> SessionStore(session metadata lookup)
|
||||
-> local AgentRuntime.run_turn()
|
||||
-> ContextBuilder.build_messages()
|
||||
-> ProviderManager.resolve(session provider)
|
||||
-> Provider.chat()
|
||||
-> LLMResponse
|
||||
-> ToolRegistry.execute() if tool calls exist
|
||||
-> tool result messages appended
|
||||
-> Provider.chat() again
|
||||
-> final assistant reply
|
||||
-> JSONL session persistence
|
||||
-> SQLite session persistence
|
||||
```
|
||||
|
||||
```text
|
||||
@@ -122,11 +128,20 @@ voidbot config sync
|
||||
-> preserve unknown/custom user fields
|
||||
```
|
||||
|
||||
```text
|
||||
voidbot data dump
|
||||
-> load configured SQLite database path
|
||||
-> read sessions table
|
||||
-> read messages table
|
||||
-> print JSON
|
||||
```
|
||||
|
||||
## Why This Matches openclaw + nanobot
|
||||
|
||||
- From `nanobot`: the loop is kept simple and centered on normalized `LLMResponse`, tool schemas, and append-only history.
|
||||
- From `openclaw`: gateway context is explicit, direct and gateway modes coexist, provider presets are registry-driven, and compatibility logic is separated from the loop.
|
||||
- From both: channel ingress is outside the core runtime, so CLI, HTTP, Feishu, and QQ all converge on one `AgentRuntime`.
|
||||
- The added provider catalog and SQLite session metadata keep model selection stable across turns and channels.
|
||||
|
||||
## Planned Next Extensions
|
||||
|
||||
|
||||
+146
-7
@@ -8,29 +8,50 @@ from voidbot.config import AppConfig
|
||||
from voidbot.context import ContextBuilder
|
||||
from voidbot.gateway.messages import InboundMessageContext
|
||||
from voidbot.models import RunTurnResult
|
||||
from voidbot.providers.base import LLMProvider
|
||||
from voidbot.session import SessionStore
|
||||
from voidbot.providers.manager import ProviderManager
|
||||
from voidbot.session import SessionState, SessionStore
|
||||
from voidbot.tools.base import ToolRegistry
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class AgentRuntime:
|
||||
"""Single-session runtime."""
|
||||
"""Session-aware runtime."""
|
||||
|
||||
config: AppConfig
|
||||
provider: LLMProvider
|
||||
providers: ProviderManager
|
||||
session: SessionStore
|
||||
tools: ToolRegistry
|
||||
context_builder: ContextBuilder
|
||||
|
||||
def run_turn(self, inbound: InboundMessageContext) -> RunTurnResult:
|
||||
"""Run one user turn through the tool loop."""
|
||||
session_state = self.session.ensure_session(
|
||||
inbound.session_id,
|
||||
provider_id=self.config.default_provider,
|
||||
)
|
||||
command_result = self._handle_control_command(inbound, session_state)
|
||||
if command_result is not None:
|
||||
return command_result
|
||||
|
||||
active_provider_id = session_state.provider_id or self.config.default_provider
|
||||
provider_description = self.providers.describe(active_provider_id)
|
||||
history = self.session.load_history(
|
||||
limit=self.config.history_limit,
|
||||
session_id=inbound.session_id,
|
||||
)
|
||||
tool_summaries = self.tools.summaries()
|
||||
messages = self.context_builder.build_messages(history, inbound, tool_summaries)
|
||||
provider_summary = (
|
||||
f"{provider_description['id']} / "
|
||||
f"{provider_description['label']} / "
|
||||
f"{provider_description['model']}"
|
||||
)
|
||||
messages = self.context_builder.build_messages(
|
||||
history,
|
||||
inbound,
|
||||
tool_summaries,
|
||||
provider_summary,
|
||||
)
|
||||
provider = self.providers.build(active_provider_id)
|
||||
|
||||
self.session.append(
|
||||
{
|
||||
@@ -40,6 +61,7 @@ class AgentRuntime:
|
||||
"message_id": inbound.message_id,
|
||||
"raw_body": inbound.raw_body,
|
||||
"session_id": inbound.session_id,
|
||||
"provider_id": active_provider_id,
|
||||
},
|
||||
session_id=inbound.session_id,
|
||||
)
|
||||
@@ -50,11 +72,13 @@ class AgentRuntime:
|
||||
|
||||
while iteration < self.config.max_iterations:
|
||||
iteration += 1
|
||||
response = self.provider.chat(messages=messages, tools=self.tools.schemas())
|
||||
response = provider.chat(messages=messages, tools=self.tools.schemas())
|
||||
|
||||
assistant_message = {
|
||||
"role": "assistant",
|
||||
"content": response.content,
|
||||
"provider_id": active_provider_id,
|
||||
"model_name": provider.model_name,
|
||||
}
|
||||
if response.has_tool_calls:
|
||||
assistant_message["tool_calls"] = [
|
||||
@@ -81,6 +105,7 @@ class AgentRuntime:
|
||||
"tool_call_id": tool_call.id,
|
||||
"name": tool_call.name,
|
||||
"run_id": inbound.run_id,
|
||||
"provider_id": active_provider_id,
|
||||
"content": self.tools.stringify_result(
|
||||
tool_call.name,
|
||||
tool_call.arguments,
|
||||
@@ -95,5 +120,119 @@ class AgentRuntime:
|
||||
)
|
||||
|
||||
return RunTurnResult(
|
||||
reply=final_reply, iterations=iteration, tool_events=tool_events
|
||||
reply=final_reply,
|
||||
iterations=iteration,
|
||||
tool_events=tool_events,
|
||||
provider_id=provider_description["id"],
|
||||
provider_label=provider_description["label"],
|
||||
model_name=provider.model_name,
|
||||
)
|
||||
|
||||
def _handle_control_command(
|
||||
self,
|
||||
inbound: InboundMessageContext,
|
||||
session_state: SessionState,
|
||||
) -> RunTurnResult | None:
|
||||
"""Handle built-in slash commands without calling the model."""
|
||||
text = inbound.body_for_agent.strip()
|
||||
if text == "/models":
|
||||
description = self._format_models(session_state.provider_id)
|
||||
self._record_control_command(
|
||||
inbound,
|
||||
command_text=text,
|
||||
reply_text=description,
|
||||
provider_id=session_state.provider_id or self.config.default_provider,
|
||||
)
|
||||
provider_description = self.providers.describe(session_state.provider_id)
|
||||
return RunTurnResult(
|
||||
reply=description,
|
||||
iterations=0,
|
||||
provider_id=provider_description["id"],
|
||||
provider_label=provider_description["label"],
|
||||
model_name=provider_description["model"],
|
||||
)
|
||||
|
||||
if text.startswith("/use "):
|
||||
provider_id = text.removeprefix("/use ").strip()
|
||||
if not provider_id:
|
||||
return None
|
||||
try:
|
||||
profile = self.providers.get_profile(provider_id)
|
||||
except ValueError as exc:
|
||||
provider_description = self.providers.describe(
|
||||
session_state.provider_id
|
||||
)
|
||||
return RunTurnResult(
|
||||
reply=str(exc),
|
||||
iterations=0,
|
||||
provider_id=provider_description["id"],
|
||||
provider_label=provider_description["label"],
|
||||
model_name=provider_description["model"],
|
||||
)
|
||||
state = self.session.update_session_state(
|
||||
inbound.session_id,
|
||||
provider_id=profile.id,
|
||||
)
|
||||
reply = (
|
||||
f"已切换到模型 {profile.id}: "
|
||||
f"{profile.label or profile.preset} / {profile.model or '(default)'}"
|
||||
)
|
||||
self._record_control_command(
|
||||
inbound,
|
||||
command_text=text,
|
||||
reply_text=reply,
|
||||
provider_id=state.provider_id or profile.id,
|
||||
)
|
||||
provider_description = self.providers.describe(state.provider_id)
|
||||
return RunTurnResult(
|
||||
reply=reply,
|
||||
iterations=0,
|
||||
provider_id=provider_description["id"],
|
||||
provider_label=provider_description["label"],
|
||||
model_name=provider_description["model"],
|
||||
)
|
||||
|
||||
return None
|
||||
|
||||
def _record_control_command(
|
||||
self,
|
||||
inbound: InboundMessageContext,
|
||||
*,
|
||||
command_text: str,
|
||||
reply_text: str,
|
||||
provider_id: str,
|
||||
) -> None:
|
||||
self.session.append(
|
||||
{
|
||||
"role": "command",
|
||||
"content": command_text,
|
||||
"run_id": inbound.run_id,
|
||||
"message_id": inbound.message_id,
|
||||
"provider_id": provider_id,
|
||||
},
|
||||
session_id=inbound.session_id,
|
||||
)
|
||||
self.session.append(
|
||||
{
|
||||
"role": "system",
|
||||
"content": reply_text,
|
||||
"run_id": inbound.run_id,
|
||||
"message_id": inbound.message_id,
|
||||
"provider_id": provider_id,
|
||||
},
|
||||
session_id=inbound.session_id,
|
||||
)
|
||||
|
||||
def _format_models(self, active_provider_id: str | None) -> str:
|
||||
current_id = active_provider_id or self.config.default_provider
|
||||
lines = ["可用模型列表:"]
|
||||
for profile in self.providers.list_profiles():
|
||||
description = self.providers.describe(profile.id)
|
||||
marker = "*" if description["id"] == current_id else " "
|
||||
lines.append(
|
||||
f"{marker} {description['id']}. "
|
||||
f"{description['label']} "
|
||||
f"[preset={description['preset']}, model={description['model']}]"
|
||||
)
|
||||
lines.append("使用 `/use <id>` 可切换当前会话的模型。")
|
||||
return "\n".join(lines)
|
||||
|
||||
+3
-4
@@ -7,7 +7,7 @@ from dataclasses import dataclass
|
||||
from voidbot.agent import AgentRuntime
|
||||
from voidbot.config import AppConfig
|
||||
from voidbot.context import ContextBuilder
|
||||
from voidbot.providers import build_provider
|
||||
from voidbot.providers import ProviderManager
|
||||
from voidbot.session import SessionStore
|
||||
from voidbot.tools import build_default_tool_registry
|
||||
|
||||
@@ -22,11 +22,10 @@ class VoidBotApp:
|
||||
|
||||
def build_app(config: AppConfig) -> VoidBotApp:
|
||||
"""Build a runtime app from config."""
|
||||
provider = build_provider(config)
|
||||
runtime = AgentRuntime(
|
||||
config=config,
|
||||
provider=provider,
|
||||
session=SessionStore(config.session_file),
|
||||
providers=ProviderManager(config),
|
||||
session=SessionStore(config.storage_path),
|
||||
tools=build_default_tool_registry(config.workspace),
|
||||
context_builder=ContextBuilder(config),
|
||||
)
|
||||
|
||||
+208
-79
@@ -22,9 +22,9 @@ def get_default_config_path() -> Path:
|
||||
return get_voidbot_home() / "config.json"
|
||||
|
||||
|
||||
def get_default_session_path() -> Path:
|
||||
"""Return the default session transcript path."""
|
||||
return get_voidbot_home() / "session.jsonl"
|
||||
def get_default_database_path() -> Path:
|
||||
"""Return the default SQLite database path."""
|
||||
return get_voidbot_home() / "voidbot.db"
|
||||
|
||||
|
||||
def get_cli_history_path() -> Path:
|
||||
@@ -39,15 +39,119 @@ def ensure_voidbot_home() -> Path:
|
||||
return path
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class ProviderConfig:
|
||||
"""One configured model endpoint."""
|
||||
|
||||
id: str
|
||||
preset: str
|
||||
api_key: str = ""
|
||||
api_base: str | None = None
|
||||
model: str | None = None
|
||||
label: str | None = None
|
||||
|
||||
@classmethod
|
||||
def from_mapping(
|
||||
cls,
|
||||
data: dict[str, Any],
|
||||
*,
|
||||
fallback_id: int,
|
||||
) -> "ProviderConfig":
|
||||
return cls(
|
||||
id=str(data.get("id") or fallback_id),
|
||||
preset=str(data.get("preset") or data.get("provider") or "openai_chatgpt"),
|
||||
api_key=str(data.get("api_key") or ""),
|
||||
api_base=str(data["api_base"]) if data.get("api_base") else None,
|
||||
model=str(data["model"]) if data.get("model") else None,
|
||||
label=str(data["label"]) if data.get("label") else None,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class FeishuChannelConfig:
|
||||
"""Feishu channel configuration."""
|
||||
|
||||
enabled: bool = False
|
||||
app_id: str = ""
|
||||
app_secret: str = ""
|
||||
encrypt_key: str | None = None
|
||||
verification_token: str | None = None
|
||||
group_policy: str = "mention"
|
||||
|
||||
@classmethod
|
||||
def from_mapping(cls, data: dict[str, Any] | None) -> "FeishuChannelConfig":
|
||||
payload = data or {}
|
||||
return cls(
|
||||
enabled=bool(payload.get("enabled", False)),
|
||||
app_id=str(payload.get("app_id") or ""),
|
||||
app_secret=str(payload.get("app_secret") or ""),
|
||||
encrypt_key=str(payload["encrypt_key"])
|
||||
if payload.get("encrypt_key")
|
||||
else None,
|
||||
verification_token=str(payload["verification_token"])
|
||||
if payload.get("verification_token")
|
||||
else None,
|
||||
group_policy=str(payload.get("group_policy") or "mention"),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class QQChannelConfig:
|
||||
"""QQ channel configuration."""
|
||||
|
||||
enabled: bool = False
|
||||
app_id: str = ""
|
||||
secret: str = ""
|
||||
|
||||
@classmethod
|
||||
def from_mapping(cls, data: dict[str, Any] | None) -> "QQChannelConfig":
|
||||
payload = data or {}
|
||||
return cls(
|
||||
enabled=bool(payload.get("enabled", False)),
|
||||
app_id=str(payload.get("app_id") or ""),
|
||||
secret=str(payload.get("secret") or ""),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class ChannelsConfig:
|
||||
"""Gateway channel settings."""
|
||||
|
||||
feishu: FeishuChannelConfig = field(default_factory=FeishuChannelConfig)
|
||||
qq: QQChannelConfig = field(default_factory=QQChannelConfig)
|
||||
|
||||
@classmethod
|
||||
def from_mapping(cls, data: dict[str, Any] | None) -> "ChannelsConfig":
|
||||
payload = data or {}
|
||||
return cls(
|
||||
feishu=FeishuChannelConfig.from_mapping(payload.get("feishu")),
|
||||
qq=QQChannelConfig.from_mapping(payload.get("qq")),
|
||||
)
|
||||
|
||||
|
||||
def build_example_config() -> dict[str, Any]:
|
||||
"""Return the built-in example config template."""
|
||||
return {
|
||||
"provider": "zhipu_coding_plan",
|
||||
"default_provider": "1",
|
||||
"providers": [
|
||||
{
|
||||
"id": "1",
|
||||
"label": "Zhipu Coding Plan",
|
||||
"preset": "zhipu_coding_plan",
|
||||
"api_key": "YOUR_API_KEY",
|
||||
"api_base": "https://open.bigmodel.cn/api/coding/paas/v4",
|
||||
"model": "glm-4.7",
|
||||
},
|
||||
{
|
||||
"id": "2",
|
||||
"label": "OpenAI ChatGPT",
|
||||
"preset": "openai_chatgpt",
|
||||
"api_key": "YOUR_OPENAI_API_KEY",
|
||||
"model": "gpt-4.1-mini",
|
||||
},
|
||||
],
|
||||
"workspace": ".",
|
||||
"session_file": "~/.voidbot/session.jsonl",
|
||||
"database_path": "~/.voidbot/voidbot.db",
|
||||
"max_iterations": 8,
|
||||
"history_limit": 24,
|
||||
"system_prompt": (
|
||||
@@ -120,68 +224,6 @@ def sync_default_config() -> tuple[Path, bool, list[str]]:
|
||||
return config_path, created, added_paths
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class FeishuChannelConfig:
|
||||
"""Feishu channel configuration."""
|
||||
|
||||
enabled: bool = False
|
||||
app_id: str = ""
|
||||
app_secret: str = ""
|
||||
encrypt_key: str | None = None
|
||||
verification_token: str | None = None
|
||||
group_policy: str = "mention"
|
||||
|
||||
@classmethod
|
||||
def from_mapping(cls, data: dict[str, Any] | None) -> "FeishuChannelConfig":
|
||||
payload = data or {}
|
||||
return cls(
|
||||
enabled=bool(payload.get("enabled", False)),
|
||||
app_id=str(payload.get("app_id") or ""),
|
||||
app_secret=str(payload.get("app_secret") or ""),
|
||||
encrypt_key=str(payload["encrypt_key"])
|
||||
if payload.get("encrypt_key")
|
||||
else None,
|
||||
verification_token=str(payload["verification_token"])
|
||||
if payload.get("verification_token")
|
||||
else None,
|
||||
group_policy=str(payload.get("group_policy") or "mention"),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class QQChannelConfig:
|
||||
"""QQ channel configuration."""
|
||||
|
||||
enabled: bool = False
|
||||
app_id: str = ""
|
||||
secret: str = ""
|
||||
|
||||
@classmethod
|
||||
def from_mapping(cls, data: dict[str, Any] | None) -> "QQChannelConfig":
|
||||
payload = data or {}
|
||||
return cls(
|
||||
enabled=bool(payload.get("enabled", False)),
|
||||
app_id=str(payload.get("app_id") or ""),
|
||||
secret=str(payload.get("secret") or ""),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class ChannelsConfig:
|
||||
"""Gateway channel settings."""
|
||||
|
||||
feishu: FeishuChannelConfig = field(default_factory=FeishuChannelConfig)
|
||||
qq: QQChannelConfig = field(default_factory=QQChannelConfig)
|
||||
|
||||
@classmethod
|
||||
def from_mapping(cls, data: dict[str, Any] | None) -> "ChannelsConfig":
|
||||
payload = data or {}
|
||||
return cls(
|
||||
feishu=FeishuChannelConfig.from_mapping(payload.get("feishu")),
|
||||
qq=QQChannelConfig.from_mapping(payload.get("qq")),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class AppConfig:
|
||||
"""Runtime configuration."""
|
||||
@@ -190,8 +232,11 @@ class AppConfig:
|
||||
api_key: str = ""
|
||||
api_base: str | None = None
|
||||
model: str | None = None
|
||||
providers: list[ProviderConfig] = field(default_factory=list)
|
||||
default_provider: str = "1"
|
||||
workspace: Path = Path(".")
|
||||
session_file: Path = field(default_factory=get_default_session_path)
|
||||
database_path: Path | None = None
|
||||
session_file: Path | None = None
|
||||
max_iterations: int = 8
|
||||
history_limit: int = 24
|
||||
system_prompt: str | None = None
|
||||
@@ -206,18 +251,40 @@ class AppConfig:
|
||||
def from_mapping(cls, data: dict[str, Any]) -> "AppConfig":
|
||||
"""Build config from a user mapping."""
|
||||
workspace = Path(data.get("workspace") or ".").expanduser().resolve()
|
||||
session_value = data.get("session_file") or str(get_default_session_path())
|
||||
session_file = Path(session_value).expanduser()
|
||||
if not session_file.is_absolute():
|
||||
session_file = workspace / session_file
|
||||
provider_list = cls._parse_provider_list(data)
|
||||
default_provider = str(data.get("default_provider") or "1")
|
||||
if provider_list:
|
||||
resolved_default = cls._pick_provider(provider_list, default_provider)
|
||||
default_provider = resolved_default.id
|
||||
provider = resolved_default.preset
|
||||
api_key = resolved_default.api_key
|
||||
api_base = resolved_default.api_base
|
||||
model = resolved_default.model
|
||||
else:
|
||||
provider = str(data.get("provider") or "openai_chatgpt")
|
||||
api_key = str(data.get("api_key") or "")
|
||||
api_base = str(data["api_base"]) if data.get("api_base") else None
|
||||
model = str(data["model"]) if data.get("model") else None
|
||||
|
||||
database_value = (
|
||||
data.get("database_path")
|
||||
or data.get("session_file")
|
||||
or str(get_default_database_path())
|
||||
)
|
||||
database_path = Path(database_value).expanduser()
|
||||
if not database_path.is_absolute():
|
||||
database_path = workspace / database_path
|
||||
|
||||
return cls(
|
||||
provider=str(data.get("provider") or "openai_chatgpt"),
|
||||
api_key=str(data.get("api_key") or ""),
|
||||
api_base=str(data["api_base"]) if data.get("api_base") else None,
|
||||
model=str(data["model"]) if data.get("model") else None,
|
||||
provider=provider,
|
||||
api_key=api_key,
|
||||
api_base=api_base,
|
||||
model=model,
|
||||
providers=provider_list,
|
||||
default_provider=default_provider,
|
||||
workspace=workspace,
|
||||
session_file=session_file.resolve(),
|
||||
database_path=database_path.resolve(),
|
||||
session_file=database_path.resolve(),
|
||||
max_iterations=int(data.get("max_iterations") or 8),
|
||||
history_limit=int(data.get("history_limit") or 24),
|
||||
system_prompt=str(data["system_prompt"])
|
||||
@@ -231,6 +298,63 @@ class AppConfig:
|
||||
channels=ChannelsConfig.from_mapping(data.get("channels")),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _parse_provider_list(data: dict[str, Any]) -> list[ProviderConfig]:
|
||||
raw_providers = data.get("providers")
|
||||
if not isinstance(raw_providers, list):
|
||||
return []
|
||||
providers: list[ProviderConfig] = []
|
||||
for index, item in enumerate(raw_providers, start=1):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
providers.append(ProviderConfig.from_mapping(item, fallback_id=index))
|
||||
return providers
|
||||
|
||||
@staticmethod
|
||||
def _pick_provider(
|
||||
providers: list[ProviderConfig],
|
||||
provider_id: str | None,
|
||||
) -> ProviderConfig:
|
||||
if provider_id:
|
||||
for provider in providers:
|
||||
if provider.id == str(provider_id):
|
||||
return provider
|
||||
if not providers:
|
||||
raise ValueError("at least one provider must be configured")
|
||||
return providers[0]
|
||||
|
||||
@property
|
||||
def storage_path(self) -> Path:
|
||||
"""Return the resolved SQLite database path."""
|
||||
if self.database_path is not None:
|
||||
return self.database_path
|
||||
if self.session_file is not None:
|
||||
return self.session_file
|
||||
return get_default_database_path()
|
||||
|
||||
def list_provider_configs(self) -> list[ProviderConfig]:
|
||||
"""Return all configured providers."""
|
||||
if self.providers:
|
||||
return list(self.providers)
|
||||
return [
|
||||
ProviderConfig(
|
||||
id="1",
|
||||
preset=self.provider,
|
||||
api_key=self.api_key,
|
||||
api_base=self.api_base,
|
||||
model=self.model,
|
||||
)
|
||||
]
|
||||
|
||||
def get_provider_config(self, provider_id: str | None = None) -> ProviderConfig:
|
||||
"""Resolve a configured provider by id."""
|
||||
providers = self.list_provider_configs()
|
||||
target_id = str(provider_id or self.default_provider or "1")
|
||||
for provider in providers:
|
||||
if provider.id == target_id:
|
||||
return provider
|
||||
return providers[0]
|
||||
|
||||
|
||||
def load_config(
|
||||
config_path: str | Path | None,
|
||||
@@ -258,7 +382,9 @@ def load_config(
|
||||
"api_key": os.getenv("VOIDBOT_API_KEY"),
|
||||
"api_base": os.getenv("VOIDBOT_API_BASE"),
|
||||
"model": os.getenv("VOIDBOT_MODEL"),
|
||||
"default_provider": os.getenv("VOIDBOT_DEFAULT_PROVIDER"),
|
||||
"workspace": os.getenv("VOIDBOT_WORKSPACE"),
|
||||
"database_path": os.getenv("VOIDBOT_DATABASE_PATH"),
|
||||
"session_file": os.getenv("VOIDBOT_SESSION_FILE"),
|
||||
"max_iterations": os.getenv("VOIDBOT_MAX_ITERATIONS"),
|
||||
"history_limit": os.getenv("VOIDBOT_HISTORY_LIMIT"),
|
||||
@@ -274,8 +400,11 @@ def load_config(
|
||||
payload[key] = value
|
||||
|
||||
config = AppConfig.from_mapping(payload)
|
||||
if require_api_key and not config.api_key:
|
||||
if require_api_key:
|
||||
default_provider = config.get_provider_config()
|
||||
if not default_provider.api_key:
|
||||
raise ValueError(
|
||||
"api_key is required. Set it in config JSON or VOIDBOT_API_KEY."
|
||||
"a default provider api_key is required. "
|
||||
"Set it in config JSON or VOIDBOT_API_KEY."
|
||||
)
|
||||
return config
|
||||
|
||||
@@ -22,9 +22,14 @@ class ContextBuilder:
|
||||
history: list[dict],
|
||||
inbound: InboundMessageContext,
|
||||
tool_summaries: list[str],
|
||||
provider_summary: str,
|
||||
) -> list[dict]:
|
||||
"""Build a chat completion message array."""
|
||||
runtime_block = self._build_runtime_block(inbound, tool_summaries)
|
||||
runtime_block = self._build_runtime_block(
|
||||
inbound,
|
||||
tool_summaries,
|
||||
provider_summary,
|
||||
)
|
||||
return [
|
||||
{"role": "system", "content": self._build_system_prompt()},
|
||||
*history,
|
||||
@@ -49,6 +54,7 @@ class ContextBuilder:
|
||||
self,
|
||||
inbound: InboundMessageContext,
|
||||
tool_summaries: list[str],
|
||||
provider_summary: str,
|
||||
) -> str:
|
||||
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
tool_text = (
|
||||
@@ -64,6 +70,7 @@ class ContextBuilder:
|
||||
f"Run ID: {inbound.run_id}\n"
|
||||
f"Message ID: {inbound.message_id}\n"
|
||||
f"Received At: {inbound.received_at}\n"
|
||||
f"Provider: {provider_summary}\n"
|
||||
"Available Tools:\n"
|
||||
f"{tool_text}\n\n"
|
||||
"Workspace Instructions:\n"
|
||||
|
||||
+114
-10
@@ -3,7 +3,11 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from voidbot.app import build_app
|
||||
from voidbot.channels.manager import ChannelManager
|
||||
@@ -18,29 +22,35 @@ from voidbot.gateway.client import GatewayClient
|
||||
from voidbot.gateway.messages import InboundMessageContext
|
||||
from voidbot.gateway.server import GatewayApplication, run_gateway_server
|
||||
from voidbot.gateway.ui import render_single_turn, run_terminal_loop
|
||||
from voidbot.session import SessionStore
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
"""Build CLI parser."""
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="voidbot", description="VoidBot CLI and gateway"
|
||||
prog="voidbot",
|
||||
description="VoidBot CLI, gateway, config, and data tools",
|
||||
)
|
||||
_add_agent_arguments(parser)
|
||||
subparsers = parser.add_subparsers(dest="command", required=False)
|
||||
|
||||
agent_parser = subparsers.add_parser(
|
||||
"agent", help="Run the agent locally or via gateway"
|
||||
"agent",
|
||||
help="Run the agent locally or via gateway",
|
||||
)
|
||||
_add_agent_arguments(agent_parser)
|
||||
|
||||
chat_parser = subparsers.add_parser(
|
||||
"chat", help="Backward-compatible alias of agent"
|
||||
"chat",
|
||||
help="Backward-compatible alias of agent",
|
||||
)
|
||||
_add_agent_arguments(chat_parser)
|
||||
|
||||
gateway_parser = subparsers.add_parser("gateway", help="Run the gateway server")
|
||||
gateway_parser.add_argument(
|
||||
"--config", type=Path, help="Path to a JSON config file"
|
||||
"--config",
|
||||
type=Path,
|
||||
help=_config_help_text(),
|
||||
)
|
||||
gateway_parser.add_argument("--host", help="Gateway bind host")
|
||||
gateway_parser.add_argument("--port", type=int, help="Gateway bind port")
|
||||
@@ -62,6 +72,42 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
action="store_true",
|
||||
help="Print the target config path after syncing",
|
||||
)
|
||||
config_subparsers.add_parser(
|
||||
"path",
|
||||
help="Print the default user-level config path",
|
||||
)
|
||||
config_subparsers.add_parser(
|
||||
"open",
|
||||
help="Open the default config file with the system default application",
|
||||
)
|
||||
|
||||
data_parser = subparsers.add_parser(
|
||||
"data",
|
||||
help="Inspect the SQLite-backed stored sessions and messages",
|
||||
)
|
||||
data_subparsers = data_parser.add_subparsers(
|
||||
dest="data_command",
|
||||
required=True,
|
||||
)
|
||||
dump_parser = data_subparsers.add_parser(
|
||||
"dump",
|
||||
help="Print stored sessions and messages from the SQLite database",
|
||||
)
|
||||
dump_parser.add_argument(
|
||||
"--config",
|
||||
type=Path,
|
||||
help=_config_help_text(),
|
||||
)
|
||||
dump_parser.add_argument(
|
||||
"--session-id",
|
||||
help="Optional session id filter",
|
||||
)
|
||||
dump_parser.add_argument(
|
||||
"--limit",
|
||||
type=int,
|
||||
help="Limit the number of returned messages",
|
||||
)
|
||||
|
||||
return parser
|
||||
|
||||
|
||||
@@ -86,18 +132,36 @@ def main() -> None:
|
||||
port=args.port,
|
||||
)
|
||||
return
|
||||
if args.command == "config" and args.config_command == "sync":
|
||||
if args.command == "config":
|
||||
if args.config_command == "sync":
|
||||
run_config_sync_command(show_path=args.path)
|
||||
return
|
||||
if args.config_command == "path":
|
||||
run_config_path_command()
|
||||
return
|
||||
if args.config_command == "open":
|
||||
run_config_open_command()
|
||||
return
|
||||
if args.command == "data" and args.data_command == "dump":
|
||||
run_data_dump_command(
|
||||
config_path=args.config,
|
||||
session_id=args.session_id,
|
||||
limit=args.limit,
|
||||
)
|
||||
|
||||
|
||||
def _config_help_text() -> str:
|
||||
return (
|
||||
"Path to a JSON config file. "
|
||||
f"Default lookup: ./config.json, then {get_default_config_path()}"
|
||||
)
|
||||
|
||||
|
||||
def _add_agent_arguments(parser: argparse.ArgumentParser) -> None:
|
||||
parser.add_argument(
|
||||
"--config",
|
||||
type=Path,
|
||||
help=(
|
||||
"Path to a JSON config file. "
|
||||
f"Default lookup: ./config.json, then {get_default_config_path()}"
|
||||
),
|
||||
help=_config_help_text(),
|
||||
)
|
||||
parser.add_argument("--message", "-m", help="Send one message and exit")
|
||||
parser.add_argument(
|
||||
@@ -107,7 +171,8 @@ def _add_agent_arguments(parser: argparse.ArgumentParser) -> None:
|
||||
help="Choose how the CLI reaches the agent runtime.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--gateway-url", help="Gateway base URL, e.g. http://127.0.0.1:8787"
|
||||
"--gateway-url",
|
||||
help="Gateway base URL, e.g. http://127.0.0.1:8787",
|
||||
)
|
||||
parser.add_argument("--gateway-host", help="Gateway host override")
|
||||
parser.add_argument("--gateway-port", type=int, help="Gateway port override")
|
||||
@@ -196,6 +261,42 @@ def run_config_sync_command(*, show_path: bool) -> None:
|
||||
print(f"VoidBot home: {get_voidbot_home()}")
|
||||
|
||||
|
||||
def run_config_path_command() -> None:
|
||||
"""Print the default user-level config path."""
|
||||
print(get_default_config_path())
|
||||
|
||||
|
||||
def run_config_open_command() -> None:
|
||||
"""Open the default config file."""
|
||||
config_path, _, _ = sync_default_config()
|
||||
_open_path(config_path)
|
||||
print(f"Opened {config_path}")
|
||||
|
||||
|
||||
def run_data_dump_command(
|
||||
*,
|
||||
config_path: Path | None,
|
||||
session_id: str | None,
|
||||
limit: int | None,
|
||||
) -> None:
|
||||
"""Print stored SQLite data."""
|
||||
config = load_config(config_path, require_api_key=False)
|
||||
store = SessionStore(config.storage_path)
|
||||
payload = store.dump_data(session_id=session_id, limit=limit)
|
||||
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
def _open_path(path: Path) -> None:
|
||||
"""Open a path with the platform default application."""
|
||||
if os.name == "nt":
|
||||
os.startfile(path) # type: ignore[attr-defined]
|
||||
return
|
||||
if sys.platform == "darwin":
|
||||
subprocess.Popen(["/usr/bin/open", str(path)])
|
||||
return
|
||||
subprocess.Popen(["/usr/bin/xdg-open", str(path)])
|
||||
|
||||
|
||||
def _run_one_turn(
|
||||
*,
|
||||
message: str,
|
||||
@@ -238,6 +339,9 @@ def _run_local(inbound: InboundMessageContext, config: AppConfig | None) -> dict
|
||||
"reply": result.reply,
|
||||
"iterations": result.iterations,
|
||||
"tool_events": result.tool_events,
|
||||
"provider_id": result.provider_id,
|
||||
"provider_label": result.provider_label,
|
||||
"model_name": result.model_name,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -21,9 +21,12 @@ class GatewayApplication:
|
||||
|
||||
def health(self) -> dict[str, Any]:
|
||||
"""Return gateway health."""
|
||||
default_provider = self.runtime.config.get_provider_config()
|
||||
return {
|
||||
"ok": True,
|
||||
"provider": self.runtime.config.provider,
|
||||
"provider": default_provider.preset,
|
||||
"default_provider": default_provider.id,
|
||||
"model": default_provider.model,
|
||||
"workspace": str(self.runtime.config.workspace),
|
||||
"channels": self.channel_manager.get_status()
|
||||
if self.channel_manager
|
||||
@@ -58,6 +61,9 @@ class GatewayApplication:
|
||||
"reply": result.reply,
|
||||
"iterations": result.iterations,
|
||||
"tool_events": result.tool_events,
|
||||
"provider_id": result.provider_id,
|
||||
"provider_label": result.provider_label,
|
||||
"model_name": result.model_name,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -41,6 +41,9 @@ class TerminalUI:
|
||||
gateway_url: str | None
|
||||
console: Console
|
||||
session: PromptSession
|
||||
active_provider_id: str
|
||||
active_provider_label: str
|
||||
active_model_name: str
|
||||
|
||||
@classmethod
|
||||
def create(
|
||||
@@ -60,12 +63,24 @@ class TerminalUI:
|
||||
style=PROMPT_STYLE,
|
||||
reserve_space_for_menu=0,
|
||||
)
|
||||
if config is not None:
|
||||
default_provider = config.get_provider_config()
|
||||
provider_id = default_provider.id
|
||||
provider_label = default_provider.label or default_provider.preset
|
||||
model_name = default_provider.model or "(default)"
|
||||
else:
|
||||
provider_id = "?"
|
||||
provider_label = "gateway"
|
||||
model_name = "(remote)"
|
||||
return cls(
|
||||
via=via,
|
||||
config=config,
|
||||
gateway_url=gateway_url,
|
||||
console=Console(),
|
||||
session=session,
|
||||
active_provider_id=provider_id,
|
||||
active_provider_label=provider_label,
|
||||
active_model_name=model_name,
|
||||
)
|
||||
|
||||
def print_welcome(self) -> None:
|
||||
@@ -81,16 +96,18 @@ class TerminalUI:
|
||||
)
|
||||
details = [
|
||||
f"mode={self.via}",
|
||||
f"provider={self.config.provider}"
|
||||
f"provider={self.active_provider_id} {self.active_provider_label}"
|
||||
if self.config
|
||||
else "provider=(gateway-only)",
|
||||
f"model={self.active_model_name}",
|
||||
]
|
||||
if self.gateway_url:
|
||||
details.append(f"gateway={self.gateway_url}")
|
||||
self.console.print(
|
||||
Panel.fit(
|
||||
"\n".join(details)
|
||||
+ "\nEnter submit, Esc+Enter newline, Ctrl+L clear screen",
|
||||
+ "\nEnter submit, Esc+Enter newline, Ctrl+L clear screen"
|
||||
+ "\n/use <id> 切换模型, /models 查看可用模型",
|
||||
title="[bold #c0caf5]Session[/bold #c0caf5]",
|
||||
border_style="#7aa2f7",
|
||||
padding=(0, 1),
|
||||
@@ -124,6 +141,7 @@ class TerminalUI:
|
||||
|
||||
def render_turn(self, user_message: str, result: dict) -> None:
|
||||
"""Render one full turn."""
|
||||
self._apply_result_state(result)
|
||||
self.console.print()
|
||||
self.console.print(
|
||||
Panel(
|
||||
@@ -159,19 +177,28 @@ class TerminalUI:
|
||||
)
|
||||
|
||||
def _bottom_toolbar(self) -> HTML:
|
||||
provider = self.config.provider if self.config else "gateway"
|
||||
model = self.config.model or "(default)" if self.config else "(remote)"
|
||||
gateway = self.gateway_url or "-"
|
||||
return HTML(
|
||||
"<bottom>"
|
||||
f" via {self.via} "
|
||||
f"• provider {provider} "
|
||||
f"• model {model} "
|
||||
f"• provider {self.active_provider_id}:{self.active_provider_label} "
|
||||
f"• model {self.active_model_name} "
|
||||
f"• gateway {gateway} "
|
||||
"• exit quit/exit "
|
||||
"</bottom>"
|
||||
)
|
||||
|
||||
def _apply_result_state(self, result: dict) -> None:
|
||||
provider_id = result.get("provider_id")
|
||||
provider_label = result.get("provider_label")
|
||||
model_name = result.get("model_name")
|
||||
if provider_id:
|
||||
self.active_provider_id = str(provider_id)
|
||||
if provider_label:
|
||||
self.active_provider_label = str(provider_label)
|
||||
if model_name:
|
||||
self.active_model_name = str(model_name)
|
||||
|
||||
|
||||
def run_terminal_loop(
|
||||
*,
|
||||
@@ -251,7 +278,10 @@ def _render_tool_event(event: dict, index: int) -> Panel:
|
||||
|
||||
def _build_reply_subtitle(result: dict) -> str:
|
||||
tool_count = len(result.get("tool_events") or [])
|
||||
provider = result.get("provider_id") or "?"
|
||||
model = result.get("model_name") or "(unknown)"
|
||||
return (
|
||||
f"mode={result.get('mode')} · iter={result.get('iterations')} · "
|
||||
f"tools={tool_count} · run={result.get('run_id')}"
|
||||
f"tools={tool_count} · provider={provider} · model={model} · "
|
||||
f"run={result.get('run_id')}"
|
||||
)
|
||||
|
||||
@@ -49,3 +49,6 @@ class RunTurnResult:
|
||||
reply: str
|
||||
iterations: int
|
||||
tool_events: list[dict[str, Any]] = field(default_factory=list)
|
||||
provider_id: str | None = None
|
||||
provider_label: str | None = None
|
||||
model_name: str | None = None
|
||||
|
||||
@@ -1,17 +1,23 @@
|
||||
"""Provider helpers."""
|
||||
|
||||
from voidbot.config import AppConfig
|
||||
from voidbot.config import ProviderConfig
|
||||
from voidbot.providers.openai_compatible import OpenAICompatibleProvider
|
||||
from voidbot.providers.manager import ProviderManager
|
||||
from voidbot.providers.registry import get_provider_spec
|
||||
|
||||
|
||||
def build_provider(config: AppConfig) -> OpenAICompatibleProvider:
|
||||
"""Build the configured provider."""
|
||||
spec = get_provider_spec(config.provider)
|
||||
def build_provider(
|
||||
profile: ProviderConfig, *, timeout: int = 120
|
||||
) -> OpenAICompatibleProvider:
|
||||
"""Build one configured provider client."""
|
||||
spec = get_provider_spec(profile.preset)
|
||||
return OpenAICompatibleProvider(
|
||||
spec=spec,
|
||||
api_key=config.api_key,
|
||||
api_base=config.api_base or spec.default_base_url,
|
||||
_model_name=config.model or spec.default_model,
|
||||
timeout=config.request_timeout,
|
||||
api_key=profile.api_key,
|
||||
api_base=profile.api_base or spec.default_base_url,
|
||||
_model_name=profile.model or spec.default_model,
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["ProviderManager", "build_provider"]
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Configured provider catalog."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from voidbot.config import AppConfig, ProviderConfig
|
||||
from voidbot.providers.openai_compatible import OpenAICompatibleProvider
|
||||
from voidbot.providers.registry import get_provider_spec
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class ProviderManager:
|
||||
"""Resolve configured providers by id."""
|
||||
|
||||
config: AppConfig
|
||||
|
||||
def list_profiles(self) -> list[ProviderConfig]:
|
||||
"""Return all configured provider profiles."""
|
||||
return self.config.list_provider_configs()
|
||||
|
||||
def get_profile(self, provider_id: str | None = None) -> ProviderConfig:
|
||||
"""Resolve one configured provider profile."""
|
||||
if provider_id is None:
|
||||
return self.config.get_provider_config(None)
|
||||
for profile in self.list_profiles():
|
||||
if profile.id == str(provider_id):
|
||||
return profile
|
||||
available = ", ".join(profile.id for profile in self.list_profiles())
|
||||
raise ValueError(
|
||||
f"unknown provider id '{provider_id}', expected one of: {available}"
|
||||
)
|
||||
|
||||
def build(self, provider_id: str | None = None) -> OpenAICompatibleProvider:
|
||||
"""Build a provider client for the given profile."""
|
||||
profile = self.get_profile(provider_id)
|
||||
spec = get_provider_spec(profile.preset)
|
||||
return OpenAICompatibleProvider(
|
||||
spec=spec,
|
||||
api_key=profile.api_key,
|
||||
api_base=profile.api_base or spec.default_base_url,
|
||||
_model_name=profile.model or spec.default_model,
|
||||
timeout=self.config.request_timeout,
|
||||
)
|
||||
|
||||
def describe(self, provider_id: str | None = None) -> dict[str, str]:
|
||||
"""Return a display-friendly description of a provider profile."""
|
||||
profile = self.get_profile(provider_id)
|
||||
spec = get_provider_spec(profile.preset)
|
||||
model_name = profile.model or spec.default_model
|
||||
label = profile.label or spec.label
|
||||
return {
|
||||
"id": profile.id,
|
||||
"preset": profile.preset,
|
||||
"label": label,
|
||||
"model": model_name,
|
||||
}
|
||||
+271
-31
@@ -1,12 +1,13 @@
|
||||
"""Session transcript storage."""
|
||||
"""SQLite-backed session storage."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import closing
|
||||
import json
|
||||
import sqlite3
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
import re
|
||||
import threading
|
||||
from typing import Any
|
||||
|
||||
@@ -15,23 +16,186 @@ def _utc_now() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class SessionState:
|
||||
"""Stored session metadata."""
|
||||
|
||||
session_id: str
|
||||
provider_id: str | None = None
|
||||
metadata: dict[str, Any] = field(default_factory=dict)
|
||||
created_at: str | None = None
|
||||
updated_at: str | None = None
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class SessionStore:
|
||||
"""Append-only JSONL session storage."""
|
||||
"""SQLite-backed chat history and session metadata."""
|
||||
|
||||
path: Path
|
||||
_lock: threading.RLock = field(default_factory=threading.RLock)
|
||||
|
||||
def ensure_parent(self, path: Path) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
def __post_init__(self) -> None:
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self._initialize()
|
||||
|
||||
def _connect(self) -> sqlite3.Connection:
|
||||
connection = sqlite3.connect(self.path, check_same_thread=False)
|
||||
connection.row_factory = sqlite3.Row
|
||||
return connection
|
||||
|
||||
def _initialize(self) -> None:
|
||||
with self._lock:
|
||||
with closing(self._connect()) as connection:
|
||||
connection.execute("PRAGMA journal_mode=WAL")
|
||||
connection.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
session_id TEXT PRIMARY KEY,
|
||||
provider_id TEXT,
|
||||
metadata_json TEXT NOT NULL DEFAULT '{}',
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
)
|
||||
"""
|
||||
)
|
||||
connection.commit()
|
||||
connection.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_id TEXT NOT NULL,
|
||||
role TEXT NOT NULL,
|
||||
content TEXT,
|
||||
payload_json TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
def ensure_session(
|
||||
self,
|
||||
session_id: str,
|
||||
*,
|
||||
provider_id: str | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> SessionState:
|
||||
"""Ensure a session row exists and return it."""
|
||||
now = _utc_now()
|
||||
with self._lock:
|
||||
with closing(self._connect()) as connection:
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO sessions (session_id, provider_id, metadata_json, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(session_id) DO NOTHING
|
||||
""",
|
||||
(
|
||||
session_id,
|
||||
provider_id,
|
||||
json.dumps(metadata or {}, ensure_ascii=False),
|
||||
now,
|
||||
now,
|
||||
),
|
||||
)
|
||||
connection.commit()
|
||||
return self.get_session_state(session_id) or SessionState(session_id=session_id)
|
||||
|
||||
def get_session_state(self, session_id: str) -> SessionState | None:
|
||||
"""Load one session state."""
|
||||
with self._lock:
|
||||
with closing(self._connect()) as connection:
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT session_id, provider_id, metadata_json, created_at, updated_at
|
||||
FROM sessions
|
||||
WHERE session_id = ?
|
||||
""",
|
||||
(session_id,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
metadata = json.loads(row["metadata_json"] or "{}")
|
||||
if not isinstance(metadata, dict):
|
||||
metadata = {}
|
||||
return SessionState(
|
||||
session_id=str(row["session_id"]),
|
||||
provider_id=str(row["provider_id"]) if row["provider_id"] else None,
|
||||
metadata=metadata,
|
||||
created_at=str(row["created_at"]),
|
||||
updated_at=str(row["updated_at"]),
|
||||
)
|
||||
|
||||
def update_session_state(
|
||||
self,
|
||||
session_id: str,
|
||||
*,
|
||||
provider_id: str | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> SessionState:
|
||||
"""Merge and persist session metadata."""
|
||||
current = self.get_session_state(session_id)
|
||||
merged_metadata = dict(current.metadata if current else {})
|
||||
if metadata:
|
||||
merged_metadata.update(metadata)
|
||||
resolved_provider = (
|
||||
provider_id
|
||||
if provider_id is not None
|
||||
else (current.provider_id if current else None)
|
||||
)
|
||||
|
||||
now = _utc_now()
|
||||
with self._lock:
|
||||
with closing(self._connect()) as connection:
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO sessions (session_id, provider_id, metadata_json, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(session_id) DO UPDATE SET
|
||||
provider_id = excluded.provider_id,
|
||||
metadata_json = excluded.metadata_json,
|
||||
updated_at = excluded.updated_at
|
||||
""",
|
||||
(
|
||||
session_id,
|
||||
resolved_provider,
|
||||
json.dumps(merged_metadata, ensure_ascii=False),
|
||||
current.created_at if current and current.created_at else now,
|
||||
now,
|
||||
),
|
||||
)
|
||||
connection.commit()
|
||||
return self.get_session_state(session_id) or SessionState(session_id=session_id)
|
||||
|
||||
def append(self, message: dict[str, Any], *, session_id: str = "main") -> None:
|
||||
path = self.path_for(session_id)
|
||||
self.ensure_parent(path)
|
||||
record = {"timestamp": _utc_now(), **message}
|
||||
"""Append one raw message payload."""
|
||||
self.ensure_session(session_id)
|
||||
payload = dict(message)
|
||||
content = payload.get("content")
|
||||
now = _utc_now()
|
||||
with self._lock:
|
||||
with path.open("a", encoding="utf-8") as handle:
|
||||
handle.write(json.dumps(record, ensure_ascii=False) + "\n")
|
||||
with closing(self._connect()) as connection:
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO messages (session_id, role, content, payload_json, created_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
session_id,
|
||||
str(payload.get("role") or "unknown"),
|
||||
str(content) if content is not None else None,
|
||||
json.dumps(payload, ensure_ascii=False),
|
||||
now,
|
||||
),
|
||||
)
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE sessions
|
||||
SET updated_at = ?
|
||||
WHERE session_id = ?
|
||||
""",
|
||||
(now, session_id),
|
||||
)
|
||||
connection.commit()
|
||||
|
||||
def load_history(
|
||||
self,
|
||||
@@ -39,24 +203,27 @@ class SessionStore:
|
||||
*,
|
||||
session_id: str = "main",
|
||||
) -> list[dict[str, Any]]:
|
||||
path = self.path_for(session_id)
|
||||
if not path.exists():
|
||||
return []
|
||||
rows: list[dict[str, Any]] = []
|
||||
"""Load chat history for LLM input."""
|
||||
self.ensure_session(session_id)
|
||||
with self._lock:
|
||||
with path.open("r", encoding="utf-8") as handle:
|
||||
for line in handle:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
rows.append(json.loads(line))
|
||||
trimmed = rows[-limit:]
|
||||
with closing(self._connect()) as connection:
|
||||
rows = connection.execute(
|
||||
"""
|
||||
SELECT payload_json
|
||||
FROM messages
|
||||
WHERE session_id = ?
|
||||
ORDER BY id DESC
|
||||
LIMIT ?
|
||||
""",
|
||||
(session_id, limit),
|
||||
).fetchall()
|
||||
parsed_rows = [json.loads(row["payload_json"]) for row in reversed(rows)]
|
||||
start_index = 0
|
||||
for index, row in enumerate(trimmed):
|
||||
for index, row in enumerate(parsed_rows):
|
||||
if row.get("role") == "user":
|
||||
start_index = index
|
||||
break
|
||||
aligned = trimmed[start_index:]
|
||||
aligned = parsed_rows[start_index:]
|
||||
messages: list[dict[str, Any]] = []
|
||||
for row in aligned:
|
||||
message = self._to_llm_message(row)
|
||||
@@ -64,15 +231,88 @@ class SessionStore:
|
||||
messages.append(message)
|
||||
return messages
|
||||
|
||||
def path_for(self, session_id: str = "main") -> Path:
|
||||
"""Resolve the transcript file for a session."""
|
||||
if session_id == "main":
|
||||
return self.path
|
||||
def list_sessions(self) -> list[dict[str, Any]]:
|
||||
"""Return all sessions and metadata."""
|
||||
with self._lock:
|
||||
with closing(self._connect()) as connection:
|
||||
rows = connection.execute(
|
||||
"""
|
||||
SELECT session_id, provider_id, metadata_json, created_at, updated_at
|
||||
FROM sessions
|
||||
ORDER BY updated_at DESC, session_id ASC
|
||||
"""
|
||||
).fetchall()
|
||||
sessions: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
metadata = json.loads(row["metadata_json"] or "{}")
|
||||
sessions.append(
|
||||
{
|
||||
"session_id": row["session_id"],
|
||||
"provider_id": row["provider_id"],
|
||||
"metadata": metadata if isinstance(metadata, dict) else {},
|
||||
"created_at": row["created_at"],
|
||||
"updated_at": row["updated_at"],
|
||||
}
|
||||
)
|
||||
return sessions
|
||||
|
||||
suffix = self.path.suffix or ".jsonl"
|
||||
safe_session = re.sub(r"[^a-zA-Z0-9._-]+", "_", session_id).strip("_")
|
||||
safe_session = safe_session or "session"
|
||||
return self.path.parent / f"{self.path.stem}-{safe_session}{suffix}"
|
||||
def list_messages(
|
||||
self,
|
||||
*,
|
||||
session_id: str | None = None,
|
||||
limit: int | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Return stored messages."""
|
||||
query = """
|
||||
SELECT id, session_id, role, content, payload_json, created_at
|
||||
FROM messages
|
||||
"""
|
||||
params: list[Any] = []
|
||||
clauses: list[str] = []
|
||||
if session_id:
|
||||
clauses.append("session_id = ?")
|
||||
params.append(session_id)
|
||||
if clauses:
|
||||
query += " WHERE " + " AND ".join(clauses)
|
||||
query += " ORDER BY id ASC"
|
||||
if limit is not None:
|
||||
query += " LIMIT ?"
|
||||
params.append(limit)
|
||||
|
||||
with self._lock:
|
||||
with closing(self._connect()) as connection:
|
||||
rows = connection.execute(query, params).fetchall()
|
||||
|
||||
messages: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
payload = json.loads(row["payload_json"])
|
||||
messages.append(
|
||||
{
|
||||
"id": row["id"],
|
||||
"session_id": row["session_id"],
|
||||
"role": row["role"],
|
||||
"content": row["content"],
|
||||
"payload": payload,
|
||||
"created_at": row["created_at"],
|
||||
}
|
||||
)
|
||||
return messages
|
||||
|
||||
def dump_data(
|
||||
self,
|
||||
*,
|
||||
session_id: str | None = None,
|
||||
limit: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Return a JSON-serializable dump of stored data."""
|
||||
sessions = self.list_sessions()
|
||||
if session_id is not None:
|
||||
sessions = [item for item in sessions if item["session_id"] == session_id]
|
||||
return {
|
||||
"database_path": str(self.path),
|
||||
"sessions": sessions,
|
||||
"messages": self.list_messages(session_id=session_id, limit=limit),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _to_llm_message(row: dict[str, Any]) -> dict[str, Any] | None:
|
||||
|
||||
+109
-31
@@ -5,7 +5,7 @@ import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from voidbot.agent import AgentRuntime
|
||||
from voidbot.config import AppConfig
|
||||
from voidbot.config import AppConfig, ProviderConfig
|
||||
from voidbot.context import ContextBuilder
|
||||
from voidbot.gateway.messages import InboundMessageContext
|
||||
from voidbot.models import LLMResponse, ToolCall
|
||||
@@ -14,9 +14,9 @@ from voidbot.tools import build_default_tool_registry
|
||||
|
||||
|
||||
class FakeProvider:
|
||||
def __init__(self) -> None:
|
||||
def __init__(self, model_name: str) -> None:
|
||||
self.calls = 0
|
||||
self.model_name = "fake-model"
|
||||
self.model_name = model_name
|
||||
|
||||
def chat(
|
||||
self, messages: list[dict], tools: list[dict] | None = None
|
||||
@@ -29,27 +29,73 @@ class FakeProvider:
|
||||
ToolCall(id="tool-1", name="list_dir", arguments={"path": "."})
|
||||
],
|
||||
)
|
||||
return LLMResponse(content="I checked the workspace and finished.")
|
||||
return LLMResponse(content=f"I checked the workspace with {self.model_name}.")
|
||||
|
||||
|
||||
class FakeProviderManager:
|
||||
def __init__(self) -> None:
|
||||
self.profiles = {
|
||||
"1": ProviderConfig(
|
||||
id="1",
|
||||
preset="openai_chatgpt",
|
||||
api_key="key-1",
|
||||
model="model-one",
|
||||
label="Model One",
|
||||
),
|
||||
"2": ProviderConfig(
|
||||
id="2",
|
||||
preset="zhipu_coding_plan",
|
||||
api_key="key-2",
|
||||
model="model-two",
|
||||
label="Model Two",
|
||||
),
|
||||
}
|
||||
|
||||
def list_profiles(self) -> list[ProviderConfig]:
|
||||
return [self.profiles["1"], self.profiles["2"]]
|
||||
|
||||
def get_profile(self, provider_id: str | None = None) -> ProviderConfig:
|
||||
key = provider_id or "1"
|
||||
if key not in self.profiles:
|
||||
raise ValueError(f"unknown provider id '{key}', expected one of: 1, 2")
|
||||
return self.profiles[key]
|
||||
|
||||
def describe(self, provider_id: str | None = None) -> dict[str, str]:
|
||||
profile = self.get_profile(provider_id)
|
||||
return {
|
||||
"id": profile.id,
|
||||
"preset": profile.preset,
|
||||
"label": profile.label or profile.preset,
|
||||
"model": profile.model or "(default)",
|
||||
}
|
||||
|
||||
def build(self, provider_id: str | None = None) -> FakeProvider:
|
||||
profile = self.get_profile(provider_id)
|
||||
return FakeProvider(profile.model or "(default)")
|
||||
|
||||
|
||||
class AgentRuntimeTests(unittest.TestCase):
|
||||
def _make_runtime(self, workspace: Path) -> AgentRuntime:
|
||||
config = AppConfig(
|
||||
api_key="test-key",
|
||||
workspace=workspace,
|
||||
database_path=workspace / ".voidbot/voidbot.db",
|
||||
default_provider="1",
|
||||
max_iterations=4,
|
||||
)
|
||||
return AgentRuntime(
|
||||
config=config,
|
||||
providers=FakeProviderManager(),
|
||||
session=SessionStore(config.storage_path),
|
||||
tools=build_default_tool_registry(workspace),
|
||||
context_builder=ContextBuilder(config),
|
||||
)
|
||||
|
||||
def test_run_turn_executes_tool_loop(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
workspace = Path(temp_dir)
|
||||
(workspace / "hello.txt").write_text("hello", encoding="utf-8")
|
||||
config = AppConfig(
|
||||
api_key="test-key",
|
||||
workspace=workspace,
|
||||
session_file=workspace / ".voidbot/session.jsonl",
|
||||
max_iterations=4,
|
||||
)
|
||||
runtime = AgentRuntime(
|
||||
config=config,
|
||||
provider=FakeProvider(),
|
||||
session=SessionStore(config.session_file),
|
||||
tools=build_default_tool_registry(workspace),
|
||||
context_builder=ContextBuilder(config),
|
||||
)
|
||||
runtime = self._make_runtime(workspace)
|
||||
|
||||
inbound = InboundMessageContext(
|
||||
session_id="main",
|
||||
@@ -58,7 +104,9 @@ class AgentRuntimeTests(unittest.TestCase):
|
||||
)
|
||||
result = runtime.run_turn(inbound)
|
||||
|
||||
self.assertEqual(result.reply, "I checked the workspace and finished.")
|
||||
self.assertEqual(result.reply, "I checked the workspace with model-one.")
|
||||
self.assertEqual(result.provider_id, "1")
|
||||
self.assertEqual(result.model_name, "model-one")
|
||||
self.assertEqual(len(result.tool_events), 1)
|
||||
self.assertEqual(result.tool_events[0]["tool_name"], "list_dir")
|
||||
history = runtime.session.load_history(limit=10, session_id="main")
|
||||
@@ -68,21 +116,11 @@ class AgentRuntimeTests(unittest.TestCase):
|
||||
def test_session_history_is_isolated_by_session_id(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
workspace = Path(temp_dir)
|
||||
config = AppConfig(
|
||||
api_key="test-key",
|
||||
workspace=workspace,
|
||||
session_file=workspace / ".voidbot/session.jsonl",
|
||||
)
|
||||
runtime = AgentRuntime(
|
||||
config=config,
|
||||
provider=FakeProvider(),
|
||||
session=SessionStore(config.session_file),
|
||||
tools=build_default_tool_registry(workspace),
|
||||
context_builder=ContextBuilder(config),
|
||||
)
|
||||
runtime = self._make_runtime(workspace)
|
||||
|
||||
runtime.session.append(
|
||||
{"role": "user", "content": "from main"}, session_id="main"
|
||||
{"role": "user", "content": "from main"},
|
||||
session_id="main",
|
||||
)
|
||||
runtime.session.append(
|
||||
{"role": "user", "content": "from feishu"},
|
||||
@@ -98,6 +136,46 @@ class AgentRuntimeTests(unittest.TestCase):
|
||||
self.assertEqual(main_history[0]["content"], "from main")
|
||||
self.assertEqual(feishu_history[0]["content"], "from feishu")
|
||||
|
||||
def test_models_command_lists_available_providers(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
runtime = self._make_runtime(Path(temp_dir))
|
||||
inbound = InboundMessageContext(
|
||||
session_id="main",
|
||||
raw_body="/models",
|
||||
body_for_agent="/models",
|
||||
)
|
||||
|
||||
result = runtime.run_turn(inbound)
|
||||
|
||||
self.assertIn("可用模型列表", result.reply)
|
||||
self.assertIn("1. Model One", result.reply)
|
||||
self.assertIn("2. Model Two", result.reply)
|
||||
self.assertEqual(result.provider_id, "1")
|
||||
|
||||
def test_use_command_switches_provider_for_session(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
runtime = self._make_runtime(Path(temp_dir))
|
||||
switch = InboundMessageContext(
|
||||
session_id="main",
|
||||
raw_body="/use 2",
|
||||
body_for_agent="/use 2",
|
||||
)
|
||||
runtime.run_turn(switch)
|
||||
|
||||
followup = InboundMessageContext(
|
||||
session_id="main",
|
||||
raw_body="continue",
|
||||
body_for_agent="continue",
|
||||
)
|
||||
result = runtime.run_turn(followup)
|
||||
state = runtime.session.get_session_state("main")
|
||||
|
||||
self.assertIsNotNone(state)
|
||||
self.assertEqual(state.provider_id, "2")
|
||||
self.assertEqual(result.provider_id, "2")
|
||||
self.assertEqual(result.model_name, "model-two")
|
||||
self.assertIn("model-two", result.reply)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -62,9 +62,16 @@ class ChannelManagerTests(unittest.TestCase):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
config = AppConfig.from_mapping(
|
||||
{
|
||||
"default_provider": "1",
|
||||
"providers": [
|
||||
{
|
||||
"id": "1",
|
||||
"preset": "openai_chatgpt",
|
||||
"api_key": "test-key",
|
||||
}
|
||||
],
|
||||
"workspace": temp_dir,
|
||||
"session_file": str(Path(temp_dir) / ".voidbot/session.jsonl"),
|
||||
"database_path": str(Path(temp_dir) / ".voidbot/voidbot.db"),
|
||||
"channels": {
|
||||
"feishu": {
|
||||
"enabled": True,
|
||||
|
||||
+56
-20
@@ -9,7 +9,7 @@ from unittest.mock import patch
|
||||
|
||||
from voidbot.config import (
|
||||
get_default_config_path,
|
||||
get_default_session_path,
|
||||
get_default_database_path,
|
||||
load_config,
|
||||
sync_default_config,
|
||||
)
|
||||
@@ -23,9 +23,21 @@ class ConfigLoadingTests(unittest.TestCase):
|
||||
config_path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"provider": "zhipu_coding_plan",
|
||||
"api_key": "test-key",
|
||||
"default_provider": "2",
|
||||
"providers": [
|
||||
{
|
||||
"id": "1",
|
||||
"preset": "zhipu_coding_plan",
|
||||
"api_key": "z-key",
|
||||
"model": "glm-4.7",
|
||||
},
|
||||
{
|
||||
"id": "2",
|
||||
"preset": "openai_chatgpt",
|
||||
"api_key": "o-key",
|
||||
"model": "gpt-4.1",
|
||||
},
|
||||
],
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
@@ -38,28 +50,35 @@ class ConfigLoadingTests(unittest.TestCase):
|
||||
finally:
|
||||
os.chdir(current)
|
||||
|
||||
self.assertEqual(config.provider, "zhipu_coding_plan")
|
||||
self.assertEqual(config.api_key, "test-key")
|
||||
self.assertEqual(config.model, "glm-4.7")
|
||||
self.assertEqual(config.default_provider, "2")
|
||||
self.assertEqual(config.get_provider_config().api_key, "o-key")
|
||||
self.assertEqual(config.get_provider_config().model, "gpt-4.1")
|
||||
|
||||
def test_loads_user_home_config_when_current_directory_has_no_config(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
home_path = Path(temp_dir)
|
||||
voidbot_home = home_path / ".voidbot"
|
||||
voidbot_home = Path(temp_dir) / ".voidbot"
|
||||
voidbot_home.mkdir(parents=True, exist_ok=True)
|
||||
user_config_path = voidbot_home / "config.json"
|
||||
user_config_path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"provider": "openai_chatgpt",
|
||||
"default_provider": "1",
|
||||
"providers": [
|
||||
{
|
||||
"id": "1",
|
||||
"preset": "openai_chatgpt",
|
||||
"api_key": "home-key",
|
||||
"model": "gpt-4.1",
|
||||
}
|
||||
],
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
with patch.dict(
|
||||
os.environ, {"VOIDBOT_HOME": str(voidbot_home)}, clear=False
|
||||
os.environ,
|
||||
{"VOIDBOT_HOME": str(voidbot_home)},
|
||||
clear=False,
|
||||
):
|
||||
with tempfile.TemporaryDirectory() as cwd_dir:
|
||||
current = os.getcwd()
|
||||
@@ -69,8 +88,8 @@ class ConfigLoadingTests(unittest.TestCase):
|
||||
finally:
|
||||
os.chdir(current)
|
||||
|
||||
self.assertEqual(config.api_key, "home-key")
|
||||
self.assertEqual(config.model, "gpt-4.1")
|
||||
self.assertEqual(config.get_provider_config().api_key, "home-key")
|
||||
self.assertEqual(config.get_provider_config().model, "gpt-4.1")
|
||||
|
||||
def test_loads_nested_channel_settings(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
@@ -78,7 +97,14 @@ class ConfigLoadingTests(unittest.TestCase):
|
||||
config_path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"default_provider": "1",
|
||||
"providers": [
|
||||
{
|
||||
"id": "1",
|
||||
"preset": "openai_chatgpt",
|
||||
"api_key": "test-key",
|
||||
}
|
||||
],
|
||||
"channels": {
|
||||
"feishu": {
|
||||
"enabled": True,
|
||||
@@ -104,16 +130,18 @@ class ConfigLoadingTests(unittest.TestCase):
|
||||
self.assertTrue(config.channels.qq.enabled)
|
||||
self.assertEqual(config.channels.qq.secret, "qq_s")
|
||||
|
||||
def test_default_session_path_comes_from_user_voidbot_home(self) -> None:
|
||||
def test_default_database_path_comes_from_user_voidbot_home(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
voidbot_home = Path(temp_dir) / ".voidbot"
|
||||
with patch.dict(
|
||||
os.environ, {"VOIDBOT_HOME": str(voidbot_home)}, clear=False
|
||||
os.environ,
|
||||
{"VOIDBOT_HOME": str(voidbot_home)},
|
||||
clear=False,
|
||||
):
|
||||
session_path = get_default_session_path()
|
||||
database_path = get_default_database_path()
|
||||
config_path = get_default_config_path()
|
||||
|
||||
self.assertEqual(session_path, voidbot_home / "session.jsonl")
|
||||
self.assertEqual(database_path, voidbot_home / "voidbot.db")
|
||||
self.assertEqual(config_path, voidbot_home / "config.json")
|
||||
|
||||
def test_sync_default_config_adds_missing_fields_without_overwriting_existing_ones(
|
||||
@@ -126,7 +154,13 @@ class ConfigLoadingTests(unittest.TestCase):
|
||||
config_path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"providers": [
|
||||
{
|
||||
"id": "9",
|
||||
"preset": "custom_openai_compatible",
|
||||
"api_key": "custom-key",
|
||||
}
|
||||
],
|
||||
"channels": {
|
||||
"feishu": {
|
||||
"enabled": True,
|
||||
@@ -140,7 +174,9 @@ class ConfigLoadingTests(unittest.TestCase):
|
||||
encoding="utf-8",
|
||||
)
|
||||
with patch.dict(
|
||||
os.environ, {"VOIDBOT_HOME": str(voidbot_home)}, clear=False
|
||||
os.environ,
|
||||
{"VOIDBOT_HOME": str(voidbot_home)},
|
||||
clear=False,
|
||||
):
|
||||
synced_path, created, added_paths = sync_default_config()
|
||||
|
||||
@@ -148,9 +184,9 @@ class ConfigLoadingTests(unittest.TestCase):
|
||||
|
||||
self.assertEqual(synced_path, config_path)
|
||||
self.assertFalse(created)
|
||||
self.assertIn("provider", added_paths)
|
||||
self.assertIn("channels.qq", added_paths)
|
||||
self.assertEqual(merged["api_key"], "custom-key")
|
||||
self.assertIn("default_provider", added_paths)
|
||||
self.assertIn("database_path", added_paths)
|
||||
self.assertEqual(merged["providers"][0]["id"], "9")
|
||||
self.assertTrue(merged["channels"]["feishu"]["enabled"])
|
||||
self.assertTrue(merged["custom_field"]["keep_me"])
|
||||
|
||||
|
||||
+70
-11
@@ -1,12 +1,22 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from voidbot.config import AppConfig
|
||||
from voidbot.gateway.cli import _run_one_turn, build_parser, run_config_sync_command
|
||||
from voidbot.gateway.cli import (
|
||||
_run_one_turn,
|
||||
build_parser,
|
||||
run_config_open_command,
|
||||
run_config_path_command,
|
||||
run_config_sync_command,
|
||||
run_data_dump_command,
|
||||
)
|
||||
from voidbot.gateway.messages import InboundMessageContext
|
||||
from voidbot.gateway.server import GatewayApplication
|
||||
from voidbot.models import RunTurnResult
|
||||
@@ -21,6 +31,9 @@ class FakeRuntime:
|
||||
reply=f"echo:{inbound.body_for_agent}",
|
||||
iterations=1,
|
||||
tool_events=[{"tool_name": "fake_tool", "arguments": {}, "result": "ok"}],
|
||||
provider_id="1",
|
||||
provider_label="Model One",
|
||||
model_name="model-one",
|
||||
)
|
||||
|
||||
|
||||
@@ -41,6 +54,7 @@ class GatewayTests(unittest.TestCase):
|
||||
|
||||
self.assertTrue(result["ok"])
|
||||
self.assertEqual(result["reply"], "echo:hello gateway")
|
||||
self.assertEqual(result["provider_id"], "1")
|
||||
self.assertEqual(result["tool_events"][0]["tool_name"], "fake_tool")
|
||||
|
||||
def test_gateway_mode_calls_gateway_client(self) -> None:
|
||||
@@ -53,6 +67,9 @@ class GatewayTests(unittest.TestCase):
|
||||
"reply": "echo:hello gateway",
|
||||
"iterations": 1,
|
||||
"tool_events": [],
|
||||
"provider_id": "1",
|
||||
"provider_label": "Model One",
|
||||
"model_name": "model-one",
|
||||
}
|
||||
result = _run_one_turn(
|
||||
message="hello gateway",
|
||||
@@ -63,7 +80,7 @@ class GatewayTests(unittest.TestCase):
|
||||
|
||||
self.assertTrue(result["ok"])
|
||||
self.assertEqual(result["mode"], "gateway")
|
||||
self.assertEqual(result["reply"], "echo:hello gateway")
|
||||
self.assertEqual(result["provider_id"], "1")
|
||||
run_agent.assert_called_once()
|
||||
|
||||
def test_auto_mode_falls_back_to_local(self) -> None:
|
||||
@@ -87,9 +104,8 @@ class GatewayTests(unittest.TestCase):
|
||||
|
||||
self.assertTrue(result["ok"])
|
||||
self.assertEqual(result["mode"], "local")
|
||||
self.assertEqual(result["reply"], "echo:hello local")
|
||||
self.assertEqual(result["provider_id"], "1")
|
||||
self.assertEqual(result["meta"]["fallback"], "local")
|
||||
self.assertIn("gateway down", result["meta"]["gateway_error"])
|
||||
|
||||
def test_cli_via_can_come_from_config(self) -> None:
|
||||
config = AppConfig(api_key="test-key", cli_via="gateway")
|
||||
@@ -102,6 +118,9 @@ class GatewayTests(unittest.TestCase):
|
||||
"reply": "echo:config gateway",
|
||||
"iterations": 1,
|
||||
"tool_events": [],
|
||||
"provider_id": "1",
|
||||
"provider_label": "Model One",
|
||||
"model_name": "model-one",
|
||||
}
|
||||
with patch("voidbot.gateway.cli.load_config", return_value=config):
|
||||
from voidbot.gateway.cli import run_agent_command
|
||||
@@ -117,21 +136,27 @@ class GatewayTests(unittest.TestCase):
|
||||
|
||||
run_via_gateway.assert_called_once()
|
||||
|
||||
def test_config_sync_command_is_exposed_in_parser(self) -> None:
|
||||
def test_config_commands_are_exposed_in_parser(self) -> None:
|
||||
parser = build_parser()
|
||||
args = parser.parse_args(["config", "sync"])
|
||||
|
||||
self.assertEqual(args.command, "config")
|
||||
self.assertEqual(args.config_command, "sync")
|
||||
sync_args = parser.parse_args(["config", "sync"])
|
||||
path_args = parser.parse_args(["config", "path"])
|
||||
open_args = parser.parse_args(["config", "open"])
|
||||
dump_args = parser.parse_args(["data", "dump"])
|
||||
|
||||
self.assertEqual(sync_args.config_command, "sync")
|
||||
self.assertEqual(path_args.config_command, "path")
|
||||
self.assertEqual(open_args.config_command, "open")
|
||||
self.assertEqual(dump_args.data_command, "dump")
|
||||
|
||||
def test_config_sync_command_prints_added_fields(self) -> None:
|
||||
buffer = io.StringIO()
|
||||
with patch(
|
||||
"voidbot.gateway.cli.sync_default_config",
|
||||
return_value=(
|
||||
AppConfig().session_file.parent / "config.json",
|
||||
Path("/tmp/.voidbot/config.json"),
|
||||
False,
|
||||
["provider"],
|
||||
["default_provider"],
|
||||
),
|
||||
):
|
||||
with patch("sys.stdout", buffer):
|
||||
@@ -139,7 +164,41 @@ class GatewayTests(unittest.TestCase):
|
||||
|
||||
output = buffer.getvalue()
|
||||
self.assertIn("VoidBot config updated", output)
|
||||
self.assertIn("provider", output)
|
||||
self.assertIn("default_provider", output)
|
||||
|
||||
def test_config_path_command_prints_default_path(self) -> None:
|
||||
buffer = io.StringIO()
|
||||
with patch("sys.stdout", buffer):
|
||||
run_config_path_command()
|
||||
|
||||
self.assertIn(".voidbot/config.json", buffer.getvalue())
|
||||
|
||||
def test_config_open_command_opens_synced_path(self) -> None:
|
||||
with patch(
|
||||
"voidbot.gateway.cli.sync_default_config",
|
||||
return_value=(Path("/tmp/.voidbot/config.json"), True, []),
|
||||
):
|
||||
with patch("voidbot.gateway.cli._open_path") as open_path:
|
||||
run_config_open_command()
|
||||
|
||||
open_path.assert_called_once_with(Path("/tmp/.voidbot/config.json"))
|
||||
|
||||
def test_data_dump_command_prints_sqlite_data(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
config = AppConfig(database_path=Path(temp_dir) / "voidbot.db")
|
||||
with patch("voidbot.gateway.cli.load_config", return_value=config):
|
||||
buffer = io.StringIO()
|
||||
with patch("sys.stdout", buffer):
|
||||
run_data_dump_command(
|
||||
config_path=None,
|
||||
session_id=None,
|
||||
limit=None,
|
||||
)
|
||||
|
||||
payload = json.loads(buffer.getvalue())
|
||||
self.assertIn("database_path", payload)
|
||||
self.assertIn("sessions", payload)
|
||||
self.assertIn("messages", payload)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user