Skip to content

Commit

Permalink
Unify the typing of the agents' reply function and update their docst…
Browse files Browse the repository at this point in the history
…rings. (#314)
  • Loading branch information
DavdGao authored Jul 2, 2024
1 parent 05b8d54 commit 401fe3a
Show file tree
Hide file tree
Showing 30 changed files with 129 additions and 99 deletions.
6 changes: 5 additions & 1 deletion docs/sphinx_doc/en/source/tutorial/104-usecase.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,13 @@ To implement your own agent, you need to inherit `AgentBase` and implement the `

```python
from agentscope.agents import AgentBase
from agentscope.message import Msg


from typing import Optional, Union, Sequence

class MyAgent(AgentBase):
def reply(self, x):
def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:
# Do something here
...
return x
Expand Down
10 changes: 5 additions & 5 deletions docs/sphinx_doc/en/source/tutorial/201-agent.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,15 @@ class AgentBase(Operator):
) -> None:

# ... [code omitted for brevity]
def observe(self, x: Union[dict, Sequence[dict]]) -> None:
def observe(self, x: Union[Msg, Sequence[Msg]]) -> 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
# response.
if self.memory:
self.memory.add(x)

def reply(self, x: dict = None) -> dict:
def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:
# The core method to be implemented by custom agents. It defines the
# logic for processing an input message and generating a suitable
# response.
Expand Down Expand Up @@ -86,7 +86,7 @@ Below, we provide usages of how to configure various agents from the AgentPool:
* **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:
def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:
# Additional processing steps can occur here

# Record the input if needed
Expand Down Expand Up @@ -142,9 +142,9 @@ service_bot = DialogAgent(**dialog_agent_config)
```python
def reply(
self,
x: dict = None,
x: Optional[Union[Msg, Sequence[Msg]]] = None,
required_keys: Optional[Union[list[str], str]] = None,
) -> dict:
) -> Msg:
# Check if there is initial data to be added to memory
if self.memory:
self.memory.add(x)
Expand Down
2 changes: 1 addition & 1 deletion docs/sphinx_doc/en/source/tutorial/203-parser.md
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ In AgentScope, we achieve post-processing by calling the `to_content`, `to_memor

```python
# ...
def reply(x: dict = None) -> None:
def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:

# ...
res = self.model(prompt, parse_func=self.parser.parse)
Expand Down
5 changes: 4 additions & 1 deletion docs/sphinx_doc/en/source/tutorial/204-service.md
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,9 @@ import json
import inspect
from agentscope.service import ServiceResponse
from agentscope.agents import AgentBase
from agentscope.message import Msg

from typing import Optional, Union, Sequence


def create_file(file_path: str, content: str = "") -> ServiceResponse:
Expand All @@ -282,7 +285,7 @@ def create_file(file_path: str, content: str = "") -> ServiceResponse:
class YourAgent(AgentBase):
# ... [omitted for brevity]

def reply(self, x: dict = None) -> dict:
def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:
# ... [omitted for brevity]

# construct a prompt to ask the agent to provide the parameters in JSON format
Expand Down
4 changes: 3 additions & 1 deletion docs/sphinx_doc/en/source/tutorial/209-prompt_opt.md
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,8 @@ from agentscope.agents import AgentBase
from agentscope.prompt import SystemPromptOptimizer
from agentscope.message import Msg

from typing import Optional, Union, Sequence

class MyAgent(AgentBase):
def __init__(
self,
Expand All @@ -411,7 +413,7 @@ class MyAgent(AgentBase):
# or model_or_model_config_name=self.model
)

def reply(self, x: dict = None) -> dict:
def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:
self.memory.add(x)

prompt = self.model.format(
Expand Down
7 changes: 6 additions & 1 deletion docs/sphinx_doc/zh_CN/source/tutorial/104-usecase.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,14 @@

```python
from agentscope.agents import AgentBase
from agentscope.message import Msg

from typing import Optional, Union, Sequence


class MyAgent(AgentBase):
def reply(self, x):

