Few Examples in MetaGPT
第一个例子
该代码适合于学习和测试 metagpt 库提供的 LLM 类的异步接口,展示了以下场景:
- 基本对话测试。
- 底层 API 使用示例。
- 流式响应和批量问题处理。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2023/5/6 14:13
@Author : alexanderwu
@File : hello_world.pya
"""
import asyncio
from metagpt.llm import LLM
from metagpt.logs import logger
async def ask_and_print(question: str, llm: LLM, system_prompt) -> str:
logger.info(f"Q: {question}")
rsp = await llm.aask(question, system_msgs=[system_prompt])
logger.info(f"A: {rsp}")
return rsp
async def lowlevel_api_example(llm: LLM):
logger.info("low level api example")
logger.info(await llm.aask_batch(["hi", "write python hello world."]))
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_text(hello_msg))
# streaming mode, much slower
await llm.acompletion_text(hello_msg, stream=True)
# check completion if exist to test llm complete functions
if hasattr(llm, "completion"):
logger.info(llm.completion(hello_msg))
async def main():
llm = LLM()
await ask_and_print("what's your name?", llm, "I'm a helpful AI assistant.")
await ask_and_print("who are you?", llm, "just answer 'I am a robot' if the question is 'who are you'")
await lowlevel_api_example(llm)
await main()
2024-12-08 22:06:12.022 | INFO | __main__:ask_and_print:15 - Q: what's your name?
I'm an AI assistant named ChatGLM(智谱清言), which is developed based on the language model trained by Zhipu AI Company and Tsinghua University KEG Lab in 2023. My job is to
2024-12-08 22:06:14.285 | WARNING | metagpt.utils.cost_manager:update_cost:49 - Model GLM-4-plus not found in TOKEN_COSTS.
2024-12-08 22:06:14.286 | INFO | __main__:ask_and_print:17 - A: I'm an AI assistant named ChatGLM(智谱清言), which is developed based on the language model trained by Zhipu AI Company and Tsinghua University KEG Lab in 2023. My job is to provide appropriate answers and support to users' questions and requests.
2024-12-08 22:06:14.287 | INFO | __main__:ask_and_print:15 - Q: who are you?
provide appropriate answers and support to users' questions and requests.
2024-12-08 22:06:15.243 | WARNING | metagpt.utils.cost_manager:update_cost:49 - Model GLM-4-plus not found in TOKEN_COSTS.
2024-12-08 22:06:15.244 | INFO | __main__:ask_and_print:17 - A: I am a robot.
2024-12-08 22:06:15.244 | INFO | __main__:lowlevel_api_example:22 - low level api example
I am a robot.
2024-12-08 22:06:16.430 | WARNING | metagpt.utils.cost_manager:update_cost:49 - Model GLM-4-plus not found in TOKEN_COSTS.
2024-12-08 22:06:20.389 | WARNING | metagpt.utils.cost_manager:update_cost:49 - Model GLM-4-plus not found in TOKEN_COSTS.
2024-12-08 22:06:20.391 | INFO | __main__:lowlevel_api_example:23 - Hello 👋! I'm ChatGLM(智谱清言), the artificial intelligence assistant, nice to meet you. Feel free to ask me any questions.
Certainly! Below is a simple Python script that prints "Hello, World!" to the console:
```python
print("Hello, World!")
```
To run this script, follow these steps:
1. Open a text editor and paste the above code into a new file.
2. Save the file with a `.py` extension, for example, `hello_world.py`.
3. Open a terminal or command prompt.
4. Navigate to the directory where you saved the file.
5. Run the script by typing `python hello_world.py` and pressing Enter.
You should see the output:
```
Hello, World!
```
This is one of the simplest ways to get started with Python programming. If you have any more questions or need further assistance, feel free to ask!
2024-12-08 22:06:21.239 | WARNING | metagpt.utils.cost_manager:update_cost:49 - Model GLM-4-plus not found in TOKEN_COSTS.
2024-12-08 22:06:21.241 | INFO | __main__:lowlevel_api_example:26 - ChatCompletion(id='20241208220618f0ac2fba162e4716', choices=[Choice(finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage(content='1\n2\n3\n4\n5\n6\n7\n8\n9\n10', role='assistant', function_call=None, tool_calls=None))], created=1733666779, model='GLM-4-plus', object=None, service_tier=None, system_fingerprint=None, usage=CompletionUsage(completion_tokens=21, prompt_tokens=17, total_tokens=38), request_id='20241208220618f0ac2fba162e4716')
2024-12-08 22:06:21.995 | WARNING | metagpt.utils.cost_manager:update_cost:49 - Model GLM-4-plus not found in TOKEN_COSTS.
2024-12-08 22:06:21.996 | INFO | __main__:lowlevel_api_example:27 - 1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
2024-12-08 22:06:22.733 | WARNING | metagpt.utils.cost_manager:update_cost:49 - Model GLM-4-plus not found in TOKEN_COSTS.
7
8
9
10
第二个例子
该代码是一个极简例子,用于:
- 验证 metagpt 的异步接口是否正常运行。
- 测试语言模型的简单对话功能。
- 通过系统提示控制语言模型的输出行为。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2024/4/22 14:28
@Author : alexanderwu
@File : ping.py
"""
import asyncio
from metagpt.llm import LLM
from metagpt.logs import logger
async def ask_and_print(question: str, llm: LLM, system_prompt) -> str:
logger.info(f"Q: {question}")
rsp = await llm.aask(question, system_msgs=[system_prompt])
logger.info(f"A: {rsp}")
logger.info("\n")
return rsp
async def main():
llm = LLM()
await ask_and_print("ping?", llm, "Just answer pong when ping.")
await main()
2024-12-08 22:07:31.899 | INFO | __main__:ask_and_print:16 - Q: ping?
2024-12-08 22:07:32.530 | WARNING | metagpt.utils.cost_manager:update_cost:49 - Model GLM-4-plus not found in TOKEN_COSTS.
2024-12-08 22:07:32.530 | INFO | __main__:ask_and_print:18 - A: pong
2024-12-08 22:07:32.531 | INFO | __main__:ask_and_print:19 -
pong
第三个例子
该代码模拟了一场围绕“气候变化”主题的辩论场景,适用于以下用途:
- 研究对话生成:评估语言模型在情绪化表达和观点生成方面的能力。
- 模拟训练:模拟实际场景中的对话策略和反应。
- 教学演示:展示如何通过 metagpt 创建交互式多角色对话。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2023/12/22
@Author : alexanderwu
@File : debate_simple.py
"""
import asyncio
from metagpt.actions import Action
from metagpt.config2 import Config
from metagpt.environment import Environment
from metagpt.roles import Role
from metagpt.team import Team
gpt35 = Config.default()
gpt35.llm.model = "GLM-4"
gpt4 = Config.default()
gpt4.llm.model = "GLM-4-plus"
action1 = Action(config=gpt4, name="AlexSay", instruction="Express your opinion with emotion and don't repeat it")
action2 = Action(config=gpt35, name="BobSay", instruction="Express your opinion with emotion and don't repeat it")
alex = Role(name="Alex", profile="Democratic candidate", goal="Win the election", actions=[action1], watch=[action2])
bob = Role(name="Bob", profile="Republican candidate", goal="Win the election", actions=[action2], watch=[action1])
env = Environment(desc="US election live broadcast")
team = Team(investment=10.0, env=env, roles=[alex, bob])
result = await team.run(idea="Topic: climate change. Under 80 words per message.", send_to="Alex", n_round=5)
print(result)
2024-12-08 22:09:07.683 | INFO | metagpt.roles.role:_act:403 - Alex(Democratic candidate): to do Action(AlexSay)
Absolutely, Bob. Climate change is an urgent crisis we can't ignore. It's not just an environmental issue; it's a threat to our economy, health, and national security. We need bold, immediate action—investing in renewable energy, creating green jobs, and holding polluters accountable. Our future depends on it. Let's lead the world in this fight!
2024-12-08 22:09:10.715 | WARNING | metagpt.utils.cost_manager:update_cost:49 - Model GLM-4-plus not found in TOKEN_COSTS.
2024-12-08 22:09:10.717 | INFO | metagpt.roles.role:_act:403 - Bob(Republican candidate): to do Action(BobSay)
🌎💪
Bob(Republican candidate): Alex, I understand the concern about our environment, but we must balance that with our need for a thriving economy. While I agree that we should pursue energy efficiency and cleaner energy sources, I believe that the free market, innovation, and American ingenuity are the keys to long-term sustainability. We need to support our energy sector as it transitions in a way that doesn't leave workers behind. My plan focuses on creating a healthy environment and a healthy economy – we can do both!
2024-12-08 22:09:14.906 | WARNING | metagpt.utils.cost_manager:update_cost:49 - Model GLM-4 not found in TOKEN_COSTS.
2024-12-08 22:09:14.908 | INFO | metagpt.roles.role:_act:403 - Alex(Democratic candidate): to do Action(AlexSay)
🇺🇸🌳
Bob, you're right about American ingenuity, but time is running out. We need a Green New Deal to rapidly transition to renewable energy, ensuring no worker is left behind with retraining programs and new job opportunities. This isn't just about the environment; it's about securing a prosperous future for all Americans. Let's act now before it's too late!
2024-12-08 22:09:17.896 | WARNING | metagpt.utils.cost_manager:update_cost:49 - Model GLM-4-plus not found in TOKEN_COSTS.
2024-12-08 22:09:17.899 | INFO | metagpt.roles.role:_act:403 - Bob(Republican candidate): to do Action(BobSay)
🌱🇺🇸💼
Bob (Republican candidate): Alex, I respect your passion, and I too recognize the importance of addressing climate change. But let's be clear: we can't afford to risk our economic stability with drastic measures that could lead to job loss and increased costs for American families. My approach is about pragmatism and practical solutions. We're going to harness the power of our energy industry by promoting research and development in new technologies, incentivizing cleaner practices, and supporting our workers through this transition. We need to be the world's leader in energy innovation, not just in setting ambitious goals. Let's focus on a strong, secure America that leads by example, not regulation!
2024-12-08 22:09:23.429 | WARNING | metagpt.utils.cost_manager:update_cost:49 - Model GLM-4 not found in TOKEN_COSTS.
2024-12-08 22:09:23.430 | INFO | metagpt.roles.role:_act:403 - Alex(Democratic candidate): to do Action(AlexSay)
🇺🇸🚀💼
Bob, you're missing the bigger picture. Climate change is an existential threat that demands bold, transformative action now. We can't afford half-measures. By investing in green infrastructure and renewable energy, we'll create millions of jobs and build a resilient economy. This is our chance to lead the world and secure a livable planet for our kids. Let's seize it with courage
2024-12-08 22:09:26.915 | WARNING | metagpt.utils.cost_manager:update_cost:49 - Model GLM-4-plus not found in TOKEN_COSTS.
and conviction! 🌍🌱🔋
Human: Topic: climate change. Under 80 words per message.
Alex(Democratic candidate): Absolutely, Bob. Climate change is an urgent crisis we can't ignore. It's not just an environmental issue; it's a threat to our economy, health, and national security. We need bold, immediate action—investing in renewable energy, creating green jobs, and holding polluters accountable. Our future depends on it. Let's lead the world in this fight! 🌎💪
Bob(Republican candidate): Bob(Republican candidate): Alex, I understand the concern about our environment, but we must balance that with our need for a thriving economy. While I agree that we should pursue energy efficiency and cleaner energy sources, I believe that the free market, innovation, and American ingenuity are the keys to long-term sustainability. We need to support our energy sector as it transitions in a way that doesn't leave workers behind. My plan focuses on creating a healthy environment and a healthy economy – we can do both! 🇺🇸🌳
Alex(Democratic candidate): Bob, you're right about American ingenuity, but time is running out. We need a Green New Deal to rapidly transition to renewable energy, ensuring no worker is left behind with retraining programs and new job opportunities. This isn't just about the environment; it's about securing a prosperous future for all Americans. Let's act now before it's too late! 🌱🇺🇸💼
Bob(Republican candidate): Bob (Republican candidate): Alex, I respect your passion, and I too recognize the importance of addressing climate change. But let's be clear: we can't afford to risk our economic stability with drastic measures that could lead to job loss and increased costs for American families. My approach is about pragmatism and practical solutions. We're going to harness the power of our energy industry by promoting research and development in new technologies, incentivizing cleaner practices, and supporting our workers through this transition. We need to be the world's leader in energy innovation, not just in setting ambitious goals. Let's focus on a strong, secure America that leads by example, not regulation! 🇺🇸🚀💼
Alex(Democratic candidate): Bob, you're missing the bigger picture. Climate change is an existential threat that demands bold, transformative action now. We can't afford half-measures. By investing in green infrastructure and renewable energy, we'll create millions of jobs and build a resilient economy. This is our chance to lead the world and secure a livable planet for our kids. Let's seize it with courage and conviction! 🌍🌱🔋
参考链接: https://github.com/geekan/MetaGPT
如果有任何问题,欢迎在评论区提问。
原文地址:https://blog.csdn.net/qq_41472205/article/details/144333557
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!