Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add environment modules #378

Merged
merged 197 commits into from
Oct 28, 2024
Merged
Show file tree
Hide file tree
Changes from 182 commits
Commits
Show all changes
197 commits
Select commit Hold shift + click to select a range
1d60d2b
update as_studio
pan-x-c Jul 30, 2024
7f4e920
add environment
pan-x-c Jul 30, 2024
d049bbb
add env
pan-x-c Jul 31, 2024
08bca3f
refactor env and add test
pan-x-c Aug 2, 2024
320ee62
add basic environment
pan-x-c Aug 2, 2024
be8a93e
update map environment
pan-x-c Aug 5, 2024
ee41cf3
fix pre-commit
pan-x-c Aug 5, 2024
13ec5b5
fix missing file
pan-x-c Aug 5, 2024
0995de4
fix missing file
pan-x-c Aug 5, 2024
484902f
add create env
pan-x-c Aug 5, 2024
088949c
merge main
pan-x-c Aug 5, 2024
c87ef56
rename attr
pan-x-c Aug 5, 2024
fe186ec
fix distance
pan-x-c Aug 6, 2024
3063356
add chatroom
pan-x-c Aug 6, 2024
bb23293
merge main
pan-x-c Aug 6, 2024
0aa9794
add chat room
pan-x-c Aug 6, 2024
9ce81bd
add chat room
pan-x-c Aug 6, 2024
79f5fb9
update chatroom
pan-x-c Aug 7, 2024
f77b273
remove environment module
pan-x-c Aug 7, 2024
cdffe6a
add rpc object
pan-x-c Aug 7, 2024
14c7e7b
rerwrite rpc agent with rpc object
pan-x-c Aug 7, 2024
c4e4e97
Merge branch 'main' into feature/pxc/env
pan-x-c Aug 7, 2024
0eb7140
support custom func
pan-x-c Aug 8, 2024
344f1b1
rename to env
pan-x-c Aug 8, 2024
5781fa0
merge rpc server launcher func into rpc object
pan-x-c Aug 8, 2024
449eb06
update serialize and deserialize
pan-x-c Aug 8, 2024
acbfbb0
pass all test
pan-x-c Aug 8, 2024
65895bd
add env test
pan-x-c Aug 8, 2024
4f4d14e
add missing file
pan-x-c Aug 8, 2024
2386bb8
move environments to examples
pan-x-c Aug 9, 2024
9ff9234
support custom async func
pan-x-c Aug 9, 2024
7dc2980
rename test
pan-x-c Aug 9, 2024
1b5bde9
add two third game
pan-x-c Aug 9, 2024
633c001
add configs
pan-x-c Aug 9, 2024
69dfd50
add two third game
pan-x-c Aug 9, 2024
0eb5983
fix guess two third example
Aug 13, 2024
7e89051
add large scale simulation example
Aug 13, 2024
21377d0
add large scale simulation example
Aug 13, 2024
0572991
add large scale simulation readme
Aug 13, 2024
4548a98
fix bug of group env
Aug 13, 2024
5709f8d
fix readme
Aug 13, 2024
3e7d87f
add a simple auction simulation example for environment
PatrickG1014 Aug 13, 2024
18481dd
Merge branch 'main' into feature/pxc/env
pan-x-c Aug 14, 2024
7b6e161
update @event_func
pan-x-c Aug 14, 2024
028a3a9
refactor: update auction simulation bid logic
PatrickG1014 Aug 14, 2024
c1777f5
Merge remote-tracking branch 'p.agentscope/feature/pxc/env' into add_…
PatrickG1014 Aug 14, 2024
ef40672
update event_func usage in auction simulation example
PatrickG1014 Aug 14, 2024
a94e92f
rpcenv support eventlistener
pan-x-c Aug 15, 2024
30a069a
fix dependency
pan-x-c Aug 15, 2024
f46f8c1
Merge remote-tracking branch 'p.agentscope/feature/pxc/env' into add_…
PatrickG1014 Aug 15, 2024
95f896a
rpcenv auction simulation example
PatrickG1014 Aug 15, 2024
77c07e4
remove base64 encode/decode
pan-x-c Aug 15, 2024
ff53531
Hot fix for MonitorManager
chenyushuo Aug 15, 2024
ddf008e
Add chatroom_example.py
chenyushuo Aug 19, 2024
9f01d59
move AgentWithChatRoom to chatroom.py
chenyushuo Aug 19, 2024
bcc1ed7
add argparse
chenyushuo Aug 19, 2024
357ffbf
bug fix in chatroom example
chenyushuo Aug 19, 2024
dd4bab1
fix cross reference
pan-x-c Aug 19, 2024
41ee7e0
Merge branch 'feature/pxc/env' of https://github.com/pan-x-c/AgentSco…
chenyushuo Aug 19, 2024
bdfd999
fix cross reference
pan-x-c Aug 19, 2024
12dbe7f
Merge branch 'feature/pxc/env' of https://github.com/pan-x-c/AgentSco…
chenyushuo Aug 19, 2024
824cacf
fix cross reference
pan-x-c Aug 20, 2024
660a5b8
bug fix in chatroom example
chenyushuo Aug 20, 2024
647edd6
Merge branch 'feature/pxc/env' of https://github.com/pan-x-c/AgentSco…
chenyushuo Aug 20, 2024
753af8e
add listener for Mentioned
chenyushuo Aug 20, 2024
57cb1b1
fix serialize
pan-x-c Aug 20, 2024
dc70ca9
add studio support
chenyushuo Aug 20, 2024
e71e403
refactor placeholder
pan-x-c Aug 20, 2024
ecfb142
refactor placeholder
pan-x-c Aug 20, 2024
0c75456
Merge branch 'feature/pxc/env' of https://github.com/pan-x-c/AgentSco…
chenyushuo Aug 20, 2024
afb1bb9
speedup create agent
pan-x-c Aug 20, 2024
f7aedc4
Merge remote-tracking branch 'p.agentscope/feature/pxc/env' into add_…
PatrickG1014 Aug 20, 2024
017987b
fix create agent test
pan-x-c Aug 20, 2024
01a1ff2
add distributed auction simulation example
PatrickG1014 Aug 20, 2024
42eded5
fix linux test
Aug 20, 2024
1b8fe84
add chatroom_with_assistant_example.py
chenyushuo Aug 21, 2024
d87b4fe
Merge branch 'feature/pxc/env' of https://github.com/pan-x-c/AgentSco…
chenyushuo Aug 21, 2024
c7b8a06
add timeout to ChatRoomAgentWithAssistant
chenyushuo Aug 22, 2024
2ca23f3
replace asyncio with threading
chenyushuo Aug 22, 2024
72ca22f
add README.md for chatroom
chenyushuo Aug 22, 2024
e4e95c4
update README.md for chatroom
chenyushuo Aug 22, 2024
455330d
add redis result pool
pan-x-c Aug 26, 2024
1ca8668
reuse grpc channel
pan-x-c Aug 26, 2024
c40d74b
fix dependency
pan-x-c Aug 26, 2024
182a0ca
update redis
pan-x-c Aug 27, 2024
8abc671
add todo
pan-x-c Aug 27, 2024
7590d34
Merge branch 'main' into feature/pxc/redis
pan-x-c Aug 28, 2024
e132805
merge main
pan-x-c Aug 28, 2024
84b9286
merge main
pan-x-c Aug 28, 2024
9f13ed6
merge main
pan-x-c Aug 29, 2024
7c94944
test redis instance exists
pan-x-c Aug 29, 2024
50c4576
test redis instance exists
pan-x-c Aug 29, 2024
05213ca
add todo
pan-x-c Aug 29, 2024
f450e86
remove rpc_agent and rpc_env
pan-x-c Aug 29, 2024
ae39d56
finish async
pan-x-c Aug 29, 2024
67dcd4b
add async pool test
pan-x-c Aug 29, 2024
0347e09
add async pool test
pan-x-c Aug 29, 2024
66bd2e8
Merge branch 'main' into feature/pxc/env
pan-x-c Aug 29, 2024
9942c35
fix test
pan-x-c Aug 29, 2024
0fd1a7f
support set agent id
pan-x-c Aug 29, 2024
92791dd
update doc
pan-x-c Aug 30, 2024
d105b04
add sync_func
pan-x-c Aug 30, 2024
a972b23
remove set start method
pan-x-c Aug 30, 2024
43ef94f
update tutorial
pan-x-c Aug 30, 2024
6592014
fix vllm script
pan-x-c Aug 30, 2024
67abf3c
finish zh tutorial
pan-x-c Sep 2, 2024
3194420
finish english tutorial
pan-x-c Sep 2, 2024
2e5db8d
fix linux test
pan-x-c Sep 2, 2024
c4195e7
fix large scale simulation example
pan-x-c Sep 2, 2024
cd2f70c
Merge branch 'feature/pxc/env' of https://github.com/pan-x-c/AgentSco…
chenyushuo Sep 2, 2024
e2e7999
fix grpc fork comp
pan-x-c Sep 2, 2024
6d520c2
Merge branch 'feature/pxc/env' of https://github.com/pan-x-c/AgentSco…
chenyushuo Sep 3, 2024
673f1b6
Merge branch 'main' into feature/pxc/env
pan-x-c Sep 3, 2024
2d0dbab
Merge branch 'feature/pxc/env' of github.com:pan-x-c/AgentScope into …
pan-x-c Sep 3, 2024
145c4ba
rename rpc agent client to rpc client
pan-x-c Sep 3, 2024
b796d90
Add RpcService
chenyushuo Sep 3, 2024
2ef1c89
Add RpcService
chenyushuo Sep 3, 2024
693b516
Add RpcService
chenyushuo Sep 3, 2024
0a2fe7e
Add example for parallel service
chenyushuo Sep 4, 2024
f1e027f
Add example for parallel service
chenyushuo Sep 4, 2024
3ae2aef
Merge branch 'feature/pxc/env' of https://github.com/pan-x-c/AgentSco…
chenyushuo Sep 5, 2024
9808caf
fix in parallel service
chenyushuo Sep 5, 2024
5d3bd26
fix bug alloc server
pan-x-c Sep 5, 2024
5255915
Merge branch 'feature/pxc/env' of https://github.com/pan-x-c/AgentSco…
chenyushuo Sep 5, 2024
6e4531f
fix bug alloc server
pan-x-c Sep 5, 2024
bf9c7bb
Merge branch 'feature/pxc/env' of https://github.com/pan-x-c/AgentSco…
chenyushuo Sep 5, 2024
4d09382
fix bug alloc server
pan-x-c Sep 5, 2024
2d096cb
Merge branch 'feature/pxc/env' of https://github.com/pan-x-c/AgentSco…
chenyushuo Sep 5, 2024
99bac7f
fix in parallel service
chenyushuo Sep 6, 2024
9cd5800
fix in parallel service
chenyushuo Sep 6, 2024
2c8675e
Update _client.py
chenyushuo Sep 6, 2024
7dc164c
code format
chenyushuo Sep 6, 2024
bee2d1f
bug fix
chenyushuo Sep 6, 2024
f0845bb
Merge pull request #8 from chenyushuo/environment
pan-x-c Sep 6, 2024
f4f67ee
merge main
pan-x-c Sep 9, 2024
b10f426
enhance error reporting
pan-x-c Sep 9, 2024
ae2ae9a
fix redis pool
pan-x-c Sep 9, 2024
acd4b77
fix set attr
pan-x-c Sep 9, 2024
8c1a668
fix redis pool
pan-x-c Sep 9, 2024
2ae6cdb
add fix
pan-x-c Sep 10, 2024
3ee5876
call in thread use pool
pan-x-c Sep 10, 2024
d9698dd
fix async test
pan-x-c Sep 12, 2024
c39e9c9
fix linux test
pan-x-c Sep 12, 2024
7a3f946
fix linux test
pan-x-c Sep 12, 2024
c54c9f1
fix pre-commit
pan-x-c Sep 12, 2024
0f98548
use timeout for update placeh
pan-x-c Sep 13, 2024
a8f4c83
server support set capacity
pan-x-c Sep 13, 2024
0b773ed
limit the capcity of sub-process mode
pan-x-c Sep 13, 2024
d52629d
update tutorial
pan-x-c Sep 13, 2024
9b9ace7
opt error report
pan-x-c Sep 13, 2024
f1838a5
fix update resp not exist
pan-x-c Sep 18, 2024
728b8bb
Merge remote-tracking branch 'p.agentscope/feature/pxc/env' into add_…
PatrickG1014 Sep 27, 2024
a1cf0ee
update env auction example
PatrickG1014 Sep 27, 2024
5b9e1a4
update experiment
pan-x-c Oct 8, 2024
bc9a0d1
add retry strategy
pan-x-c Oct 8, 2024
ea6ac25
add rpc agent test with retry strategy
pan-x-c Oct 8, 2024
7d90257
add rpc agent test with retry strategy
pan-x-c Oct 8, 2024
7e404f1
Merge branch 'main' into feature/pxc/env
pan-x-c Oct 8, 2024
987c19a
update doc
pan-x-c Oct 8, 2024
05d85af
fix test
pan-x-c Oct 8, 2024
60d0717
fix retry
pan-x-c Oct 8, 2024
089e695
fix retries
pan-x-c Oct 8, 2024
f5f3002
Merge pull request #7 from PatrickG1014/add_simple_env_example
pan-x-c Oct 8, 2024
e9c1856
simplify auction example
pan-x-c Oct 8, 2024
5d939fc
update tutorial
pan-x-c Oct 11, 2024
dc93bfc
update as_server command
pan-x-c Oct 11, 2024
d86d67c
update tutorial
pan-x-c Oct 11, 2024
2f0851f
update chatroom
pan-x-c Oct 11, 2024
fd41285
update participant
pan-x-c Oct 14, 2024
7620fbf
fix comments
pan-x-c Oct 14, 2024
39c5738
refactor chatroom
pan-x-c Oct 14, 2024
07d6c7f
refactor chatroom
pan-x-c Oct 14, 2024
4509ff4
Merge branch 'feature/pxc/chatroom_eh' into feature/pxc/env
pan-x-c Oct 14, 2024
df680e8
fix precommit
pan-x-c Oct 14, 2024
ca1085a
fix chatroom bug
pan-x-c Oct 14, 2024
5b36a3a
fix cls reference bug
pan-x-c Oct 14, 2024
e6f7dc3
fix cls info
pan-x-c Oct 15, 2024
6bf0fb5
fix chatroom example
pan-x-c Oct 16, 2024
d9f8143
fix
pan-x-c Oct 16, 2024
eb2bfc7
add persona config
pan-x-c Oct 16, 2024
a2f467c
opt retry info
pan-x-c Oct 18, 2024
d29a4ac
quick fix on chatroom
chenyushuo Oct 22, 2024
3a805e9
fix comments
pan-x-c Oct 23, 2024
e2fda5d
fix comments
pan-x-c Oct 23, 2024
c9a07ce
fix comments
pan-x-c Oct 23, 2024
f7b84a3
Merge branch 'main' into feature/pxc/env
pan-x-c Oct 23, 2024
fc98f32
add notes
pan-x-c Oct 23, 2024
a50e58c
fix in chatroom
chenyushuo Oct 23, 2024
4eb9940
fix in chatroom
chenyushuo Oct 23, 2024
7d59469
fix in chatroom
chenyushuo Oct 23, 2024
c6684b1
bug fix in leave chatroom
chenyushuo Oct 23, 2024
dfa5606
bug fix in intro
chenyushuo Oct 23, 2024
84c44de
precommit fix
chenyushuo Oct 23, 2024
b11fa41
Merge pull request #10 from chenyushuo/new_env
pan-x-c Oct 23, 2024
872ffb6
update docs
pan-x-c Oct 23, 2024
d1ae655
update paper info
pan-x-c Oct 28, 2024
72aaa72
simplify env structure
pan-x-c Oct 28, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
678 changes: 360 additions & 318 deletions docs/sphinx_doc/en/source/tutorial/208-distribute.md

