当前位置: 首页 > article >正文

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

如果有任何问题,欢迎在评论区提问。


http://www.kler.cn/a/428479.html

相关文章:

  • C语言操作符(上)
  • linux下使用脚本实现对进程的内存占用自动化监测
  • MySQL可直接使用的查询表的列信息
  • 再见 Crontab!Linux 定时任务的新选择!
  • Effective C++读书笔记——item22(明确变量的作用域和访问权限)
  • 汇编与逆向(一)-汇编工具简介
  • ORB-SLAM3源码学习:ImuTypes.cc:Eigen::Matrix3f RightJacobianSO3计算右雅可比矩阵
  • 跟着问题学15——GRU网络结构详解及代码实战
  • 计算机毕业设计hadoop+spark+hive图书推荐系统 豆瓣图书数据分析可视化大屏 豆瓣图书爬虫 知识图谱 图书大数据 大数据毕业设计 机器学习
  • 【集群划分】含分布式光伏的配电网集群电压控制【33节点】
  • 入门Web自动化测试之元素定位进阶技巧
  • 用二维图像渲染3D场景视频
  • 《图神经网络编程实战:开启深度学习新领域》
  • Android显示系统(08)- OpenGL ES - 图片拉伸
  • 基于拼团社交与开源链动 2+1 模式 S2B2C 商城小程序源码的营销创新策略研究
  • TokenFormer: Rethinking Transformer Scaling with Tokenized Model Parameters
  • Vant UI +Golang(gin) 上传文件
  • Connection对象,Statement对象和ResultSet对象的依赖关系 JDBC
  • 设计模式学习思路二
  • linux内核网络层学习
  • spark-operaotr
  • unity3d—demo(实现给出图集名字和图片名字生成对应的图片)
  • 腾讯云 AI 代码助手:AI Agent 构建企业新一代研发范式
  • 时频转换 | Matlab实小波变换Real wavelet transform一维数据转二维图像方法
  • 使用Jackson库美化JSON输出
  • Llama-3.1-405B-Instruct 开源体验|对比|亮点|使用|总结