Skip to content

Commit

Permalink
minor fix according to zhijianma's comments
Browse files Browse the repository at this point in the history
  • Loading branch information
yxdyc committed Jan 18, 2024
1 parent ab751ef commit 1927d1a
Show file tree
Hide file tree
Showing 11 changed files with 31 additions and 34 deletions.
4 changes: 2 additions & 2 deletions docs/tutorial/102-concepts.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ In this tutorial, you'll have an initial understanding of the **fundamental conc

* **Agent** refers to an autonomous entity capable of performing actions to achieve specific objectives (probably powered by LLMs). In AgentScope, an agent takes the message as input and generates a corresponding response message. Agents can interact with each other to simulate human-like behaviors (e.g., discussion or debate) and cooperate to finish complicated tasks (e.g., generate runnable and reliable code).
* **Message** is a carrier of communication information among agents. It encapsulates information that needs to be conveyed, such as instructions, multi-modal data, or status updates. In AgentScope, a message is a subclass of Python's dict with additional features for inter-agent communication, including fields such as `name` and `content` for identification and payload delivery.
* **Memory** refers to the structures (e.g., list-like memory, database-based memory) used to store and manage `Message` that agents need to remember and store. This can include chat history, knowledge, or other data that informs the agent's future actions.
* **Memory** refers to the structures (e.g., list-like memory, database-based memory) used to store and manage `Msg` (Message) that agents need to remember and store. This can include chat history, knowledge, or other data that informs the agent's future actions.
* **Service** is a collection of functionality tools (e.g., web search, code interpreter, file processing) that provide specific capabilities or processes that are independent of an agent's memory state. Services can be invoked by agents or other components and designed to be reusable across different scenarios.
* **Pipeline** refers to the interaction order or pattern of agents in a task. AgentScope provides built-in `pipelines` to streamline the process of collaboration across multiple agents, such as `SequentialPipeline` and `ForLoopPipeline`. When a `Pipeline` is executed, the `message` passes from predecessors to successors with intermediate results for the task.
* **Pipeline** refers to the interaction order or pattern of agents in a task. AgentScope provides built-in `pipelines` to streamline the process of collaboration across multiple agents, such as `SequentialPipeline` and `ForLoopPipeline`. When a `Pipeline` is executed, the *message* passes from predecessors to successors with intermediate results for the task.


## Code Structure
Expand Down
15 changes: 6 additions & 9 deletions docs/tutorial/103-example.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ AgentScope is a versatile platform for building and running multi-agent applicat

## Step1: Prepare Model Configs

Agent is the basic composition and communication unit in AgentScope. To initialize an model-based agent, you need to prepare your configs for avaliable models. AgentScope supports a variety of APIs for pre-trained models. Here is a table outlining the supported APIs and the type of arguments required for each:
Agent is the basic composition and communication unit in AgentScope. To initialize a model-based agent, you need to prepare your configs for avaliable models. AgentScope supports a variety of APIs for pre-trained models. Here is a table outlining the supported APIs and the type of arguments required for each:

| Model Usage | Type Argument in AgentScope | Supported APIs |
| -------------------- | ------------------ |-----------------------------------------------------------------------------|
Expand Down Expand Up @@ -32,13 +32,10 @@ You can register your configuration by calling AgentScope's initilization method
```python
import agentscope

agentscope.init(model_configs="./openai_model_configs.json")
agentscope.init(model_configs="./modelscope_model_configs.json") # init again to use openai and modelscope at the same time

# or you can init once by passing a list of config dict
# openai_cfg_dict = {...dict_filling...}
# modelscope_cfg_dict = {...dict_filling...}
# agentscope.init(model_configs=[openai_cfg_dict, modelscope_cfg_dict])
# init once by passing a list of config dict
openai_cfg_dict = {...dict_filling...}
modelscope_cfg_dict = {...dict_filling...}
agentscope.init(model_configs=[openai_cfg_dict, modelscope_cfg_dict])
```


Expand All @@ -62,7 +59,7 @@ userAgent = UserAgent()

## Step3: Agent Conversation