Large diffs are not rendered by default.

685 changes: 369 additions & 316 deletions docs/sphinx_doc/zh_CN/source/tutorial/208-distribute.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion examples/distributed_parallel_optimization/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def parse_args() -> argparse.Namespace:
model_config_name="my_model",
)
if args.use_dist:
answerer = answerer.to_dist(lazy_launch=False)
answerer = answerer.to_dist()
answerers.append(answerer)

user_agent = UserAgent()
Expand Down
2 changes: 1 addition & 1 deletion examples/distributed_simulation/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ def run_main_process(
Msg(
name="Moderator",
role="assistant",
content=f"The average value is {summ/cnt} [takes {et-st} s]",
content=f"The average value is {summ / cnt} [takes {et - st} s]",
),
)

Expand Down
55 changes: 55 additions & 0 deletions examples/environments/auction_simulation/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Simple Auction Simulation

This is a simple example of auction simulation to show the environment module of AgentScope.

## Background

This example simulates the following scenario:

Some bidders, each carrying their own money, participate in an auction. After the bidding for an item begins, they decide whether to bid a higher price after hearing the bids of others. When no one places a bid after the waiting time has elapsed, the auctioneer announces the auction results.

## How to Run

```shell
cd examples/environments/auction_simulation
python main.py
```

