### Verify CoPaw Installation with cURL Source: https://copaw.agentscope.io/docs/quickstart This snippet shows how to verify the CoPaw installation by sending a POST request to the /api/agent/process endpoint using cURL. It includes a sample JSON payload for a single-turn user interaction and demonstrates how to enable SSE streaming. The same session_id can be used for multi-turn conversations. ```bash curl -N -X POST "http://localhost:8088/api/agent/process" \ -H "Content-Type: application/json" \ -d '{"input":[{"role":"user","content":[{"type":"text","text":"你好"}]}],"session_id":"session123"}' ``` -------------------------------- ### Start CoPaw Application Source: https://copaw.agentscope.io/docs/cli Starts the CoPaw service, which is essential for all runtime functionalities like channels, scheduled tasks, and the console. It supports custom host and port binding, automatic reloading for development, multi-worker mode, and log level configuration. ```bash copaw app # Default 127.0.0.1:8088 copaw app --host 0.0.0.0 --port 9090 # Custom address copaw app --reload # Auto-reload on code changes (for development) copaw app --workers 4 # Multi-worker mode copaw app --log-level debug # Verbose logging ``` -------------------------------- ### Initialize CoPaw CLI Source: https://copaw.agentscope.io/docs/cli Initializes the CoPaw configuration interactively or with defaults. It guides through setting up heartbeats, tool details, language, channels, LLM providers, skills, and environment variables. The `--force` option overwrites existing configurations. ```bash copaw init # Interactive initialization (recommended for new users) copaw init --defaults # Non-interactive, uses defaults (suitable for scripting) copaw init --force # Overwrite existing configuration file ``` -------------------------------- ### Download and Manage Ollama Models Source: https://copaw.agentscope.io/docs/cli Integrates with Ollama to run models locally. Users can pull models from Ollama, list available Ollama models, and remove them. This functionality requires Ollama to be installed and running separately. The `copaw[ollama]` extra needs to be installed. ```bash # Download Ollama model copaw models ollama-pull mistral:7b copaw models ollama-pull qwen2.5:3b # View Ollama models copaw models ollama-list # Delete Ollama model copaw models ollama-remove mistral:7b copaw models ollama-remove qwen2.5:3b --yes # Skip confirmation # Use in configuration flow (auto-detects Ollama models) copaw models config # Select Ollama -> Choose from model list copaw models set-llm # Switch to another Ollama model ``` -------------------------------- ### POST /new Source: https://copaw.agentscope.io/docs/commands Clears the current conversation context and starts a new session while saving history to long-term memory. ```APIDOC ## POST /new ### Description Immediately clears the current context and starts a fresh conversation. History is persisted to long-term memory. ### Method POST ### Endpoint /new ### Response #### Success Response (200) - **Status** (string) - Confirmation message #### Response Example { "Status": "New Conversation Started!" } ``` -------------------------------- ### Define and Initialize a Custom Channel (Python) Source: https://copaw.agentscope.io/docs/channels This Python code defines a custom channel `MyChannel` inheriting from `BaseChannel`. It includes initialization logic, configuration loading from various sources (`from_config`, `from_env`), and placeholder methods for starting and stopping the channel. ```python from agentscope_runtime.engine.schemas.agent_schemas import TextContent, ContentType from copaw.app.channels.base import BaseChannel from copaw.app.channels.schema import ChannelType class MyChannel(BaseChannel): channel: ChannelType = "my_channel" def __init__(self, process, enabled=True, bot_prefix="", **kwargs): super().__init__(process, on_reply_sent=kwargs.get("on_reply_sent")) self.enabled = enabled self.bot_prefix = bot_prefix @classmethod def from_config(cls, process, config, on_reply_sent=None, show_tool_details=True): return cls(process=process, enabled=getattr(config, "enabled", True), bot_prefix=getattr(config, "bot_prefix", ""), on_reply_sent=on_reply_sent) @classmethod def from_env(cls, process, on_reply_sent=None): return cls(process=process, on_reply_sent=on_reply_sent) def build_agent_request_from_native(self, native_payload): payload = native_payload if isinstance(native_payload, dict) else {} channel_id = payload.get("channel_id") or self.channel sender_id = payload.get("sender_id") or "" meta = payload.get("meta") or {} session_id = self.resolve_session_id(sender_id, meta) text = payload.get("text", "") content_parts = [TextContent(type=ContentType.TEXT, text=text)] request = self.build_agent_request_from_user_content( channel_id=channel_id, sender_id=sender_id, session_id=session_id, content_parts=content_parts, channel_meta=meta, ) request.channel_meta = meta return request async def start(self): pass async def stop(self): pass async def send(self, to_handle, text, meta=None): # 调用你的 HTTP API 等发送 pass ``` -------------------------------- ### Download and Manage Local Models (llama.cpp/MLX) Source: https://copaw.agentscope.io/docs/cli Allows downloading and managing local models using llama.cpp or MLX backends. Users can download models from Hugging Face or ModelScope, specify the backend and source, view downloaded models, and remove them. Requires installing the respective backend (`copaw[llamacpp]` or `copaw[mlx]`). ```bash # Download model (auto-selects Q4_K_M GGUF) copaw models download Qwen/Qwen3-4B-GGUF # Download MLX model copaw models download Qwen/Qwen3-4B --backend mlx # Download from ModelScope copaw models download Qwen/Qwen2-0.5B-Instruct-GGUF --source modelscope # View downloaded models copaw models local copaw models local --backend mlx # Delete downloaded model copaw models remove-local copaw models remove-local --yes # Skip confirmation ``` -------------------------------- ### Channel Integration Guide Source: https://copaw.agentscope.io/docs/channels Information on how to extend the platform by integrating new communication channels. ```APIDOC ## Extending Channels ### Description This section details how to integrate new communication platforms by extending the `BaseChannel` class. It also explains the data flow and queue management within the `ChannelManager`. ### Data Flow and Queues The `ChannelManager` maintains a queue for each enabled channel. When a message is received, the channel enqueues the payload using `self._enqueue(payload)`. The manager then processes these messages in its consumption loop by calling `channel.consume_one(payload)`. The default `consume_one` implementation in the base class handles the conversion of the payload to an `AgentRequest`, processes it, sends the reply, and handles errors. Most new channels only need to implement the message reception and reply sending logic. ### Abstract Methods to Implement (Subclasses) | Method | Description | | :----------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------- | | `build_agent_request_from_native(self, native_payload)` | Converts the native channel payload into an `AgentRequest` object, setting `request.channel_meta` for sending replies. | | `from_env` / `from_config` | Constructs the channel instance from environment variables or configuration settings. | | `async start()` / `async stop()` | Handles the lifecycle of the channel, including establishing connections and performing cleanup. | | `async send(self, to_handle, text, meta=None)` | Sends a text message, potentially with attachments, to the specified recipient handle. | ### Base Class Provided Capabilities - **Consumption Process**: Includes methods like `_payload_to_request`, `get_to_handle_from_request`, `get_on_reply_sent_args`, `_before_consume_process`, `_on_consume_error`, and an optional `refresh_webhook_or_token`. - **Utilities**: Helper methods such as `resolve_session_id`, `build_agent_request_from_user_content`, `_message_to_content_parts`, `send_message_content`, `send_content_parts`, and `to_handle_from_target`. ### Overriding Methods - Override `consume_one` for custom consumption logic (e.g., console logging, deduplication). - Override `get_to_handle_from_request` and `get_on_reply_sent_args` for custom reply targeting or callback parameters. ### Example: Minimal Text-Only Channel For channels that only handle text and use the manager's queue, the default `consume_one` implementation is sufficient, and no explicit implementation is needed. ``` -------------------------------- ### GET /history Source: https://copaw.agentscope.io/docs/commands Displays all uncompressed messages in the current conversation and provides detailed context usage statistics. ```APIDOC ## GET /history ### Description Displays the current conversation history, including total messages, token usage, and context percentage. ### Method GET ### Endpoint /history ### Response #### Success Response (200) - **Total messages** (integer) - Count of messages - **Estimated tokens** (integer) - Total token count - **Context usage** (float) - Percentage of context window used #### Response Example { "Total messages": 3, "Estimated tokens": 1256, "Context usage": "0.98%" } ``` -------------------------------- ### Matrix Channel Configuration in config.json Source: https://copaw.agentscope.io/docs/channels Example of Matrix channel configuration within the `config.json` file, specifying enabled status, bot prefix, homeserver, user ID, and access token. ```json "matrix": { "enabled": true, "bot_prefix": "[BOT]", "homeserver": "https://matrix.org", "user_id": "@mybot:matrix.org", "access_token": "syt_..." } ``` -------------------------------- ### Matrix Bot Login API Request Source: https://copaw.agentscope.io/docs/channels Example using curl to perform a Matrix bot login via the Client-Server API to obtain an access token. ```bash curl -X POST "https://matrix.org/_matrix/client/v3/login" \ -H "Content-Type: application/json" \ -d '{"type":"m.login.password","user":"@yourbot:matrix.org","password":"yourpassword"}' ``` -------------------------------- ### Manage CoPaw Daemon Source: https://copaw.agentscope.io/docs/cli Provides commands to check the status, version, and logs of the CoPaw daemon without starting a full conversation. It supports managing the status, restarting, reloading configuration, and viewing version information and recent logs for a specific agent ID. ```bash copaw daemon status # Default agent status copaw daemon status --agent-id abc123 # Specific agent status copaw daemon version copaw daemon logs -n 50 ``` -------------------------------- ### Docker Deployment for CoPaw Agents Source: https://copaw.agentscope.io/docs/quickstart This snippet demonstrates how to pull the CoPaw Docker image from Docker Hub and run it. It configures port mapping, volume mounts for data and secrets, and environment variables for API keys. The service is accessible via http://127.0.0.1:8088. ```bash docker pull agentscope/copaw:latest docker run -p 127.0.0.1:8088:8088 \ -v copaw-data:/app/working \ -v copaw-secrets:/app/working.secret \ agentscope/copaw:latest ``` -------------------------------- ### GET /message Source: https://copaw.agentscope.io/docs/commands Retrieves the detailed content of a specific message in the conversation history by its index. ```APIDOC ## GET /message ### Description View the detailed content of a specific message using its index. ### Method GET ### Endpoint /message ### Parameters #### Path Parameters - **index** (integer) - Required - The 1-based index of the message to retrieve. ### Response #### Success Response (200) - **Timestamp** (string) - Message creation time - **Role** (string) - Sender role (user/assistant) - **Content** (string) - The message body #### Response Example { "Timestamp": "2024-01-15 10:30:00", "Role": "user", "Content": "帮我写一个 Python 函数" } ``` -------------------------------- ### Agent Prompt Files Overview Source: https://copaw.agentscope.io/docs/config Provides a summary of the Agent Prompt files, their core responsibilities, read/write attributes, and key content. ```APIDOC ## Agent Prompt Files Overview This section summarizes the Agent Prompt files, inspired by OpenClaw. | File | Core Responsibility | Read/Write Attributes | Key Content | |----------------|------------------------------------------|--------------------------------|-----------------------------------------------------------------------------------------------------------| | **SOUL.md** | Agent's values and code of conduct | Read-only (pre-defined) | Be helpful, have opinions, self-solve first, respect privacy. | | **PROFILE.md** | Agent's identity and user profile | Read/Write (auto-generated) | Agent: name, role, style, capabilities; User: name, preferences, background. | | **BOOTSTRAP.md**| Initial onboarding process for new Agents | One-time (self-deletes after use) | Self-introduction, understand user, write PROFILE.md, read SOUL.md, self-delete. | | **AGENTS.md** | Agent's complete operational guidelines | Read-only (core reference) | Memory system rules, security, tool usage, heartbeat logic, operational boundaries. | | **MEMORY.md** | Stores tool settings and lessons learned | Read/Write (auto-maintained) | SSH config, local environment paths/versions, user preferences. | | **HEARTBEAT.md**| Defines Agent's background inspection tasks | Read/Write (empty = skip) | List of tasks to execute periodically. | ### File Collaboration Relationship ``` BOOTSTRAP.md (🐣 One-time) ├── Generates → PROFILE.md (🪪 Who am I) ├── Guides reading → SOUL.md (🫀 My soul) └── Self-deletes after completion ✂️ AGENTS.md (📋 Daily guidelines) ├── Read/Write → MEMORY.md (🧠 Long-term memory) ├── References → HEARTBEAT.md (💓 Periodic inspection) └── References → PROFILE.md (🪪 Understand the user) ``` **In essence:** SOUL defines personality, PROFILE remembers relationships, BOOTSTRAP handles birth, AGENTS dictate behavior, MEMORY accumulates experience, and HEARTBEAT maintains vigilance. ``` -------------------------------- ### Environment Variables Management Source: https://copaw.agentscope.io/docs/config Explains how to manage environment variables required by certain tools, such as API keys for network search. ```APIDOC ## Environment Variables Some tools require additional API keys (e.g., `TAVILY_API_KEY` for web search). You can manage these through three methods: 1. **`copaw init`**: During initialization, you will be prompted with "Configure environment variables?" 2. **Console UI**: Edit them in the settings page. 3. **API**: Use `GET/PUT/DELETE /envs` endpoints. Configured variables are automatically loaded on application startup and are accessible via `os.environ` by all tools and subprocesses. **Note:** The validity of environment variable values (e.g., third-party API keys) is the user's responsibility. CoPaw only handles storage and injection, not validation. ``` -------------------------------- ### 在 Linux/macOS 中临时更改 CoPaw 工作目录 Source: https://copaw.agentscope.io/docs/config 演示了如何使用 `export` 命令设置 `COPAW_WORKING_DIR` 环境变量,从而临时更改 CoPaw 的工作目录。这会影响 `config`、`HEARTBEAT`、`jobs`、`memory` 等文件的读写位置。 ```bash export COPAW_WORKING_DIR=/home/me/my_copaw copaw app ``` -------------------------------- ### Configure Heartbeat Settings in config.json Source: https://copaw.agentscope.io/docs/heartbeat The config.json file manages the heartbeat execution parameters, including the frequency (every), the output destination (target), and the optional active hours window. ```json "agents": { "defaults": { "heartbeat": { "every": "30m", "target": "main" } } } ``` ```json "agents": { "defaults": { "heartbeat": { "every": "1h", "target": "last", "activeHours": { "start": "08:00", "end": "22:00" } } } } ``` -------------------------------- ### Define Heartbeat Content in HEARTBEAT.md Source: https://copaw.agentscope.io/docs/heartbeat The HEARTBEAT.md file contains the text or Markdown content that the CoPAW agent processes during each heartbeat interval. This file acts as the user input for the automated agent interaction. ```markdown # Heartbeat checklist - 扫描收件箱紧急邮件 - 查看未来 2h 的日历 - 检查待办是否卡住 - 若安静超过 8h,轻量 check-in ``` -------------------------------- ### POST /compact Source: https://copaw.agentscope.io/docs/commands Manually triggers conversation compression to condense messages into a summary and save to long-term memory. ```APIDOC ## POST /compact ### Description Manually triggers conversation compression, condensing all current messages into a summary. ### Method POST ### Endpoint /compact ### Response #### Success Response (200) - **Messages compacted** (integer) - Number of messages processed - **Compressed Summary** (string) - The resulting summary text #### Response Example { "Messages compacted": 12, "Compressed Summary": "用户请求帮助构建用户认证系统..." } ``` -------------------------------- ### Configure LLM Models Source: https://copaw.agentscope.io/docs/cli Manages Language Model (LLM) providers and active models. This includes listing providers, configuring API keys interactively or individually, setting the active model, and downloading/managing local models via llama.cpp or MLX backends. ```bash copaw models list # View current status copaw models config # Full interactive configuration copaw models config-key modelscope # Configure only ModelScope API Key copaw models config-key dashscope # Configure only DashScope API Key copaw models config-key custom # Configure custom provider (Base URL + Key) copaw models set-llm # Switch model only ``` -------------------------------- ### CoPaw 全局 config.json 示例 Source: https://copaw.agentscope.io/docs/config 展示了 CoPaw 全局配置文件 `config.json` 的结构。该文件包含智能体配置(包括活动智能体和配置文件)、API 连接信息以及是否显示工具详情的选项。 ```json { "agents": { "active_agent": "default", "profiles": { "default": { "id": "default", "name": "默认智能体", "description": "默认工作区智能体", "enabled": true }, "abc123": { "id": "abc123", "name": "代码助手", "description": "专注代码审查和开发", "enabled": true } } }, "last_api": { "host": "127.0.0.1", "port": 7860 }, "show_tool_details": true } ``` -------------------------------- ### POST /api/agent/process Source: https://copaw.agentscope.io/docs/quickstart This endpoint allows users to send messages to the agent and receive responses. It supports multi-turn conversations using a session_id and provides SSE (Server-Sent Events) for streaming responses. ```APIDOC ## POST /api/agent/process ### Description Sends a message to the agent and retrieves a response. Supports multi-turn dialogue via session management and streaming output. ### Method POST ### Endpoint /api/agent/process ### Parameters #### Request Body - **input** (array) - Required - A list of message objects containing role and content. - **session_id** (string) - Required - Unique identifier for the conversation session. ### Request Example { "input": [ { "role": "user", "content": [ {"type": "text", "text": "你好"} ] } ], "session_id": "session123" } ### Response #### Success Response (200) - **response** (string) - The agent's generated response content. #### Response Example { "status": "success", "data": "你好!请问有什么我可以帮您的吗?" } ``` -------------------------------- ### Handle Multimodal Content in Agent Request (Python) Source: https://copaw.agentscope.io/docs/channels This Python code extends the `build_agent_request_from_native` method to parse multimodal content, including text, images, videos, audio, and files, from a native payload. It constructs appropriate `agentscope_runtime` content objects for each attachment type. ```python from agentscope_runtime.engine.schemas.agent_schemas import ( TextContent, ImageContent, VideoContent, AudioContent, FileContent, ContentType, ) def build_agent_request_from_native(self, native_payload): payload = native_payload if isinstance(native_payload, dict) else {} channel_id = payload.get("channel_id") or self.channel sender_id = payload.get("sender_id") or "" meta = payload.get("meta") or {} session_id = self.resolve_session_id(sender_id, meta) content_parts = [] if payload.get("text"): content_parts.append(TextContent(type=ContentType.TEXT, text=payload["text"])) for att in payload.get("attachments") or []: t = (att.get("type") or "file").lower() url = att.get("url") or "" if not url: continue if t == "image": content_parts.append(ImageContent(type=ContentType.IMAGE, image_url=url)) elif t == "video": content_parts.append(VideoContent(type=ContentType.VIDEO, video_url=url)) elif t == "audio": content_parts.append(AudioContent(type=ContentType.AUDIO, data=url)) else: content_parts.append(FileContent(type=ContentType.FILE, file_url=url)) if not content_parts: content_parts = [TextContent(type=ContentType.TEXT, text="")] request = self.build_agent_request_from_user_content( channel_id=channel_id, sender_id=sender_id, session_id=session_id, content_parts=content_parts, channel_meta=meta, ) request.channel_meta = meta return request ``` -------------------------------- ### CoPaw 智能体 agent.json 示例 Source: https://copaw.agentscope.io/docs/config 展示了单个智能体的工作区目录下的 `agent.json` 配置文件。该文件包含智能体的 ID、名称、描述、启用状态、频道配置(如 iMessage、Discord、DingTalk、Console)、心跳设置、运行参数、语言和时区等。 ```json { "id": "default", "name": "默认智能体", "description": "默认工作区智能体", "enabled": true, "channels": { "imessage": { "enabled": false, "bot_prefix": "", "db_path": "~/Library/Messages/chat.db", "poll_sec": 1.0 }, "discord": { "enabled": false, "bot_prefix": "", "bot_token": "", "http_proxy": "", "http_proxy_auth": "" }, "dingtalk": { "enabled": false, "bot_prefix": "", "client_id": "", "client_secret": "" }, "console": { "enabled": true, "bot_prefix": "" } }, "heartbeat": { "every": "30m", "target": "main", "activeHours": null }, "running": { "max_iters": 50, "max_input_length": 131072 }, "language": "zh", "installed_md_files_language": "zh", "user_timezone": "Asia/Shanghai", "last_dispatch": null, "show_tool_details": true } ``` -------------------------------- ### Memory Configuration Source: https://copaw.agentscope.io/docs/config Explains CoPaw's persistent memory capabilities, including context compression, Markdown storage, and embedding configuration. ```APIDOC ## Memory CoPaw provides persistent memory across conversations by automatically compressing context and storing key information in Markdown files. ### Memory File Locations | File/Directory | Description | |-----------------------|---------------------------------------------------| | `~/.copaw/MEMORY.md` | Long-term key information (decisions, preferences) | | `~/.copaw/memory/YYYY-MM-DD.md` | Daily logs (notes, runtime context, summaries) | ### Embedding Configuration Memory search relies on vector embeddings for semantic retrieval. The configuration priority is: **Configuration File > Environment Variables > Default Values**. It's recommended to configure embedding settings in `agent.json` under `running.embedding_config`. Environment variables serve as a fallback: | Environment Variable (Fallback) | Description | Default Value | |---------------------------------|-----------------------------|---------------| | `EMBEDDING_API_KEY` | Embedding service API Key | `` | | `EMBEDDING_BASE_URL` | Embedding service URL | `` | | `EMBEDDING_MODEL_NAME` | Embedding model name | `` | Vector search is enabled only if `api_key`, `model_name`, and `base_url` are all non-empty. Refer to the Memory documentation for full configuration details. ``` -------------------------------- ### CoPaw 智能体工作区目录结构示例 Source: https://copaw.agentscope.io/docs/config 展示了 CoPaw 0.1.0 版本开始支持的多智能体工作区目录结构。该结构清晰地组织了全局配置文件、工作区目录以及每个智能体的工作区内容,包括智能体配置、对话历史、任务、技能和记忆等。 ```directory ~/.copaw/ ├── config.json # 全局配置(提供商、环境变量) └── workspaces/ ├── default/ # 默认智能体工作区 │ ├── agent.json # 智能体配置 │ ├── chats.json # 对话历史 │ ├── jobs.json # 定时任务 │ ├── AGENTS.md # 详细工作流程、规则和指南 │ ├── SOUL.md # 核心身份与行为原则 │ ├── active_skills/ # 激活的技能 │ ├── customized_skills/ # 自定义技能 │ └── memory/ # 记忆文件 └── abc123/ # 其他智能体工作区 └── ... ```