Skip to content

Commit cda0329

Browse files
author
莘权 马
committed
refactor: pre-commit run --all-files
1 parent d8adba9 commit cda0329

File tree

129 files changed

+811
-830
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

129 files changed

+811
-830
lines changed

examples/agent_creator.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,22 @@
1-
'''
1+
"""
22
Filename: MetaGPT/examples/agent_creator.py
33
Created Date: Tuesday, September 12th 2023, 3:28:37 pm
44
Author: garylin2099
5-
'''
5+
"""
66
import re
77

8-
from metagpt.const import PROJECT_ROOT, WORKSPACE_ROOT
98
from metagpt.actions import Action
9+
from metagpt.const import PROJECT_ROOT, WORKSPACE_ROOT
10+
from metagpt.logs import logger
1011
from metagpt.roles import Role
1112
from metagpt.schema import Message
12-
from metagpt.logs import logger
1313

1414
with open(PROJECT_ROOT / "examples/build_customized_agent.py", "r") as f:
1515
# use official example script to guide AgentCreator
1616
MULTI_ACTION_AGENT_CODE_EXAMPLE = f.read()
1717

18-
class CreateAgent(Action):
1918

19+
class CreateAgent(Action):
2020
PROMPT_TEMPLATE = """
2121
### BACKGROUND
2222
You are using an agent framework called metagpt to write agents capable of different actions,
@@ -34,7 +34,6 @@ class CreateAgent(Action):
3434
"""
3535

3636
async def run(self, example: str, instruction: str):
37-
3837
prompt = self.PROMPT_TEMPLATE.format(example=example, instruction=instruction)
3938
# logger.info(prompt)
4039

@@ -46,13 +45,14 @@ async def run(self, example: str, instruction: str):
4645

4746
@staticmethod
4847
def parse_code(rsp):
49-
pattern = r'```python(.*)```'
48+
pattern = r"```python(.*)```"
5049
match = re.search(pattern, rsp, re.DOTALL)
5150
code_text = match.group(1) if match else ""
5251
with open(WORKSPACE_ROOT / "agent_created_agent.py", "w") as f:
5352
f.write(code_text)
5453
return code_text
5554

55+
5656
class AgentCreator(Role):
5757
def __init__(
5858
self,
@@ -76,11 +76,11 @@ async def _act(self) -> Message:
7676

7777
return msg
7878

79+
7980
if __name__ == "__main__":
8081
import asyncio
8182

8283
async def main():
83-
8484
agent_template = MULTI_ACTION_AGENT_CODE_EXAMPLE
8585

8686
creator = AgentCreator(agent_template=agent_template)

examples/build_customized_agent.py

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,21 @@
1-
'''
1+
"""
22
Filename: MetaGPT/examples/build_customized_agent.py
33
Created Date: Tuesday, September 19th 2023, 6:52:25 pm
44
Author: garylin2099
5-
'''
5+
"""
6+
import asyncio
67
import re
78
import subprocess
8-
import asyncio
99

1010
import fire
1111

1212
from metagpt.actions import Action
13+
from metagpt.logs import logger
1314
from metagpt.roles import Role
1415
from metagpt.schema import Message
15-
from metagpt.logs import logger
1616

17-
class SimpleWriteCode(Action):
1817

18+
class SimpleWriteCode(Action):
1919
PROMPT_TEMPLATE = """
2020
Write a python function that can {instruction} and provide two runnnable test cases.
2121
Return ```python your_code_here ``` with NO other texts,
@@ -35,7 +35,6 @@ def __init__(self, name="SimpleWriteCode", context=None, llm=None):
3535
super().__init__(name, context, llm)
3636

3737
async def run(self, instruction: str):
38-
3938
prompt = self.PROMPT_TEMPLATE.format(instruction=instruction)
4039

4140
rsp = await self._aask(prompt)
@@ -46,11 +45,12 @@ async def run(self, instruction: str):
4645

4746
@staticmethod
4847
def parse_code(rsp):
49-
pattern = r'```python(.*)```'
48+
pattern = r"```python(.*)```"
5049
match = re.search(pattern, rsp, re.DOTALL)
5150
code_text = match.group(1) if match else rsp
5251
return code_text
5352

53+
5454
class SimpleRunCode(Action):
5555
def __init__(self, name="SimpleRunCode", context=None, llm=None):
5656
super().__init__(name, context, llm)
@@ -61,6 +61,7 @@ async def run(self, code_text: str):
6161
logger.info(f"{code_result=}")
6262
return code_result
6363

64+
6465
class SimpleCoder(Role):
6566
def __init__(
6667
self,
@@ -75,14 +76,15 @@ async def _act(self) -> Message:
7576
logger.info(f"{self._setting}: ready to {self._rc.todo}")
7677
todo = self._rc.todo
7778

78-
msg = self._rc.memory.get()[-1] # retrieve the latest memory
79+
msg = self._rc.memory.get()[-1] # retrieve the latest memory
7980
instruction = msg.content
8081

8182
code_text = await SimpleWriteCode().run(instruction)
8283
msg = Message(content=code_text, role=self.profile, cause_by=todo)
8384

8485
return msg
8586

87+
8688
class RunnableCoder(Role):
8789
def __init__(
8890
self,
@@ -128,12 +130,14 @@ async def _react(self) -> Message:
128130
await self._act()
129131
return Message(content="All job done", role=self.profile)
130132

133+
131134
def main(msg="write a function that calculates the sum of a list"):
132135
# role = SimpleCoder()
133136
role = RunnableCoder()
134137
logger.info(msg)
135138
result = asyncio.run(role.run(msg))
136139
logger.info(result)
137140

138-
if __name__ == '__main__':
141+
142+
if __name__ == "__main__":
139143
fire.Fire(main)

examples/debate.py

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,19 @@
1-
'''
1+
"""
22
Filename: MetaGPT/examples/debate.py
33
Created Date: Tuesday, September 19th 2023, 6:52:25 pm
44
Author: garylin2099
5-
'''
5+
"""
66
import asyncio
77
import platform
8+
89
import fire
910