You can also set the following arguments:

- `bidder-num`: the number of bidders who participate in the auction.
- `agent-type`: `random` or `llm`, the agent type of bidders.
- `waiting-time`: the waiting time for the auctioneer to decide the winner.
- `use-dist`: whether to use the distributed version. (You have to shut down the simulation manually in the distributed version.)

The following is sample output:

```log
Auction: Auction starts!
Listener: Notifying the bidder bidder_0...
Listener: Notifying the bidder bidder_1...
Listener: Notifying the bidder bidder_2...
Listener: Notifying the bidder bidder_3...
Listener: Notifying the bidder bidder_4...
bidder_1: Bid 34 for oil_painting
Listener: Bidder bidder_1 bids 34 for oil_painting. Notifying Bidder bidder_0
Listener: Bidder bidder_1 bids 34 for oil_painting. Notifying Bidder bidder_2
Listener: Bidder bidder_1 bids 34 for oil_painting. Notifying Bidder bidder_3
Listener: Bidder bidder_1 bids 34 for oil_painting. Notifying Bidder bidder_4
...
bidder_1: Bid 88 for oil_painting
Listener: Bidder bidder_1 bids 88 for oil_painting. Notifying Bidder bidder_0
bidder_0: Bid 53 for oil_painting
Listener: Bidder bidder_1 bids 88 for oil_painting. Notifying Bidder bidder_2
Listener: Bidder bidder_1 bids 88 for oil_painting. Notifying Bidder bidder_3
Listener: Bidder bidder_1 bids 88 for oil_painting. Notifying Bidder bidder_4
bidder_3: Not bid for oil_painting
bidder_0: Not bid for oil_painting
bidder_3: Bid 35 for oil_painting
bidder_4: Bid 21 for oil_painting
bidder_0: Not bid for oil_painting
bidder_1: Bid 26 for oil_painting
bidder_2: Not bid for oil_painting
Auction: Auction ends!
Auction: oil_painting is sold to bidder_1 for 88
```
156 changes: 156 additions & 0 deletions examples/environments/auction_simulation/agents.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
# -*- coding: utf-8 -*-
"""The agents used to simulate an auction."""
import random
import re
import time
from typing import Optional, Sequence, Union