`Message` is the primary means of communication between agents in AgentScope. They are Python dictionaries comprising essential fields like the actual `content` of this message and the sender's `name`. Optionally, a message can include a `url` to either a local file (image, video or audio) or website.
"Message" is the primary means of communication between agents in AgentScope. They are Python dictionaries comprising essential fields like the actual `content` of this message and the sender's `name`. Optionally, a message can include a `url` to either a local file (image, video or audio) or website.

```python
from agentscope.message import Msg
Expand Down
4 changes: 2 additions & 2 deletions docs/tutorial/104-usecase.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Crafting Your First Application

<img src="https://img.alicdn.com/imgextra/i3/O1CN01dFpOh82643mygUh2Z_!!6000000007607-2-tps-1024-1024.png" alt="img" style="zoom:33%;" />
<img src="https://img.alicdn.com/imgextra/i3/O1CN01dFpOh82643mygUh2Z_!!6000000007607-2-tps-1024-1024.png" alt="img" style="zoom:25%;" />

Before diving into the advanced topics of AgentScope, in this tutorial, we will give you a glance at building a Werewolf application with out-of-the-box components of AgentScope.

Expand All @@ -10,7 +10,7 @@ Let the adventure begin to unlock the potential of multi-agent applications with

## Getting Started

Firstly, ensure that you have installed and configured AgentScope properly. Besides, we will involve the basic concepts of `Model API`, `Agent`, `Message`, and `pipeline,` as described in [Tutorial-Concept](https://github.com/alibaba/AgentScope/tree/main/docs/tutorial/102-concepts.md). The overview of this tutorial is shown below:
Firstly, ensure that you have installed and configured AgentScope properly. Besides, we will involve the basic concepts of `Model API`, `Agent`, `Msg`, and `pipeline,` as described in [Tutorial-Concept](https://github.com/alibaba/AgentScope/tree/main/docs/tutorial/102-concepts.md). The overview of this tutorial is shown below:

* [Step 1: Prepare **Model API** and Set Model Configs](#step-1-prepare-model-api-and-set-model-configs)
* [Step 2: Define the Roles of Each **Agent**](#step-2-define-the-roles-of-each-agent)
Expand Down
2 changes: 1 addition & 1 deletion docs/tutorial/105-logging.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ Logging chat messages helps keep a record of the conversation between agents. He
# Log a simple string message.
logger.chat("Hello World!")

# Log a `message` representing dialogue with a speaker and content.
# Log a `msg` representing dialogue with a speaker and content.
logger.chat({"name": "User", "content": "Hello, how are you?"})
logger.chat({"name": "Agent", "content": "I'm fine, thank you!"})
```
Expand Down
16 changes: 8 additions & 8 deletions docs/tutorial/201-agent.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ Each AgentBase derivative is composed of several key characteristics:

In addition to these attributes, `AgentBase` endows agents with pivotal methods such as `observe` and `reply`:

* `observe()`: Through this method, an agent can take note of `message` without immediately replying, allowing it to update its memory based on the observed `message`.
* `reply()`: This is the primary method that developers must implement. It defines the agent's behavior in response to an incoming `message`, encapsulating the logic that results in the agent's output.
* `observe()`: Through this method, an agent can take note of *message* without immediately replying, allowing it to update its memory based on the observed *message*.
* `reply()`: This is the primary method that developers must implement. It defines the agent's behavior in response to an incoming *message*, encapsulating the logic that results in the agent's output.

Besides, for unified interfaces and type hints, we introduce another base class `Operator`, which indicates performing some operation on input data by the `__call__` function. And we make `AgentBase` a subclass of `Operator`.

Expand All @@ -40,13 +40,13 @@ class AgentBase(Operator):
def observe(self, x: Union[dict, Sequence[dict]]) -> None:
# An optional method for updating the agent's internal state based on
# messages it has observed. This method can be used to enrich the
# agent's understanding and memory without producing an immediate
# agent's understanding and memory without producing an immediate
# response.
self.memory.add(x)