10-
from metagpt.software_company import SoftwareCompany
1111
from metagpt.actions import Action, BossRequirement
12+
from metagpt.logs import logger
1213
from metagpt.roles import Role
1314
from metagpt.schema import Message
14-
from metagpt.logs import logger
15+
from metagpt.software_company import SoftwareCompany
16+
1517

1618
class ShoutOut(Action):
1719
"""Action: Shout out loudly in a debate (quarrel)"""
@@ -31,14 +33,14 @@ def __init__(self, name="ShoutOut", context=None, llm=None):
3133
super().__init__(name, context, llm)
3234

3335
async def run(self, context: str, name: str, opponent_name: str):
34-
3536
prompt = self.PROMPT_TEMPLATE.format(context=context, name=name, opponent_name=opponent_name)
3637
# logger.info(prompt)
3738

3839
rsp = await self._aask(prompt)
3940

4041
return rsp
4142

43+
4244
class Trump(Role):
4345
def __init__(
4446
self,
@@ -55,7 +57,7 @@ def __init__(
5557
async def _observe(self) -> int:
5658
await super()._observe()
5759
# accept messages sent (from opponent) to self, disregard own messages from the last round
58-
self._rc.news = [msg for msg in self._rc.news if msg.send_to == self.name]
60+
self._rc.news = [msg for msg in self._rc.news if msg.send_to == self.name]
5961
return len(self._rc.news)
6062

6163
async def _act(self) -> Message:
@@ -79,6 +81,7 @@ async def _act(self) -> Message:
7981

8082
return msg
8183

84+
8285
class Biden(Role):
8386
def __init__(
8487
self,
@@ -120,10 +123,12 @@ async def _act(self) -> Message:
120123

121124
return msg
122125

123-
async def startup(idea: str, investment: float = 3.0, n_round: int = 5,
124-
code_review: bool = False, run_tests: bool = False):
126+
127+
async def startup(
128+
idea: str, investment: float = 3.0, n_round: int = 5, code_review: bool = False, run_tests: bool = False
129+
):
125130
"""We reuse the startup paradigm for roles to interact with each other.
126-
Now we run a startup of presidents and watch they quarrel. :) """
131+
Now we run a startup of presidents and watch they quarrel. :)"""
127132
company = SoftwareCompany()
128133
company.hire([Biden(), Trump()])
129134
company.invest(investment)
@@ -133,7 +138,7 @@ async def startup(idea: str, investment: float = 3.0, n_round: int = 5,
133138

134139
def main(idea: str, investment: float = 3.0, n_round: int = 10):
135140
"""
136-
:param idea: Debate topic, such as "Topic: The U.S. should commit more in climate change fighting"
141+
:param idea: Debate topic, such as "Topic: The U.S. should commit more in climate change fighting"
137142
or "Trump: Climate change is a hoax"
138143
:param investment: contribute a certain dollar amount to watch the debate
139144
:param n_round: maximum rounds of the debate
@@ -144,5 +149,5 @@ def main(idea: str, investment: float = 3.0, n_round: int = 10):
144149
asyncio.run(startup(idea, investment, n_round))
145150

146151

147-
if __name__ == '__main__':
152+
if __name__ == "__main__":
148153
fire.Fire(main)

examples/invoice_ocr.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,19 +19,15 @@ async def main():
1919
Path("../tests/data/invoices/invoice-1.pdf"),
2020
Path("../tests/data/invoices/invoice-2.png"),
2121
Path("../tests/data/invoices/invoice-3.jpg"),
22-
Path("../tests/data/invoices/invoice-4.zip")
22+
Path("../tests/data/invoices/invoice-4.zip"),
2323
]
2424
# The absolute path of the file
2525
absolute_file_paths = [Path.cwd() / path for path in relative_paths]
2626

2727
for path in absolute_file_paths:
2828
role = InvoiceOCRAssistant()
29-
await role.run(Message(
30-
content="Invoicing date",
31-
instruct_content={"file_path": path}
32-
))
29+
await role.run(Message(content="Invoicing date", instruct_content={"file_path": path}))
3330

3431

35-
if __name__ == '__main__':
32+
if __name__ == "__main__":
3633
asyncio.run(main())
37-

examples/llm_hello_world.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,11 @@
1414
async def main():
1515
llm = LLM()
1616
claude = Claude()
17-
logger.info(await claude.aask('你好,请进行自我介绍'))
18-
logger.info(await llm.aask('hello world'))
19-
logger.info(await llm.aask_batch(['hi', 'write python hello world.']))
17+
logger.info(await claude.aask("你好,请进行自我介绍"))
18+
logger.info(await llm.aask("hello world"))
19+
logger.info(await llm.aask_batch(["hi", "write python hello world."]))
2020

21-
hello_msg = [{'role': 'user', 'content': 'count from 1 to 10. split by newline.'}]
21+
hello_msg = [{"role": "user", "content": "count from 1 to 10. split by newline."}]
2222
logger.info(await llm.acompletion(hello_msg))
2323
logger.info(await llm.acompletion_batch([hello_msg]))
2424
logger.info(await llm.acompletion_batch_text([hello_msg]))
@@ -27,5 +27,5 @@ async def main():
2727
await llm.acompletion_text(hello_msg, stream=True)
2828

2929

30-
if __name__ == '__main__':
30+
if __name__ == "__main__":
3131
asyncio.run(main())

examples/research.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,5 +12,5 @@ async def main():
1212
print(f"save report to {RESEARCH_PATH / f'{topic}.md'}.")
1313

1414

15-
if __name__ == '__main__':
15+
if __name__ == "__main__":
1616
asyncio.run(main())

examples/search_google.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,5 @@ async def main():
1515
await Searcher().run("What are some good sun protection products?")
1616

1717

18-
if __name__ == '__main__':
18+
if __name__ == "__main__":
1919
asyncio.run(main())

examples/search_kb.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313

1414
async def search():
15-
store = FaissStore(DATA_PATH / 'example.json')
15+
store = FaissStore(DATA_PATH / "example.json")
1616
role = Sales(profile="Sales", store=store)
1717

1818
queries = ["Which facial cleanser is good for oily skin?", "Is L'Oreal good to use?"]
@@ -22,5 +22,5 @@ async def search():
2222
logger.info(result)
2323

2424

25-
if __name__ == '__main__':
25+
if __name__ == "__main__":
2626
asyncio.run(search())

examples/search_with_specific_engine.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,12 @@
66

77
async def main():
88
# Serper API
9-
#await Searcher(engine = SearchEngineType.SERPER_GOOGLE).run(["What are some good sun protection products?","What are some of the best beaches?"])
9+
# await Searcher(engine = SearchEngineType.SERPER_GOOGLE).run(["What are some good sun protection products?","What are some of the best beaches?"])
1010
# SerpAPI
11-
#await Searcher(engine=SearchEngineType.SERPAPI_GOOGLE).run("What are the best ski brands for skiers?")
11+
# await Searcher(engine=SearchEngineType.SERPAPI_GOOGLE).run("What are the best ski brands for skiers?")
1212
# Google API
1313
await Searcher(engine=SearchEngineType.DIRECT_GOOGLE).run("What are the most interesting human facts?")
1414

15-
if __name__ == '__main__':
15+
16+
if __name__ == "__main__":
1617
asyncio.run(main())

examples/use_off_the_shelf_agent.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,20 @@
1-
'''
1+
"""
22
Filename: MetaGPT/examples/use_off_the_shelf_agent.py
33
Created Date: Tuesday, September 19th 2023, 6:52:25 pm
44
Author: garylin2099
5-
'''
5+
"""
66
import asyncio
77

8-
from metagpt.roles.product_manager import ProductManager
98
from metagpt.logs import logger
9+
from metagpt.roles.product_manager import ProductManager
10+
1011

1112
async def main():
1213
msg = "Write a PRD for a snake game"
1314
role = ProductManager()
1415
result = await role.run(msg)
1516
logger.info(result.content[:100])
1617

17-
if __name__ == '__main__':
18+
19+
if __name__ == "__main__":
1820
asyncio.run(main())

examples/write_tutorial.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,5 @@ async def main():
1616
await role.run(topic)
1717

1818

19-
if __name__ == '__main__':
19+
if __name__ == "__main__":
2020
asyncio.run(main())
21-

metagpt/actions/action_output.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,21 +23,20 @@ def __init__(self, content: str, instruct_content: BaseModel):
2323
def create_model_class(cls, class_name: str, mapping: Dict[str, Type]):
2424
new_class = create_model(class_name, **mapping)
2525

26-
@validator('*', allow_reuse=True)
26+
@validator("*", allow_reuse=True)
2727
def check_name(v, field):
2828
if field.name not in mapping.keys():
29-
raise ValueError(f'Unrecognized block: {field.name}')
29+
raise ValueError(f"Unrecognized block: {field.name}")
3030
return v
3131

3232
@root_validator(pre=True, allow_reuse=True)
3333
def check_missing_fields(values):
3434
required_fields = set(mapping.keys())
3535
missing_fields = required_fields - set(values.keys())
3636
if missing_fields:
37-
raise ValueError(f'Missing fields: {missing_fields}')
37+
raise ValueError(f"Missing fields: {missing_fields}")
3838
return values
3939

4040
new_class.__validator_check_name = classmethod(check_name)
4141
new_class.__root_validator_check_missing_fields = classmethod(check_missing_fields)
4242
return new_class
43-

0 commit comments

Comments
 (0)