from env import Item

from loguru import logger
from agentscope.agents import AgentBase
from agentscope.message import Msg


class RandomBidder(AgentBase):
"""A fake bidder agent who bids randomly."""

def __init__(
self,
name: str,
money: int = 100,
not_bid_ratio: float = 0.5,
sleep_time: float = 1.0,
) -> None:
"""Initialize the bidder agent."""
super().__init__(name=name)
self.money = money
self.not_bid_ratio = not_bid_ratio
self.sleep_time = sleep_time

def generate_random_response(self, start: int = 0) -> Optional[int]:
"""Generate a random bid or not to bid."""
time.sleep(random.random() * self.sleep_time)
if random.random() < self.not_bid_ratio:
return None
return random.randint(start, self.money)

def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:
"""Generate a random value"""
item = Item.from_dict(x.content["item"])
# generate a random bid or not to bid
response = self.generate_random_response(item.opening_price)
if response is None:
self.speak(
Msg(
self.name,
content=f"Not bid for {item.name}",
role="assistant",
),
)
return Msg(self.name, content=None, role="assistant")
else:
self.speak(
Msg(
self.name,
content=f"Bid {response} for {item.name}",
role="assistant",
),
)
msg = Msg(self.name, content=response, role="assistant")
return msg


class Bidder(AgentBase):
"""The bidder agent."""