def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:
# Do something here
...
return x
Expand Down
8 changes: 4 additions & 4 deletions docs/sphinx_doc/zh_CN/source/tutorial/201-agent.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ class AgentBase(Operator):
if self.memory:
self.memory.add(x)

def reply(self, x: dict = None) -> dict:
def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:
# The core method to be implemented by custom agents. It defines the
# logic for processing an input message and generating a suitable
# response.
Expand Down Expand Up @@ -87,7 +87,7 @@ class AgentBase(Operator):
* **回复方法**`reply` 方法是处理输入消息和生成响应的主要逻辑所在

```python
def reply(self, x: dict = None) -> dict:
def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:
# Additional processing steps can occur here

# Record the input if needed
Expand Down Expand Up @@ -143,9 +143,9 @@ service_bot = DialogAgent(**dialog_agent_config)
```python
def reply(
self,
x: dict = None,
x: Optional[Union[Msg, Sequence[Msg]]] = None,
required_keys: Optional[Union[list[str], str]] = None,
) -> dict:
) -> Msg:
# Check if there is initial data to be added to memory
if self.memory:
self.memory.add(x)
Expand Down
2 changes: 1 addition & 1 deletion docs/sphinx_doc/zh_CN/source/tutorial/203-parser.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ AgentScope中,我们通过调用`to_content`,`to_memory`和`to_metadata`方

