refactor: pre-commit run --all-files

This commit is contained in:
莘权 马 2023-11-22 16:26:48 +08:00
parent d8adba99d4
commit cda032948f
129 changed files with 812 additions and 831 deletions

View file

@ -1,22 +1,22 @@
'''
"""
Filename: MetaGPT/examples/agent_creator.py
Created Date: Tuesday, September 12th 2023, 3:28:37 pm
Author: garylin2099
'''
"""
import re
from metagpt.const import PROJECT_ROOT, WORKSPACE_ROOT
from metagpt.actions import Action
from metagpt.const import PROJECT_ROOT, WORKSPACE_ROOT
from metagpt.logs import logger
from metagpt.roles import Role
from metagpt.schema import Message
from metagpt.logs import logger
with open(PROJECT_ROOT / "examples/build_customized_agent.py", "r") as f:
# use official example script to guide AgentCreator
MULTI_ACTION_AGENT_CODE_EXAMPLE = f.read()
class CreateAgent(Action):
class CreateAgent(Action):
PROMPT_TEMPLATE = """
### BACKGROUND
You are using an agent framework called metagpt to write agents capable of different actions,
@ -34,7 +34,6 @@ class CreateAgent(Action):
"""
async def run(self, example: str, instruction: str):
prompt = self.PROMPT_TEMPLATE.format(example=example, instruction=instruction)
# logger.info(prompt)
@ -46,13 +45,14 @@ class CreateAgent(Action):
@staticmethod
def parse_code(rsp):
pattern = r'```python(.*)```'
pattern = r"```python(.*)```"
match = re.search(pattern, rsp, re.DOTALL)
code_text = match.group(1) if match else ""
with open(WORKSPACE_ROOT / "agent_created_agent.py", "w") as f:
f.write(code_text)
return code_text
class AgentCreator(Role):
def __init__(
self,
@ -76,11 +76,11 @@ class AgentCreator(Role):
return msg
if __name__ == "__main__":
import asyncio
async def main():
agent_template = MULTI_ACTION_AGENT_CODE_EXAMPLE
creator = AgentCreator(agent_template=agent_template)

View file

@ -1,21 +1,21 @@
'''
"""
Filename: MetaGPT/examples/build_customized_agent.py
Created Date: Tuesday, September 19th 2023, 6:52:25 pm
Author: garylin2099
'''
"""
import asyncio
import re
import subprocess
import asyncio
import fire
from metagpt.actions import Action
from metagpt.logs import logger
from metagpt.roles import Role
from metagpt.schema import Message
from metagpt.logs import logger
class SimpleWriteCode(Action):
PROMPT_TEMPLATE = """
Write a python function that can {instruction} and provide two runnnable test cases.
Return ```python your_code_here ``` with NO other texts,
@ -35,7 +35,6 @@ class SimpleWriteCode(Action):
super().__init__(name, context, llm)
async def run(self, instruction: str):
prompt = self.PROMPT_TEMPLATE.format(instruction=instruction)
rsp = await self._aask(prompt)
@ -46,11 +45,12 @@ class SimpleWriteCode(Action):
@staticmethod
def parse_code(rsp):
pattern = r'```python(.*)```'
pattern = r"```python(.*)```"
match = re.search(pattern, rsp, re.DOTALL)
code_text = match.group(1) if match else rsp
return code_text
class SimpleRunCode(Action):
def __init__(self, name="SimpleRunCode", context=None, llm=None):
super().__init__(name, context, llm)
@ -61,6 +61,7 @@ class SimpleRunCode(Action):
logger.info(f"{code_result=}")
return code_result
class SimpleCoder(Role):
def __init__(
self,
@ -75,7 +76,7 @@ class SimpleCoder(Role):
logger.info(f"{self._setting}: ready to {self._rc.todo}")
todo = self._rc.todo
msg = self._rc.memory.get()[-1] # retrieve the latest memory
msg = self._rc.memory.get()[-1] # retrieve the latest memory
instruction = msg.content
code_text = await SimpleWriteCode().run(instruction)
@ -83,6 +84,7 @@ class SimpleCoder(Role):
return msg
class RunnableCoder(Role):
def __init__(
self,
@ -128,6 +130,7 @@ class RunnableCoder(Role):
await self._act()
return Message(content="All job done", role=self.profile)
def main(msg="write a function that calculates the sum of a list"):
# role = SimpleCoder()
role = RunnableCoder()
@ -135,5 +138,6 @@ def main(msg="write a function that calculates the sum of a list"):
result = asyncio.run(role.run(msg))
logger.info(result)
if __name__ == '__main__':
if __name__ == "__main__":
fire.Fire(main)

View file

@ -1,17 +1,19 @@
'''
"""
Filename: MetaGPT/examples/debate.py
Created Date: Tuesday, September 19th 2023, 6:52:25 pm
Author: garylin2099
'''
"""
import asyncio
import platform
import fire
from metagpt.software_company import SoftwareCompany
from metagpt.actions import Action, BossRequirement
from metagpt.logs import logger
from metagpt.roles import Role
from metagpt.schema import Message
from metagpt.logs import logger
from metagpt.software_company import SoftwareCompany
class ShoutOut(Action):
"""Action: Shout out loudly in a debate (quarrel)"""
@ -31,7 +33,6 @@ class ShoutOut(Action):
super().__init__(name, context, llm)
async def run(self, context: str, name: str, opponent_name: str):
prompt = self.PROMPT_TEMPLATE.format(context=context, name=name, opponent_name=opponent_name)
# logger.info(prompt)
@ -39,6 +40,7 @@ class ShoutOut(Action):
return rsp
class Trump(Role):
def __init__(
self,
@ -55,7 +57,7 @@ class Trump(Role):
async def _observe(self) -> int:
await super()._observe()
# accept messages sent (from opponent) to self, disregard own messages from the last round
self._rc.news = [msg for msg in self._rc.news if msg.send_to == self.name]
self._rc.news = [msg for msg in self._rc.news if msg.send_to == self.name]
return len(self._rc.news)
async def _act(self) -> Message:
@ -79,6 +81,7 @@ class Trump(Role):
return msg
class Biden(Role):
def __init__(
self,
@ -120,10 +123,12 @@ class Biden(Role):
return msg
async def startup(idea: str, investment: float = 3.0, n_round: int = 5,
code_review: bool = False, run_tests: bool = False):
async def startup(
idea: str, investment: float = 3.0, n_round: int = 5, code_review: bool = False, run_tests: bool = False
):
"""We reuse the startup paradigm for roles to interact with each other.
Now we run a startup of presidents and watch they quarrel. :) """
Now we run a startup of presidents and watch they quarrel. :)"""
company = SoftwareCompany()
company.hire([Biden(), Trump()])
company.invest(investment)
@ -133,7 +138,7 @@ async def startup(idea: str, investment: float = 3.0, n_round: int = 5,
def main(idea: str, investment: float = 3.0, n_round: int = 10):
"""
:param idea: Debate topic, such as "Topic: The U.S. should commit more in climate change fighting"
:param idea: Debate topic, such as "Topic: The U.S. should commit more in climate change fighting"
or "Trump: Climate change is a hoax"
:param investment: contribute a certain dollar amount to watch the debate
:param n_round: maximum rounds of the debate
@ -144,5 +149,5 @@ def main(idea: str, investment: float = 3.0, n_round: int = 10):
asyncio.run(startup(idea, investment, n_round))
if __name__ == '__main__':
if __name__ == "__main__":
fire.Fire(main)

View file

@ -19,19 +19,15 @@ async def main():
Path("../tests/data/invoices/invoice-1.pdf"),
Path("../tests/data/invoices/invoice-2.png"),
Path("../tests/data/invoices/invoice-3.jpg"),
Path("../tests/data/invoices/invoice-4.zip")
Path("../tests/data/invoices/invoice-4.zip"),
]
# The absolute path of the file
absolute_file_paths = [Path.cwd() / path for path in relative_paths]
for path in absolute_file_paths:
role = InvoiceOCRAssistant()
await role.run(Message(
content="Invoicing date",
instruct_content={"file_path": path}
))
await role.run(Message(content="Invoicing date", instruct_content={"file_path": path}))
if __name__ == '__main__':
if __name__ == "__main__":
asyncio.run(main())