def __init__(
self,
name: str,
model_config_name: str,
money: int = 100,
) -> None:
"""Initialize the bidder agent."""
super().__init__(
name=name,
model_config_name=model_config_name,
use_memory=True,
)
self.money = money
self.prompt = Msg(
name="system",
role="system",
content="You are a bidder. You will be given an item. "
f"You have {self.money} money. "
"Please consider whether to bid for the item. "
"If you want to bid, please provide the bid value "
"(an integer between 1 and your money). "
"If you don't want to bid, please provide 0.",
)

def parse_value(self, txt: str) -> Optional[int]:
"""Parse the bid from the response."""
numbers = re.findall(r"\d+", txt)
if len(numbers) == 0:
logger.warning(
f"Fail to parse value from [{txt}], use not bidding instead.",
)
return None
elif int(numbers[-1]) > self.money:
logger.warning(
f"Try to bid more than {self.money}, "
f"use {self.money} instead.",
)
return self.money
else:
return int(numbers[-1]) if numbers[-1] != "0" else None

def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:
"""Generate a value by LLM"""

if self.memory:
self.memory.add(x)

item = Item.from_dict(x.content["item"])
bidder_name = x.content.get("bidder_name", None)
prev_bid = x.content.get("bid", None)
content = (
f"The item is {item.name} and "
f"the opening price is {item.opening_price}."
)
if bidder_name and prev_bid:
content += f"\n{bidder_name} bid {prev_bid} for the item."
bid_info = Msg("assistant", content=content, role="assistant")