```python
# ...
def reply(x: dict = None) -> None:
def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:

# ...
res = self.model(prompt, parse_func=self.parser.parse)
Expand Down
2 changes: 1 addition & 1 deletion docs/sphinx_doc/zh_CN/source/tutorial/204-service.md
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ def create_file(file_path: str, content: str = "") -> ServiceResponse:
class YourAgent(AgentBase):
# ... [为简洁起见省略代码]

def reply(self, x: dict = None) -> dict:
def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:
# ... [为简洁起见省略代码]

# 构造提示,让代理提供 JSON 格式的参数
Expand Down
2 changes: 1 addition & 1 deletion docs/sphinx_doc/zh_CN/source/tutorial/209-prompt_opt.md
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ class MyAgent(AgentBase):
# 或是 model_or_model_config_name=self.model
)

def reply(self, x: dict = None) -> dict:
def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:
self.memory.add(x)

prompt = self.model.format(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"""A simple example of using langchain to create an assistant agent in
AgentScope."""
import os
from typing import Optional
from typing import Optional, Union, Sequence

from langchain_openai import OpenAI
from langchain.memory import ConversationBufferMemory
Expand Down Expand Up @@ -52,7 +52,7 @@ def __init__(self, name: str) -> None:
)
# [END] BY LANGCHAIN

def reply(self, x: Optional[dict] = None) -> Msg:
def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:
# [START] BY LANGCHAIN

# Generate response
Expand Down
4 changes: 2 additions & 2 deletions examples/conversation_with_swe-agent/swe_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from agentscope.message import Msg
from agentscope.exception import ResponseParsingError
from agentscope.parsers import MarkdownJsonDictParser
from typing import List, Callable
from typing import List, Callable, Optional, Union, Sequence
import json
from agentscope.service import (
ServiceFactory,
Expand Down Expand Up @@ -206,7 +206,7 @@ def step(self) -> Msg:
self.running_memory.append(str(action) + str(obs))
return msg_res

def reply(self, x: dict = None) -> dict:
def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:
action_name = None
self.main_goal = x.content
while not action_name == "exit":
Expand Down
5 changes: 3 additions & 2 deletions examples/distributed_debate/user_proxy_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,17 @@
from typing import Optional

from agentscope.agents import UserAgent
from agentscope.message import Msg


class UserProxyAgent(UserAgent):
"""User proxy agent class"""

def reply( # type: ignore[override]
self,
x: dict = None,
x: Optional[Union[Msg, Sequence[Msg]]] = None,
required_keys: Optional[Union[list[str], str]] = None,
) -> dict:
) -> Msg:
"""
Reply with `self.speak(x)`
"""
Expand Down
3 changes: 2 additions & 1 deletion examples/distributed_parallel_optimization/answerer_agent.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
"""Answerer Agent."""
from typing import Optional, Union, Sequence

from agentscope.message import Msg
from agentscope.agents import AgentBase
Expand All @@ -22,7 +23,7 @@ def __init__(
use_memory=False,
)

def reply(self, x: dict = None) -> dict:
def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:
response = load_web(
url=x.url,
keep_raw=False,
Expand Down
4 changes: 3 additions & 1 deletion examples/distributed_parallel_optimization/searcher_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
"""Searcher agent."""

from functools import partial
from typing import Optional, Union, Sequence

from agentscope.message import Msg
from agentscope.agents import AgentBase
from agentscope.service import google_search, bing_search
Expand Down Expand Up @@ -56,7 +58,7 @@ def __init__(
assert api_key is not None, "bing search requires 'api_key'"
self.search = partial(bing_search, api_key=api_key)

def reply(self, x: dict = None) -> dict:
def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:
prompt = self.model.format(
Msg(name="system", role="system", content=self.sys_prompt),
x,
Expand Down
8 changes: 5 additions & 3 deletions examples/distributed_simulation/participant.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import random
import time
import re
from typing import Optional, Union, Sequence

from loguru import logger

from agentscope.message import Msg
Expand Down Expand Up @@ -30,7 +32,7 @@ def generate_random_response(self) -> str:
time.sleep(self.sleep_time)
return str(random.randint(0, self.max_value))

def reply(self, x: dict = None) -> dict:
def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:
"""Generate a random value"""
# generate a response in content
response = self.generate_random_response()
Expand Down Expand Up @@ -74,7 +76,7 @@ def parse_value(self, txt: str) -> str:
else:
return numbers[-1]

def reply(self, x: dict = None) -> dict:
def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:
"""Generate a value by LLM"""
if self.memory:
self.memory.add(x)
Expand Down Expand Up @@ -134,7 +136,7 @@ def __init__(
for config in part_configs
]

def reply(self, x: dict = None) -> dict:
def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:
results = []
msg = Msg(
name="moderator",
Expand Down
13 changes: 7 additions & 6 deletions examples/game_gomoku/code/board_agent.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
"""A board agent class that can host a Gomoku game, and a function to
convert the board to an image."""
from typing import Optional, Union, Sequence

import numpy as np
from matplotlib import pyplot as plt, patches
Expand Down Expand Up @@ -81,36 +82,36 @@ def __init__(self, name: str) -> None:
# Record the status of the game
self.game_end = False

def reply(self, x: dict = None) -> dict:
def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:
if x is None:
# Beginning of the game
content = (
"Welcome to the Gomoku game! Black player goes first. "
"Please make your move."
)
else:
row, col = x["content"]
row, col = x.content

self.assert_valid_move(row, col)

# change the board
self.board[row, col] = NAME_TO_PIECE[x["name"]]
self.board[row, col] = NAME_TO_PIECE[x.name]

# check if the game ends
if self.check_draw():
content = "The game ends in a draw!"
self.game_end = True
else:
next_player_name = (
NAME_BLACK if x["name"] == NAME_WHITE else NAME_WHITE
NAME_BLACK if x.name == NAME_WHITE else NAME_WHITE
)
content = CURRENT_BOARD_PROMPT_TEMPLATE.format(
board=self.board2text(),
player=next_player_name,
)

if self.check_win(row, col, NAME_TO_PIECE[x["name"]]):
content = f"The game ends, {x['name']} wins!"
if self.check_win(row, col, NAME_TO_PIECE[x.name]):
content = f"The game ends, {x.name} wins!"
self.game_end = True

msg_host = Msg(self.name, content, role="assistant")
Expand Down
4 changes: 2 additions & 2 deletions examples/game_gomoku/code/gomoku_agent.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
"""A Gomoku agent that can play the game with another agent."""

from typing import Optional
from typing import Optional, Union, Sequence

import json

Expand Down Expand Up @@ -48,7 +48,7 @@ def __init__(

self.memory.add(Msg("system", sys_prompt, role="system"))

def reply(self, x: Optional[dict] = None) -> dict:
def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:
if self.memory:
self.memory.add(x)

Expand Down
Loading

0 comments on commit 401fe3a

Please sign in to comment.