def reply(self, x: dict = None) -> dict:
# The core method to be implemented by custom agents. It defines the
# logic for processing an input message and generating a suitable
# logic for processing an input message and generating a suitable
# response.
raise NotImplementedError(
f"Agent [{type(self).__name__}] is missing the required "
Expand All @@ -72,13 +72,13 @@ Below is a table summarizing the functionality of some of the key agents availab

## Customizing Agents from the AgentPool

Customizing an agent from AgentPool enables you to tailor its functionality to meet the unique demands of your multi-agent application. You have the flexibility to modify existing agents with minimal effort by **adjusting configurations** and prompts or, for more extensive customization, you can engage in secondary development.
Customizing an agent from AgentPool enables you to tailor its functionality to meet the unique demands of your multi-agent application. You have the flexibility to modify existing agents with minimal effort by **adjusting configurations** and prompts or, for more extensive customization, you can engage in secondary development.

Below, we provide usages of how to configure various agents from the AgentPool:

### `DialogAgent`

- **Reply Method**: The `reply` method is where the main logic for processing input `message` and generating responses.
- **Reply Method**: The `reply` method is where the main logic for processing input *message* and generating responses.

```python
def reply(self, x: dict = None) -> dict:
Expand Down Expand Up @@ -121,7 +121,7 @@ service_bot = DialogAgent(**dialog_agent_config)

### `UserAgent`

- **Reply Method**: This method processes user input by prompting for content and if needed, additional keys and a URL. The gathered data is stored in a `message` object in the agent's memory for logging or later use and returns the message as a response.
- **Reply Method**: This method processes user input by prompting for content and if needed, additional keys and a URL. The gathered data is stored in a *message* object in the agent's memory for logging or later use and returns the message as a response.

```python
def reply(
Expand Down
2 changes: 1 addition & 1 deletion docs/tutorial/202-pipeline.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Agent Interactions: Dive deeper into Pipelines and Message Hub

**Pipeline & MsgHub** (message hub) are one or a sequence of steps describing how the structured `Message` passes between multi-agents, which streamlines the process of collaboration across agents.
**Pipeline & MsgHub** (message hub) are one or a sequence of steps describing how the structured `Msg` passes between multi-agents, which streamlines the process of collaboration across agents.

`Pipeline` allows users to program communication among agents easily, and `MsgHub` enables message sharing among agents like a group chat.

Expand Down
2 changes: 1 addition & 1 deletion docs/tutorial/203-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ from transformers import AutoModelForCausalLM, AutoTokenizer
model = AutoModelForCausalLM.from_pretrained(MODEL_NAME)
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model.eval()
# Do remember to re-implement the `reply` method to tokenize `message`!
# Do remember to re-implement the `reply` method to tokenize *message*!
agent = YourAgent(name='agent', model=model, tokenizer=tokenizer)
```

Expand Down
12 changes: 6 additions & 6 deletions docs/tutorial/205-memory.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ Here are the key attributes managed by the `MessageBase` class:

### `Msg`

The `Msg` ("Message") subclass extends `MessageBase` and represents a standard `message`. `Msg` provides concrete definitions for the `to_str` and `serialize` methods to enable string representation and serialization suitable for the agent's operational context.
The `Msg` ("Message") subclass extends `MessageBase` and represents a standard *message*. `Msg` provides concrete definitions for the `to_str` and `serialize` methods to enable string representation and serialization suitable for the agent's operational context.

```python
class Msg(MessageBase):
Expand Down Expand Up @@ -81,7 +81,7 @@ class Tht(MessageBase):

### `MemoryBase`

`MemoryBase` is an abstract class that handles an agent's memory in a structured way. It defines operations for storing, retrieving, deleting, and manipulating `message`'s content.
`MemoryBase` is an abstract class that handles an agent's memory in a structured way. It defines operations for storing, retrieving, deleting, and manipulating *message*'s content.

```python
class MemoryBase(ABC):
Expand Down Expand Up @@ -125,11 +125,11 @@ class MemoryBase(ABC):
Here are the key methods of `MemoryBase`:

- **`get_memory`**: This method is responsible for retrieving stored messages from the agent's memory. It can return these messages in different formats as specified by the `return_type`. The method can also retrieve a specific number of recent messages if `recent_n` is provided, and it can apply a filtering function (`filter_func`) to select messages based on custom criteria.
- **`add`**: This method is used to add a new `message` to the agent's memory. It can accept a single message or a list of messages. Each message is typically an instance of `MessageBase` or its subclasses.
- **`add`**: This method is used to add a new *message* to the agent's memory. It can accept a single message or a list of messages. Each message is typically an instance of `MessageBase` or its subclasses.
- **`delete`**: This method enables the removal of messages from memory by their index (or indices if an iterable is provided).
- **`load`**: This method allows for the bulk loading of messages into the agent's memory from an external source. The `overwrite` parameter determines whether to clear the existing memory before loading the new set of messages.
- **`export`**: This method facilitates exporting the stored `message` from the agent's memory either to an external file (specified by `file_path`) or directly into the working memory of the program (if `to_mem` is set to `True`).
- **`clear`**: This method purges all `message` from the agent's memory, essentially resetting it.
- **`export`**: This method facilitates exporting the stored *message* from the agent's memory either to an external file (specified by `file_path`) or directly into the working memory of the program (if `to_mem` is set to `True`).
- **`clear`**: This method purges all *message* from the agent's memory, essentially resetting it.
- **`size`**: This method returns the number of messages currently stored in the agent's memory.

### `TemporaryMemory`
Expand All @@ -139,7 +139,7 @@ The `TemporaryMemory` class is a concrete implementation of `MemoryBase`, provid
- **`retrieve_by_embedding`**: Retrieves `messages` that are most similar to a query, based on their embeddings. It uses a provided metric to determine the relevance and can return the top `k` most relevant messages.
- **`get_embeddings`**: Return the embeddings for all messages in memory. If a message does not have an embedding and an embedding model is provided, it will generate and store the embedding for the message.

For more details about the usage of `Memory` and `Message`, please refer to the API references.
For more details about the usage of `Memory` and `Msg`, please refer to the API references.



Expand Down
2 changes: 1 addition & 1 deletion docs/tutorial/208-distribute.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ D-->F
```

Among them, `B` and `C` can start execution simultaneously after receiving the message from `A`, and `E` can run immediately without waiting for `A`, `B`, `C,` and `D`.
By implementing each agent as an actor, an agent will automatically wait for its input `Message` before starting to execute the reply method, and multiple agents can also automatically execute `reply` at the same time if their input messages are ready, which avoids complex parallel control and makes things simple.
By implementing each agent as an actor, an agent will automatically wait for its input `Msg` before starting to execute the reply method, and multiple agents can also automatically execute `reply` at the same time if their input messages are ready, which avoids complex parallel control and makes things simple.

### Write centrally, run distributedly

Expand Down
4 changes: 2 additions & 2 deletions src/agentscope/prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def join(
accept any number and type of arguments. If prompt type is
`PromptType.STRING`, the arguments will be joined by `"\\\\n"`. If
prompt type is `PromptType.LIST`, the string arguments will be
converted to `Message` from `system`.
converted to `Msg` from `system`.
"""
# TODO: achieve the summarize function
if self.prompt_type == PromptType.STRING:
Expand Down Expand Up @@ -134,7 +134,7 @@ def join_to_str(self, *args: Any, format_map: Union[dict, None]) -> str:
return prompt_str

def join_to_list(self, *args: Any, format_map: Union[dict, None]) -> list:
"""Join prompt components to a list of `Message` objects."""
"""Join prompt components to a list of `Msg` objects."""
prompt = []
for item in args:
if isinstance(item, list):
Expand Down
2 changes: 1 addition & 1 deletion src/agentscope/utils/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def _get_timestamp(format_: str = "%Y-%m-%d %H:%M:%S") -> str:


def to_openai_dict(item: dict) -> dict:
"""Convert `Message` to `dict` for OpenAI API."""
"""Convert `Msg` to `dict` for OpenAI API."""
clean_dict = {}

if "name" in item:
Expand Down

0 comments on commit 1927d1a

Please sign in to comment.