# prepare prompt
prompt = self.model.format(
self.prompt,
self.memory.get_memory(),
bid_info,
)

# call llm and generate response
response = self.model(prompt).text
bid = self.parse_value(response)
msg = Msg(self.name, bid, role="assistant")
if response is None:
self.speak(
Msg(
self.name,
content=f"Not bid for {item.name}",
role="assistant",
),
)
else:
self.speak(
Msg(
self.name,
content=f"Bid {response} for {item.name}",
role="assistant",
),
)
# Record the message in memory
if self.memory:
self.memory.add(msg)

return msg
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[
{
"config_name": "model",
"model_type": "openai_chat",
"model_name": "path-to-your-model-dir",
"api_key": "EMPTY",
"client_args": {
"base_url": "http://localhost:8083/v1"
},
"generate_args": {
"temperature": 1.0
}
}
]
151 changes: 151 additions & 0 deletions examples/environments/auction_simulation/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
# -*- coding: utf-8 -*-
"""The envs used to simulate an auction."""
import time
from typing import Any, Dict, Optional
from threading import Lock

from loguru import logger

from agentscope.environment import BasicEnv, event_func
from agentscope.message import Msg


class Item:
"""The item class."""

def __init__(
self,
name: str,
opening_price: int = 5,
is_auctioned: bool = False,
) -> None:
"""Initialize the item."""
self.name = name
self.opening_price = opening_price
self.is_auctioned = is_auctioned