View file

@ -14,11 +14,11 @@ from metagpt.logs import logger
async def main():
llm = LLM()
claude = Claude()
logger.info(await claude.aask('你好,请进行自我介绍'))
logger.info(await llm.aask('hello world'))
logger.info(await llm.aask_batch(['hi', 'write python hello world.']))
logger.info(await claude.aask("你好,请进行自我介绍"))
logger.info(await llm.aask("hello world"))
logger.info(await llm.aask_batch(["hi", "write python hello world."]))
hello_msg = [{'role': 'user', 'content': 'count from 1 to 10. split by newline.'}]
hello_msg = [{"role": "user", "content": "count from 1 to 10. split by newline."}]
logger.info(await llm.acompletion(hello_msg))
logger.info(await llm.acompletion_batch([hello_msg]))
logger.info(await llm.acompletion_batch_text([hello_msg]))
@ -27,5 +27,5 @@ async def main():
await llm.acompletion_text(hello_msg, stream=True)
if __name__ == '__main__':
if __name__ == "__main__":
asyncio.run(main())

View file

@ -12,5 +12,5 @@ async def main():
print(f"save report to {RESEARCH_PATH / f'{topic}.md'}.")
if __name__ == '__main__':
if __name__ == "__main__":
asyncio.run(main())

View file

