chore(skills): 装入 agentscope-skill 知识包(项目本地 .claude/skills)
AgentScope(Python)库开发知识包,对应 long-term premium agentic 轨 (参 saa-agentic-infra-decision);short-term 主线仍走 SAA(Java)。 含 SKILL.md + references(部署/多agent编排) + scripts(查模块签名/PyPI版本)。 仅装项目本地作用域;settings.local.json 与 .claude/worktrees 不入库。 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
37f5eddbdd
commit
7a68530f67
305
.claude/skills/agentscope-skill/SKILL.md
Normal file
305
.claude/skills/agentscope-skill/SKILL.md
Normal file
@ -0,0 +1,305 @@
|
||||
---
|
||||
name: agentscope-skill
|
||||
description: This guide covers the design philosophy, core concepts, and practical usage of the AgentScope framework. Use this skill whenever the user wants to do anything with the AgentScope (Python) library. This includes building agent applications using AgentScope, answering questions about AgentScope, looking for guidance on how to use AgentScope, searching for examples or specific information (functions/classes/modules).
|
||||
version: 0.1.0
|
||||
---
|
||||
|
||||
## Understanding AgentScope
|
||||
### What is AgentScope?
|
||||
AgentScope is a production-ready, enterprise-grade open-source framework for building multi-agent applications with large language models. Its functionalities cover:
|
||||
|
||||
- **Development**: ReAct agent, context compression, short/long-term memory, tool use, human-in-the-loop, multi-agent orchestration, agent hooks, structured output, planning, integration with MCP, agent skill, LLMs API, voice interaction (TTS/Realtime), RAG
|
||||
- **Evaluation**: Evaluate multistep agentic applications with statistical analysis
|
||||
- **Training**: Agentic reinforcement learning
|
||||
- **Deployment**: Session/state management, sandbox, local/serverless/Kubernetes deployment
|
||||
|
||||
### Installation
|
||||
```bash
|
||||
pip install agentscope
|
||||
# or
|
||||
uv pip install agentscope
|
||||
```
|
||||
|
||||
### Core Concepts
|
||||
- **Message**: The core abstraction for information exchange between agents. Supports heterogeneous content blocks (text, images, tool calls, tool results).
|
||||
```python
|
||||
from agentscope.message import Msg, TextBlock, ImageBlock, URLSource
|
||||
|
||||
msg = Msg(
|
||||
name="user",
|
||||
content=[TextBlock("Hello world"), ImageBlock(type="image", source=URLSource(type="url", url="..."))],
|
||||
role="user"
|
||||
)
|
||||
```
|
||||
- **Agent**: LLM-empowered agent that can reason, use tools, and generate responses through iterative thinking and action loops.
|
||||
- **Toolkit**: Register and manage tools (Python functions, MCP, agent skills) that agents can call.
|
||||
- **Memory**: Store `Msg` objects as conversation history/context with a marking mechanism for advanced memory management (compression, retrieval).
|
||||
- **ChatModel**: Unified interface across different providers (OpenAI, Anthropic, DashScope, Ollama, etc.) with support for tool use and streaming.
|
||||
- **Formatter**: Convert `Msg` objects to LLM API-specific formats. Must be used with the corresponding ChatModel. Supports multi-agent conversations with different agent identifiers.
|
||||
|
||||
### Basic Usage Examples
|
||||
#### Example 1: Simple Chatbot
|
||||
```python
|
||||
from agentscope.agent import ReActAgent, UserAgent
|
||||
from agentscope.model import DashScopeChatModel
|
||||
from agentscope.formatter import DashScopeChatFormatter
|
||||
from agentscope.memory import InMemoryMemory
|
||||
from agentscope.tool import Toolkit, execute_python_code, execute_shell_command
|
||||
import os, asyncio
|
||||
|
||||
async def main():
|
||||
# Initialize toolkit with tools
|
||||
toolkit = Toolkit()
|
||||
toolkit.register_tool_function(execute_python_code)
|
||||
toolkit.register_tool_function(execute_shell_command)
|
||||
|
||||
# Create ReActAgent with model, memory, formatter, and toolkit
|
||||
agent = ReActAgent(
|
||||
name="Friday",
|
||||
sys_prompt="You're a helpful assistant named Friday.",
|
||||
model=DashScopeChatModel(
|
||||
model_name="qwen-max",
|
||||
api_key=os.getenv("DASHSCOPE_API_KEY"),
|
||||
stream=True,
|
||||
),
|
||||
memory=InMemoryMemory(),
|
||||
formatter=DashScopeChatFormatter(),
|
||||
toolkit=toolkit,
|
||||
)
|
||||
|
||||
# Create user agent for terminal input
|
||||
user = UserAgent(name="user")
|
||||
|
||||
# Conversation loop
|
||||
msg = None
|
||||
while True:
|
||||
msg = await agent(msg) # Agent processes and replies
|
||||
msg = await user(msg) # User inputs next message
|
||||
if msg.get_text_content() == "exit":
|
||||
break
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
#### Example 2: Multi-Agent Conversation
|
||||
AgentScope adopts explicit message passing for multi-agent conversations (PyTorch-like dynamic graph), allowing flexible information flow control.
|
||||
|
||||
```python
|
||||
alice, bob, carol, david = ReActAgent(...), ReActAgent(...), ReActAgent(...), ReActAgent(...)
|
||||
|
||||
msg_alice = await alice()
|
||||
msg_bob = await bob(msg_alice) # Bob receives Alice's message and generate a reply. Alice doesn't receive Bob's message unless explicitly passed back.
|
||||
msg_carol = await carol(msg_alice) # Similarly, the agent cannot receive messages from other agents unless explicitly passed.
|
||||
|
||||
# Broadcasting with MsgHub, a syntactic sugar for message broadcasting within a group of agents
|
||||
from agentscope.pipeline import MsgHub
|
||||
|
||||
async with MsgHub(
|
||||
participants=[alice, bob, carol],
|
||||
announcement=Msg("Host", "Let's discuss", "user")
|
||||
) as hub:
|
||||
await alice() # Bob and Carol receive this
|
||||
await bob() # Alice and Carol receive this
|
||||
|
||||
# Manual broadcast
|
||||
await hub.broadcast(Msg("Host", "New topic", "user"))
|
||||
|
||||
# Dynamic participant management
|
||||
hub.add(david)
|
||||
hub.delete(bob)
|
||||
```
|
||||
|
||||
#### Example 3: Master-Worker Pattern
|
||||
Wrap worker agents as tools for the master agent.
|
||||
|
||||
```python
|
||||
from agentscope.tool import ToolResponse, Toolkit
|
||||
|
||||
async def create_worker(task: str) -> ToolResponse:
|
||||
"""Create a worker agent for the given task.
|
||||
|
||||
Args:
|
||||
task (`str`): The given task, which should be specific and concise.
|
||||
"""
|
||||
task_msg = Msg(name="master", content=task, role="user") # Use the input task or wrap it into a more complex prompt
|
||||
worker = ReActAgent(...)
|
||||
res = await worker(task_msg)
|
||||
return ToolResponse(content=res.content) # Return the worker's response as the tool response
|
||||
|
||||
toolkit = Toolkit()
|
||||
toolkit.register_tool_function(create_worker)
|
||||
```
|
||||
|
||||
## Working with AgentScope
|
||||
This section provides guidance on how to effectively answer questions about AgentScope or coding with the framework.
|
||||
|
||||
### Step 1: Clone the Repository First
|
||||
|
||||
**CRITICAL**: Before doing anything else, clone or update the AgentScope repository. The repository contains essential examples and references.
|
||||
|
||||
```bash
|
||||
# Clone into this skill directory so that you can refer to it across different sessions
|
||||
cd /path/to/this/skill/directory
|
||||
git clone -b main https://github.com/agentscope-ai/agentscope.git
|
||||
|
||||
# Or update if already cloned
|
||||
cd /path/to/this/skill/directory/agentscope
|
||||
git pull
|
||||
```
|
||||
|
||||
**Why this matters**: The repository contains working examples, complete API documentation in source code, and implementation patterns that are more reliable than guessing.
|
||||
|
||||
### Step 2: Understand the Repository Structure
|
||||
The cloned repository is organized as follows. Note this may be outdated as the project evolves, you should always check the actual structure after cloning.
|
||||
```
|
||||
agentscope/
|
||||
├── src/agentscope/ # Main library source code
|
||||
│ ├── agent/ # Agent implementations (ReActAgent, etc.)
|
||||
│ ├── model/ # LLM API wrappers (OpenAI, Anthropic, DashScope, etc.)
|
||||
│ ├── formatter/ # Message formatters for different models
|
||||
│ ├── memory/ # Memory implementations
|
||||
│ ├── tool/ # Tool management and built-in tools
|
||||
│ ├── message/ # Msg class and content blocks
|
||||
│ ├── pipeline/ # Multi-agent orchestration (MsgHub, etc.)
|
||||
│ ├── session/ # Session/state management
|
||||
│ ├── mcp/ # MCP integration
|
||||
│ ├── rag/ # RAG functionality
|
||||
│ ├── realtime/ # Realtime voice interaction
|
||||
│ ├── tts/ # Text-to-speech
|
||||
│ ├── evaluate/ # Evaluation tools
|
||||
│ └── ... # Other modules
|
||||
│
|
||||
├── examples/ # Working examples organized by category
|
||||
│ ├── agent/ # Different agent types
|
||||
│ │ └── ...
|
||||
│ ├── workflows/ # Multi-agent workflows
|
||||
│ │ └── ...
|
||||
│ ├── functionality/ # Specific features
|
||||
│ │ └── ...
|
||||
│ ├── deployment/ # Deployment patterns
|
||||
│ ├── integration/ # Third-party integrations
|
||||
│ ├── evaluation/ # Evaluation examples
|
||||
│ └── game/ # Game examples (e.g., werewolves)
|
||||
│
|
||||
├── docs/ # Documentation
|
||||
│ ├── tutorial/ # Tutorial markdown files
|
||||
│ ├── changelog.md # Version history
|
||||
│ └── roadmap.md # Development roadmap
|
||||
│
|
||||
└── tests/ # Test files
|
||||
```
|
||||
|
||||
### Step 3: Browse Examples by Category
|
||||
|
||||
When looking for similar implementations, **browse the examples directory by category** rather than searching by keywords alone:
|
||||
1. **Start with the category** that matches your use case:
|
||||
- Building a specific agent type? → `examples/agent/`
|
||||
- Multi-agent system? → `examples/workflows/`
|
||||
- Need a specific feature (MCP, RAG, session)? → `examples/functionality/`
|
||||
- Deployment patterns? → `examples/deployment/`
|
||||
2. **List the subdirectories** to see what's available:
|
||||
- Use file listing tools to explore directory structure
|
||||
- Read directory names to understand what each example covers
|
||||
3. **Read example files** to understand implementation patterns:
|
||||
- Most examples contain a main script and supporting files
|
||||
- Look for README files in subdirectories for explanations
|
||||
4. **Combine with text search** when needed:
|
||||
- After identifying relevant directories, search within them for specific patterns
|
||||
- Search for class names, method calls, or specific functionality
|
||||
|
||||
**Example workflow**:
|
||||
```
|
||||
User asks: "Build a FastAPI app with AgentScope"
|
||||
→ Browse: List files in examples/deployment/
|
||||
→ Check: Are there any web service examples?
|
||||
→ Search: Look for "fastapi", "flask", "api", "server" in examples/
|
||||
→ Read: Found examples and adapt to user's needs
|
||||
```
|
||||
|
||||
## Step 4: Verify Functionality Exists
|
||||
Before implementing custom solutions, verify if AgentScope already provides the functionality:
|
||||
|
||||
1. **List required functionalities** (e.g., session management, MCP integration, RAG)
|
||||
2. **Check if provided**:
|
||||
- Browse `examples` for examples
|
||||
- Search tutorial documentation in `docs/tutorial/`
|
||||
- Use the provided scripts (see Part 3) to explore API structure
|
||||
- Read source code in `src/agentscope/` for implementation details
|
||||
3. **If not provided**: Check how to customize by reading base classes and inheritance patterns in source code
|
||||
|
||||
### Step 5: Make a Plan
|
||||
Always create a plan before coding:
|
||||
1. Identify what AgentScope components you'll use
|
||||
2. Determine what needs custom implementation
|
||||
3. Outline the architecture and data flow
|
||||
4. Consider edge cases and error handling
|
||||
|
||||
### Step 6: Code with API Reference
|
||||
When writing code:
|
||||
1. **Check docstrings and arguments** before using any class/method
|
||||
- Read source code files to see signatures and documentation, or
|
||||
- Use the provided scripts to view module/class structures
|
||||
- **NEVER** make up classes, methods, or arguments
|
||||
2. **Check parent classes** - A class's functionality includes inherited methods
|
||||
3. **Manage lifecycle** - Clean up resources when needed (close connections, release memory)
|
||||
|
||||
### Common Pitfalls to Avoid
|
||||
- ❌ Guessing API signatures without checking documentation
|
||||
- ❌ Implementing features that already exist in AgentScope
|
||||
- ❌ Mixing incompatible Model and Formatter (e.g., OpenAI model with DashScope formatter)
|
||||
- ❌ Forgetting to await async agent calls
|
||||
- ❌ Not checking parent class methods when searching for functionality
|
||||
- ❌ Searching by keywords only without browsing the organized examples directory structure
|
||||
|
||||
## Resources
|
||||
This section lists all available resources for working with AgentScope.
|
||||
### Official Documentation
|
||||
- **[Tutorial](https://agentscope.ai/docs/)**: Comprehensive step-by-step guide covering most functionalities in detail. This is the primary resource for learning AgentScope.
|
||||
|
||||
### GitHub Resources
|
||||
- **[Main Repository](https://github.com/agentscope-ai/agentscope)**: Source code, examples, and documentation
|
||||
- **[Project Board](https://github.com/orgs/agentscope-ai/projects/2)**: Official development roadmap and task tracking
|
||||
- **[Design Discussions](https://github.com/agentscope-ai/agentscope/discussions/categories/agentscope-design-book)**: In-depth explanations about specific modules/functions/components
|
||||
|
||||
### Repository Structure
|
||||
When the repository is cloned locally, the following structure is available for reference:
|
||||
- **`src/agentscope/`**: Main library source code
|
||||
- Read this for API implementation details
|
||||
- Check docstrings for parameter descriptions
|
||||
- Understand inheritance hierarchies
|
||||
- **`examples/`**: Working examples demonstrating features
|
||||
- Start here when building similar applications
|
||||
- Examples cover: basic agents, multi-agent systems, tool usage, deployment patterns
|
||||
- **`docs/tutorial/`**: Tutorial documentation source files
|
||||
- Markdown files explaining concepts and usage
|
||||
- More detailed than README files
|
||||
|
||||
### Scripts
|
||||
Located in `scripts/` directory of this skill.
|
||||
|
||||
- `view_pypi_latest_version.sh`: View the latest version of AgentScope on PyPI.
|
||||
```bash
|
||||
cd /path/to/this/skill/directory/scripts/
|
||||
bash view_pypi_latest_version.sh
|
||||
```
|
||||
- `view_module_signature.py`: Explore the structure of AgentScope modules, classes, and methods.
|
||||
**Search strategy**: Use deep-first search - start broad, then narrow down:
|
||||
1. `agentscope` → see all submodules
|
||||
2. `agentscope.agent` → see agent-related classes
|
||||
3. `agentscope.agent.ReActAgent` → see specific class methods
|
||||
|
||||
```bash
|
||||
cd /path/to/this/skill/directory/scripts/
|
||||
# View top-level module
|
||||
python view_module_signature.py --module agentscope
|
||||
# View specific submodule
|
||||
python view_module_signature.py --module agentscope.agent
|
||||
# View specific class
|
||||
python view_module_signature.py --module agentscope.agent.ReActAgent
|
||||
```
|
||||
|
||||
## Reference
|
||||
Located in `references/` directory of this skill.
|
||||
|
||||
- **`multi_agent_orchestration.md`**: Multi-agent orchestration concepts and implementation
|
||||
- **`deployment_guide.md`**: Deployment patterns and best practices
|
||||
154
.claude/skills/agentscope-skill/references/deployment_guide.md
Normal file
154
.claude/skills/agentscope-skill/references/deployment_guide.md
Normal file
@ -0,0 +1,154 @@
|
||||
# Deployment Guide
|
||||
|
||||
In agent application, [agentscope-runtime](https://github.com/agentscope-ai/agentscope-runtime) addresses three critical production deployment challenges:
|
||||
|
||||
* Deployment: Unified `AgentApp` interface abstracts deployment targets (local, Docker, K8s, serverless, etc.)
|
||||
* Security Risks: Sandboxed execution environment isolate tool calls (Python, shell, browser, filesystem, etc.)
|
||||
|
||||
## Quickstart
|
||||
|
||||
```bash
|
||||
uv pip install agentscope-runtime
|
||||
# or
|
||||
# pip install agentscope-runtime
|
||||
```
|
||||
|
||||
## Deployment
|
||||
|
||||
AgentScope Runtime provides `AgentApp`, a FastAPI-based service wrapper that turns your agents into production-ready APIs with streaming responses, health checks, and lifecycle management. It supports multiple deployment targets from local development to cloud platforms.
|
||||
|
||||
> Note: The `AgentApp` provides a unified interface for deployment, but you can also choose to deploy your agent service using your own FastAPI server or other web frameworks if you prefer.
|
||||
|
||||
### Complete Example
|
||||
|
||||
The following example can also be found in the README.md of the [agentscope-runtime repository](https://github.com/agentscope-ai/agentscope-runtime)
|
||||
|
||||
```python
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from agentscope.agent import ReActAgent
|
||||
from agentscope.model import DashScopeChatModel
|
||||
from agentscope.formatter import DashScopeChatFormatter
|
||||
from agentscope.tool import Toolkit, execute_python_code
|
||||
from agentscope.pipeline import stream_printing_messages
|
||||
from agentscope.memory import InMemoryMemory
|
||||
from agentscope.session import RedisSession
|
||||
|
||||
from agentscope_runtime.engine import AgentApp
|
||||
from agentscope_runtime.engine.schemas.agent_schemas import AgentRequest
|
||||
|
||||
|
||||
# 1. Define lifespan manager
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""Manage resources during service startup and shutdown"""
|
||||
# Startup: Initialize Session manager
|
||||
import fakeredis
|
||||
|
||||
fake_redis = fakeredis.aioredis.FakeRedis(decode_responses=True)
|
||||
# NOTE: This FakeRedis instance is for development/testing only.
|
||||
# In production, replace it with your own Redis client/connection
|
||||
# (e.g., aioredis.Redis)
|
||||
app.state.session = RedisSession(connection_pool=fake_redis.connection_pool)
|
||||
|
||||
yield # Service is running
|
||||
|
||||
# Shutdown: Add cleanup logic here (e.g., closing database connections)
|
||||
print("AgentApp is shutting down...")
|
||||
|
||||
|
||||
# 2. Create AgentApp instance
|
||||
agent_app = AgentApp(
|
||||
app_name="Friday",
|
||||
app_description="A helpful assistant",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
|
||||
# 3. Define request handling logic
|
||||
@agent_app.query(framework="agentscope")
|
||||
async def query_func(
|
||||
self,
|
||||
msgs,
|
||||
request: AgentRequest = None,
|
||||
**kwargs,
|
||||
):
|
||||
session_id = request.session_id
|
||||
user_id = request.user_id
|
||||
|
||||
toolkit = Toolkit()
|
||||
toolkit.register_tool_function(execute_python_code)
|
||||
|
||||
agent = ReActAgent(
|
||||
name="Friday",
|
||||
model=DashScopeChatModel(
|
||||
"qwen-turbo",
|
||||
api_key=os.getenv("DASHSCOPE_API_KEY"),
|
||||
stream=True,
|
||||
),
|
||||
sys_prompt="You're a helpful assistant named Friday.",
|
||||
toolkit=toolkit,
|
||||
memory=InMemoryMemory(),
|
||||
formatter=DashScopeChatFormatter(),
|
||||
)
|
||||
agent.set_console_output_enabled(enabled=False)
|
||||
|
||||
# Load state
|
||||
await agent_app.state.session.load_session_state(
|
||||
session_id=session_id,
|
||||
user_id=user_id,
|
||||
agent=agent,
|
||||
)
|
||||
|
||||
async for msg, last in stream_printing_messages(
|
||||
agents=[agent],
|
||||
coroutine_task=agent(msgs),
|
||||
):
|
||||
yield msg, last
|
||||
|
||||
# Save state
|
||||
await agent_app.state.session.save_session_state(
|
||||
session_id=session_id,
|
||||
user_id=user_id,
|
||||
agent=agent,
|
||||
)
|
||||
|
||||
|
||||
# 4. Run the application
|
||||
agent_app.run(host="127.0.0.1", port=8090)
|
||||
```
|
||||
|
||||
## Tool Sandbox
|
||||
|
||||
Tool Sandbox provides secure, isolated environments for executing code and tools without affecting your system. It supports multiple sandbox types including base Python/shell execution, GUI operations, browser automation, filesystem access, and mobile interactions, with both synchronous and asynchronous APIs.
|
||||
|
||||
### Complete Example
|
||||
|
||||
```python
|
||||
# --- Synchronous version ---
|
||||
from agentscope_runtime.sandbox import BaseSandbox
|
||||
|
||||
with BaseSandbox() as box:
|
||||
# By default, pulls `agentscope/runtime-sandbox-base:latest` from DockerHub
|
||||
print(box.list_tools()) # List all available tools
|
||||
print(box.run_ipython_cell(code="print('hi')")) # Run Python code
|
||||
print(box.run_shell_command(command="echo hello")) # Run shell command
|
||||
input("Press Enter to continue...")
|
||||
|
||||
# --- Asynchronous version ---
|
||||
from agentscope_runtime.sandbox import BaseSandboxAsync
|
||||
|
||||
async with BaseSandboxAsync() as box:
|
||||
# Default image is `agentscope/runtime-sandbox-base:latest`
|
||||
print(await box.list_tools_async()) # List all available tools
|
||||
print(await box.run_ipython_cell(code="print('hi')")) # Run Python code
|
||||
print(await box.run_shell_command(command="echo hello")) # Run shell command
|
||||
input("Press Enter to continue...")
|
||||
```
|
||||
|
||||
## Further Reading
|
||||
|
||||
* [AgentScope-Runtime Documentation](https://runtime.agentscope.io/en/intro.html)
|
||||
* [AgentScope-Runtime GitHub Repository](https://github.com/agentscope-ai/agentscope-runtime)
|
||||
@ -0,0 +1,86 @@
|
||||
# Multi-Agent Orchestration
|
||||
There are two types of multi-agent orchestrations:
|
||||
|
||||
- Master-worker: a master agent assigns tasks to multiple worker agents, and the worker agents only report to the master agent.
|
||||
- Peer-to-peer (or conversational): multiple agents interact with each other, and each agent can perceive the information from different identities in the conversation.
|
||||
|
||||
## Master-Worker
|
||||
In AgentScope, the master-worker orchestration can be implemented by wrapping the worker agents as tools for the master agent.
|
||||
The worker agents can be designed to perform specific tasks, or a unified worker agent can be assigned with different tasks by providing different system prompts or tools.
|
||||
|
||||
The following is an example of how to wrap a worker agent as a tool for the master agent.
|
||||
|
||||
> Note: the tool name, input arguments, and output organization of the worker agent can be customized as needed.
|
||||
|
||||
```python
|
||||
from agentscope.pipeline import stream_printing_messages
|
||||
from agentscope.tool import ToolResponse, Toolkit, execute_shell_command
|
||||
from agentscope.agent import ReActAgent
|
||||
from agentscope.message import Msg
|
||||
|
||||
from typing import AsyncGenerator
|
||||
|
||||
async def create_worker(task: str) -> AsyncGenerator[ToolResponse, None]:
|
||||
"""{description}
|
||||
|
||||
Args:
|
||||
task (`str`):
|
||||
The task to be performed by the worker agent.
|
||||
"""
|
||||
toolkit = Toolkit()
|
||||
toolkit.register_tool_function(execute_shell_command)
|
||||
|
||||
agent = ReActAgent(...)
|
||||
|
||||
# We disable the terminal printing to avoid messy outputs
|
||||
agent.set_console_output_enabled(False)
|
||||
|
||||
async for msg, _ in stream_printing_messages(
|
||||
agents=[agent],
|
||||
coroutine_task=agent(
|
||||
# Wrap the task into a user Msg object
|
||||
Msg("user", f"Please perform the following task: {task}", "user")
|
||||
),
|
||||
):
|
||||
# Optionally, you can process the message here before yielding it to the master agent
|
||||
# to control the information exposed to the master agent. For example, filter out the
|
||||
# reasoning process and only expose the final action to the master agent.
|
||||
yield msg
|
||||
```
|
||||
|
||||
## Peer-to-Peer
|
||||
|
||||
Because agentscope supports explicit message passing, the peer-to-peer orchestration can be implemented by allowing multiple agents to perceive the messages from each other.
|
||||
Additionally, the `pipeline` module provides different syntactic sugers to facilitate the implementation of different conversation patterns among multiple agents, such as broadcasting, fan-out, and so on.
|
||||
|
||||
The following is an example of how to implement a peer-to-peer conversation among multiple agents.
|
||||
|
||||
```python
|
||||
from agentscope.pipeline import MsgHub
|
||||
... # other imports
|
||||
|
||||
alice = ReActAgent(...)
|
||||
bob = ReActAgent(...)
|
||||
charlie = ReActAgent(...)
|
||||
|
||||
# Create a message hub
|
||||
async with MsgHub(
|
||||
participants=[alice, bob, charlie],
|
||||
# The announcement message will be broadcasted to all participants at the beginning of the conversation
|
||||
announcement=Msg(
|
||||
"user",
|
||||
"Now introduce yourself in one sentence, including your name, age and career.",
|
||||
"user",
|
||||
),
|
||||
) as hub:
|
||||
# Group chat without manual message passing
|
||||
await alice()
|
||||
await bob()
|
||||
await charlie()
|
||||
```
|
||||
|
||||
## Further Reading
|
||||
More information about multi-agent orchestration or pipeline can be found in the following references:
|
||||
- Tutorial of pipeline:
|
||||
- [Online link](https://doc.agentscope.io/tutorial/task_pipeline.html)
|
||||
- [Source Code]({path_to_agentscope_repo}/agentscope/docs/tutorial/en/src/task_pipeline.py)
|
||||
306
.claude/skills/agentscope-skill/scripts/view_module_signature.py
Normal file
306
.claude/skills/agentscope-skill/scripts/view_module_signature.py
Normal file
@ -0,0 +1,306 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# pylint: skip-file
|
||||
"""Get the signatures of functions and classes in the agentscope library."""
|
||||
from typing import Literal, Callable
|
||||
|
||||
import agentscope
|
||||
import inspect
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
def get_class_signature(cls: type) -> str:
|
||||
"""Get the signature of a class.
|
||||
|
||||
Args:
|
||||
cls (`type`):
|
||||
A class object.
|
||||
|
||||
Returns:
|
||||
str: The signature of the class.
|
||||
"""
|
||||
# Obtain class name and docstring
|
||||
class_name = cls.__name__
|
||||
class_docstring = cls.__doc__ or ""
|
||||
|
||||
# Construct the class string
|
||||
class_str = f"class {class_name}:\n"
|
||||
if class_docstring:
|
||||
class_str += f' """{class_docstring}"""\n'
|
||||
|
||||
# Obtain the module of the class
|
||||
methods = []
|
||||
for name, method in inspect.getmembers(cls, predicate=inspect.isfunction):
|
||||
# Skip methods that are not part of the class
|
||||
if method.__qualname__.split(".")[0] != class_name:
|
||||
continue
|
||||
|
||||
if name.startswith("_") and name not in ["__init__", "__call__"]:
|
||||
continue
|
||||
|
||||
# Obtain the method's signature
|
||||
sig = inspect.signature(method)
|
||||
|
||||
# Construct the method string
|
||||
method_str = f" def {name}{sig}:\n"
|
||||
|
||||
# Add the method's docstring if it exists
|
||||
method_docstring = method.__doc__ or ""
|
||||
if method_docstring:
|
||||
method_str += f' """{method_docstring}"""\n'
|
||||
|
||||
methods.append(method_str)
|
||||
|
||||
class_str += "\n".join(methods)
|
||||
return class_str
|
||||
|
||||
|
||||
def get_function_signature(func: Callable) -> str:
|
||||
"""Get the signature of a function."""
|
||||
sig = inspect.signature(func)
|
||||
method_str = f"def {func.__name__}{sig}:\n"
|
||||
|
||||
method_docstring = func.__doc__ or ""
|
||||
if method_docstring:
|
||||
method_str += f' """{method_docstring}"""\n'
|
||||
|
||||
return method_str
|
||||
|
||||
|
||||
class FuncOrCls(BaseModel):
|
||||
"""The class records the module, signature, docstring, reference, and
|
||||
type"""
|
||||
|
||||
module: str
|
||||
"""The module of the function or class."""
|
||||
signature: str
|
||||
"""The signature of the function or class."""
|
||||
docstring: str
|
||||
"""The docstring of the function or class."""
|
||||
reference: str
|
||||
"""The reference to the source code of the function or class"""
|
||||
type: Literal["function", "class"]
|
||||
"""The type of the function or class, either 'function' or 'class'."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
module: str,
|
||||
signature: str,
|
||||
docstring: str,
|
||||
reference: str,
|
||||
# pylint: disable=redefined-builtin
|
||||
type: Literal["function", "class"],
|
||||
) -> None:
|
||||
"""Initialize the FuncOrCls instance."""
|
||||
super().__init__(
|
||||
module=module,
|
||||
signature=signature.strip(),
|
||||
docstring=docstring.strip(),
|
||||
reference=reference,
|
||||
type=type,
|
||||
)
|
||||
|
||||
|
||||
def _truncate_docstring(docstring: str, max_length: int = 200) -> str:
|
||||
"""Truncate the docstring to a maximum length.
|
||||
|
||||
Args:
|
||||
docstring (`str`):
|
||||
The docstring to truncate.
|
||||
max_length (`int`, *optional*, defaults to 200):
|
||||
The maximum length of the docstring.
|
||||
|
||||
Returns:
|
||||
`str`:
|
||||
The truncated docstring.
|
||||
"""
|
||||
if len(docstring) > max_length:
|
||||
return docstring[:max_length] + "..."
|
||||
return docstring
|
||||
|
||||
|
||||
def get_agentscope_module_signatures() -> list[FuncOrCls]:
|
||||
"""Get the signatures of functions and classes in the agentscope library.
|
||||
|
||||
Returns:
|
||||
`list[FuncOrCls]`:
|
||||
A list of FuncOrCls instances representing the functions and
|
||||
classes in the agentscope library.
|
||||
"""
|
||||
signatures = []
|
||||
for module in agentscope.__all__:
|
||||
as_module = getattr(agentscope, module)
|
||||
path_module = ".".join(["agentscope", module])
|
||||
|
||||
# Functions
|
||||
if inspect.isfunction(as_module):
|
||||
file = inspect.getfile(as_module)
|
||||
source_lines, start_line = inspect.getsourcelines(as_module)
|
||||
signatures.append(
|
||||
FuncOrCls(
|
||||
module=path_module,
|
||||
signature=get_function_signature(as_module),
|
||||
docstring=_truncate_docstring(as_module.__doc__ or ""),
|
||||
reference=f"{file}: {start_line}-"
|
||||
f"{start_line + len(source_lines)}",
|
||||
type="function",
|
||||
),
|
||||
)
|
||||
|
||||
else:
|
||||
if not hasattr(as_module, "__all__"):
|
||||
continue
|
||||
|
||||
# Modules with __all__ attribute
|
||||
for name in as_module.__all__:
|
||||
func_or_cls = getattr(as_module, name)
|
||||
path_func_or_cls = ".".join([path_module, name])
|
||||
|
||||
if inspect.isclass(func_or_cls):
|
||||
file = inspect.getfile(func_or_cls)
|
||||
source_lines, start_line = inspect.getsourcelines(
|
||||
func_or_cls,
|
||||
)
|
||||
signatures.append(
|
||||
FuncOrCls(
|
||||
module=path_func_or_cls,
|
||||
signature=get_class_signature(func_or_cls),
|
||||
docstring=_truncate_docstring(
|
||||
func_or_cls.__doc__ or "",
|
||||
),
|
||||
reference=(
|
||||
f"{file}: {start_line}-"
|
||||
f"{start_line + len(source_lines)}"
|
||||
),
|
||||
type="class",
|
||||
),
|
||||
)
|
||||
|
||||
elif inspect.isfunction(func_or_cls):
|
||||
file = inspect.getfile(func_or_cls)
|
||||
source_lines, start_line = inspect.getsourcelines(
|
||||
func_or_cls,
|
||||
)
|
||||
signatures.append(
|
||||
FuncOrCls(
|
||||
module=path_func_or_cls,
|
||||
signature=get_function_signature(func_or_cls),
|
||||
docstring=_truncate_docstring(
|
||||
func_or_cls.__doc__ or "",
|
||||
),
|
||||
reference=(
|
||||
f"{file}: {start_line}-"
|
||||
f"{start_line + len(source_lines)}"
|
||||
),
|
||||
type="function",
|
||||
),
|
||||
)
|
||||
|
||||
return signatures
|
||||
|
||||
|
||||
def view_agentscope_library(
|
||||
module: str,
|
||||
) -> str:
|
||||
"""View AgentScope's Python library by given a module name
|
||||
(e.g. agentscope), and return the module's submodules, classes, and
|
||||
functions. Given a class name, return the class's documentation, methods,
|
||||
and their signatures. Given a function name, return the function's
|
||||
documentation and signature. If you don't have any information about
|
||||
AgentScope library, try to use "agentscope" to view the available top
|
||||
modules.
|
||||
|
||||
Note this function only provide the module's brief information.
|
||||
For more information, you should view the source code.
|
||||
|
||||
Args:
|
||||
module (`str`):
|
||||
The module name to view, which should be a module path separated
|
||||
by dots (e.g. "agentscope.models"). It can refer to a module,
|
||||
a class, or a function.
|
||||
"""
|
||||
if not module.startswith("agentscope"):
|
||||
return (
|
||||
f"Module '{module}' is invalid. The input module should be "
|
||||
f"'agentscope' or submodule of 'agentscope.xxx.xxx' "
|
||||
f"(separated by dots)."
|
||||
)
|
||||
|
||||
agentscope_top_modules = {}
|
||||
for as_module in agentscope.__all__:
|
||||
if as_module in ["__version__", "logger"]:
|
||||
continue
|
||||
agentscope_top_modules[as_module] = getattr(
|
||||
agentscope,
|
||||
as_module,
|
||||
).__doc__
|
||||
|
||||
# top modules
|
||||
if module == "agentscope":
|
||||
top_modules_description = (
|
||||
[
|
||||
"The top-level modules in AgentScope library:",
|
||||
]
|
||||
+ [
|
||||
f"- agentscope.{k}: {v}"
|
||||
for k, v in agentscope_top_modules.items()
|
||||
]
|
||||
+ [
|
||||
"You can further view the classes/function within above "
|
||||
"modules by calling this function with the above module name.",
|
||||
]
|
||||
)
|
||||
return "\n".join(top_modules_description)
|
||||
|
||||
# class, functions
|
||||
modules = get_agentscope_module_signatures()
|
||||
for as_module in modules:
|
||||
if as_module.module == module:
|
||||
return f"""- The signature of '{module}':
|
||||
```python
|
||||
{as_module.signature}
|
||||
```
|
||||
|
||||
- Source code reference: {as_module.reference}"""
|
||||
|
||||
# two-level modules
|
||||
collected_modules = []
|
||||
for as_module in modules:
|
||||
if as_module.module.startswith(module):
|
||||
collected_modules.append(as_module)
|
||||
|
||||
if len(collected_modules) > 0:
|
||||
collected_modules_content = (
|
||||
[
|
||||
f"The classes/functions and their truncated docstring in "
|
||||
f"'{module}' module:",
|
||||
]
|
||||
+ [f"- {_.module}: {repr(_.docstring)}" for _ in collected_modules]
|
||||
+ [
|
||||
"The docstring is truncated for limited context. For detailed "
|
||||
"signature and methods, call this function with the above "
|
||||
"module name",
|
||||
]
|
||||
)
|
||||
|
||||
return "\n".join(collected_modules_content)
|
||||
|
||||
return (
|
||||
f"Module '{module}' not found. Use 'agentscope' to view the "
|
||||
f"top-level modules to ensure the given module is valid."
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument(
|
||||
"--module",
|
||||
type=str,
|
||||
default="agentscope",
|
||||
help="The module name to view, e.g. 'agentscope'",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
res = view_agentscope_library(module=args.module)
|
||||
print(res)
|
||||
@ -0,0 +1,3 @@
|
||||
# !/bin/bash
|
||||
|
||||
curl -s https://pypi.org/pypi/agentscope/json | python -c "import sys,json; print(json.load(sys.stdin)['info']['version'])"
|
||||
Loading…
x
Reference in New Issue
Block a user