def to_dict(self) -> dict:
"""Convert the item to a dict."""
return {
"name": self.name,
"opening_price": self.opening_price,
"is_auctioned": self.is_auctioned,
}

@classmethod
def from_dict(cls, data: dict) -> "Item":
"""Convert the item from a dict."""
assert "name" in data
return cls(
name=data["name"],
opening_price=data.get("opening_price", 5),
is_auctioned=data.get("is_auctioned", False),
)


class Auction(BasicEnv):
"""The auction env."""

def __init__(
self,
name: str = None,
waiting_time: float = 3.0,
) -> None:
"""Initialize the auction env.

Args:
name (`str`): The name of the Auction.
waiting_time (`float`): The waiting time between bids.
"""
super().__init__(
name=name,
)
self.waiting_time = waiting_time
self.end_time = 0
self.cur_item = None
self.cur_bid_info = None
self.bid_lock = Lock()

def get_bid_info(self) -> Optional[Dict[str, Any]]:
"""Get the bid info.
Returns:
`Dict[str, Any]`: The bid info.
"""
return self.cur_bid_info

@event_func
def start(self, item: Item) -> None:
"""Start bidding for an item.
Args:
item (`Item`): The item.
"""
self.cur_item = item
self.cur_bid_info = None
self.end_time = time.time() + self.waiting_time
logger.chat(
Msg(name="Auction", role="system", content="Auction starts!"),
)

def run(self, item: Item) -> None:
"""Run bidding for an item.
Args:
item (`Item`): The item.
"""
self.start(item)
while time.time() < self.end_time:
time.sleep(1)
logger.chat(
Msg(name="Auction", role="system", content="Auction ends!"),
)
if self.cur_bid_info is None:
self.fail()
else:
self.sold()

@event_func
def bid(self, bidder_name: str, item: Item, bid: int) -> bool:
"""Bid for the auction.
Args:
bidder_name (`str`): The name of the bidder.
item (`Item`): The item.
bid (`int`): The bid of the bidder.

Returns:
`bool`: Whether the bid was successful.
"""
with self.bid_lock:
if (
self.cur_item.is_auctioned
or bid < item.opening_price
or (self.cur_bid_info and bid <= self.cur_bid_info["bid"])
):
return False
self.cur_bid_info = {"bidder": bidder_name, "bid": bid}
self.end_time = time.time() + self.waiting_time
return True

def fail(self) -> None:
"""Pass the auction. (No bid for the item)"""
self.cur_item.is_auctioned = True
logger.chat(
Msg(
name="Auction",
role="system",
content=f"{self.cur_item.name} is not sold",
),
)

def sold(self) -> None:
"""Sold the item."""
self.cur_item.is_auctioned = True
logger.chat(
Msg(
name="Auction",
role="system",
content=(
f"{self.cur_item.name} is sold to "
f"{self.cur_bid_info['bidder']} " # type: ignore[index]
f"for {self.cur_bid_info['bid']}" # type: ignore[index]
),
),
)
Loading
Loading