@ -15,5 +15,5 @@ async def main():
await Searcher().run("What are some good sun protection products?")
if __name__ == '__main__':
if __name__ == "__main__":
asyncio.run(main())

View file

@ -12,7 +12,7 @@ from metagpt.roles import Sales
async def search():
store = FaissStore(DATA_PATH / 'example.json')
store = FaissStore(DATA_PATH / "example.json")
role = Sales(profile="Sales", store=store)
queries = ["Which facial cleanser is good for oily skin?", "Is L'Oreal good to use?"]
@ -22,5 +22,5 @@ async def search():
logger.info(result)
if __name__ == '__main__':
if __name__ == "__main__":
asyncio.run(search())

View file

@ -6,11 +6,12 @@ from metagpt.tools import SearchEngineType
async def main():
# Serper API
#await Searcher(engine = SearchEngineType.SERPER_GOOGLE).run(["What are some good sun protection products?","What are some of the best beaches?"])
# await Searcher(engine = SearchEngineType.SERPER_GOOGLE).run(["What are some good sun protection products?","What are some of the best beaches?"])
# SerpAPI
#await Searcher(engine=SearchEngineType.SERPAPI_GOOGLE).run("What are the best ski brands for skiers?")
# await Searcher(engine=SearchEngineType.SERPAPI_GOOGLE).run("What are the best ski brands for skiers?")
# Google API
await Searcher(engine=SearchEngineType.DIRECT_GOOGLE).run("What are the most interesting human facts?")
if __name__ == '__main__':
if __name__ == "__main__":
asyncio.run(main())

View file

@ -1,12 +1,13 @@
'''
"""
Filename: MetaGPT/examples/use_off_the_shelf_agent.py
Created Date: Tuesday, September 19th 2023, 6:52:25 pm
Author: garylin2099
'''
"""
import asyncio
from metagpt.roles.product_manager import ProductManager
from metagpt.logs import logger
from metagpt.roles.product_manager import ProductManager
async def main():
msg = "Write a PRD for a snake game"
@ -14,5 +15,6 @@ async def main():
result = await role.run(msg)
logger.info(result.content[:100])
if __name__ == '__main__':
if __name__ == "__main__":
asyncio.run(main())

View file

@ -16,6 +16,5 @@ async def main():
await role.run(topic)
if __name__ == '__main__':
if __name__ == "__main__":
asyncio.run(main())