0


LangChain 27 AI Agents角色扮演多轮对话解决问题CAMEL

LangChain系列文章

  1. LangChain 实现给动物取名字,
  2. LangChain 2模块化prompt template并用streamlit生成网站 实现给动物取名字
  3. LangChain 3使用Agent访问Wikipedia和llm-math计算狗的平均年龄
  4. LangChain 4用向量数据库Faiss存储,读取YouTube的视频文本搜索Indexes for information retrieve
  5. LangChain 5易速鲜花内部问答系统
  6. LangChain 6根据图片生成推广文案HuggingFace中的image-caption模型
  7. LangChain 7 文本模型TextLangChain和聊天模型ChatLangChain
  8. LangChain 8 模型Model I/O:输入提示、调用模型、解析输出
  9. LangChain 9 模型Model I/O 聊天提示词ChatPromptTemplate, 少量样本提示词FewShotPrompt
  10. LangChain 10思维链Chain of Thought一步一步的思考 think step by step
  11. LangChain 11实现思维树Implementing the Tree of Thoughts in LangChain’s Chain
  12. LangChain 12调用模型HuggingFace中的Llama2和Google Flan t5
  13. LangChain 13输出解析Output Parsers 自动修复解析器
  14. LangChain 14 SequencialChain链接不同的组件
  15. LangChain 15根据问题自动路由Router Chain确定用户的意图
  16. LangChain 16 通过Memory记住历史对话的内容
  17. LangChain 17 LangSmith调试、测试、评估和监视基于任何LLM框架构建的链和智能代理
  18. LangChain 18 LangSmith监控评估Agent并创建对应的数据库
  19. LangChain 19 Agents Reason+Action自定义agent处理OpenAI的计算缺陷
  20. LangChain 20 Agents调用google搜索API搜索市场价格 Reason Action:在语言模型中协同推理和行动
  21. LangChain 21 Agents自问自答与搜索 Self-ask with search
  22. LangChain 22 LangServe用于一键部署LangChain应用程序
  23. LangChain 23 Agents中的Tools用于增强和扩展智能代理agent的功能
  24. LangChain 24 对本地文档的搜索RAG检索增强生成Retrieval-augmented generation
  25. LangChain 25: SQL Agent通过自然语言查询数据库sqlite
  26. LangChain 26: 回调函数callbacks打印prompt verbose调用在这里插入图片描述

1. AI Agents角色扮演

对话和基于聊天的语言模型的快速发展已经取得了在复杂任务解决方面的显著进展。然而,它们的成功在很大程度上依赖于人类输入来引导对话,这可能具有挑战性且耗时。本文探讨了构建可扩展技术以促进沟通代理之间的自主合作,并洞察其“认知”过程的潜力。为了解决实现自主合作的挑战,我们提出了一个名为角色扮演的新型沟通代理框架。我们的方法涉及使用启发式提示来引导聊天代理完成任务,同时保持与人类意图的一致性。我们展示了角色扮演如何用于生成对话数据,以研究聊天代理的行为和能力,为研究对话语言模型提供了宝贵的资源。我们的贡献包括引入了一个新型的沟通代理框架,提供了一个可扩展的方法来研究多代理系统的合作行为和能力,并公开了我们的库以支持对沟通代理及其他领域的研究。

在这里插入图片描述

这篇论文《Communicative Agents for Software Development](https://arxiv.org/pdf/2303.17760.pdf》介绍了CHATDEV,这是一个基于大型语言模型(LLM)的虚拟聊天驱动的软件开发框架。CHATDEV采用瀑布模型,将软件开发分为设计、编码、测试和文档编写等阶段。它整合了多个代理角色,如程序员、审查员和测试员,促进协作对话和高效工作流程。该框架简化了软件开发流程,无需在每个阶段使用专门的模型,并通过思考指令机制解决了代码幻觉等挑战。实验结果显示了CHATDEV在软件生成方面的效率和成本效益,突出了将LLM集成到软件开发中的潜力。

2. 代码实现

这段代码使用colorama和camel库来创建一个基于角色扮演的交互式会话,目的是设计一个自定义的游戏。下面是代码的详细解释:

from colorama import Fore  # 从colorama导入Fore模块,用于终端文本的彩色显示from camel.societies import RolePlaying  # 导入RolePlaying类,用于角色扮演游戏from camel.utils import print_text_animated  # 导入函数以动画形式输出文本# 设定游戏设计任务的提示
task_prompt ="Design a custom game using pygame"print(Fore.YELLOW +f"Original task prompt:\n{task_prompt}\n")# 用黄色打印原始任务提示# 初始化一个角色扮演会话,指定角色和任务提示
role_play_session = RolePlaying("Computer Programmer","Gamer", task_prompt=task_prompt)print(Fore.CYAN +f"Specified task prompt:\n{role_play_session.task_prompt}\n")# 用青色打印指定的任务提示# 设置聊天轮次的限制和初始化轮次计数器
chat_turn_limit, n =50,0
input_assistant_msg, _ = role_play_session.init_chat()# 开始聊天会话并获得助手的初始消息# 循环管理用户和助手之间的聊天轮次while n < chat_turn_limit:
    n +=1# 轮次计数器递增# 在角色扮演中处理一步,获得助手和用户的响应
    assistant_response, user_response = role_play_session.step(input_assistant_msg)# 动画打印用户和助手的响应
    print_text_animated(Fore.BLUE +f"AI User:\n\n{user_response.msg.content}\n")
    print_text_animated(Fore.GREEN +"AI Assistant:\n\n"f"{assistant_response.msg.content}\n")# 检查用户响应中是否标记了任务完成if"CAMEL_TASK_DONE"in user_response.msg.content:break# 如果任务完成则退出循环# 更新下一轮的助手消息
    input_assistant_msg = assistant_response.msg

输出结果:

Original task prompt:
Design a custom game using pygame

Specified task prompt:
Create a 2D side-scrolling adventure game using Pygame. The game should feature a courageous protagonist navigating through a mysterious, enchanted forest filled with magical creatures and obstacles. Incorporate interactive elements such as puzzles, power-ups, and hidden treasures to enhance the player's experience.

AI User:

Instruction: Set up the game window with Pygame.
Input: None

AI Assistant:

Solution: 
To set up the game window with Pygame, you can use the following code:

```python
import pygame

# Initialize Pygame
pygame.init()# Set up the game window
screen_width =800
screen_height =600screen= pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Enchanted Forest Adventure")# Game loop
running = True
while running:
    foreventin pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Update the display
    pygame.display.update()# Quit Pygame
pygame.quit()

This code initializes Pygame, sets up the game window with a specified width and height, sets the window caption, and creates a game loop to handle events and update the display. When the user closes the window, the game loop ends and Pygame is quit.

Next request.

AI User:

Instruction: Create a protagonist character for the game.
Input: None

AI Assistant:

Solution:
To create a protagonist character for the game, you can use an image for the character and load it into Pygame. Here’s an example of how to do this:

import pygame

# Initialize Pygame
pygame.init()# Set up the game window
screen_width =800
screen_height =600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Enchanted Forest Adventure")# Load the protagonist character image
protagonist_image = pygame.image.load('protagonist.png')
protagonist_x =50# Initial x position of the protagonist
protagonist_y =300# Initial y position of the protagonist# Game loop
running =Truewhile running:for event in pygame.event.get():if event.type== pygame.QUIT:
            running =False# Draw the protagonist character on the screen
    screen.blit(protagonist_image,(protagonist_x, protagonist_y))# Update the display
    pygame.display.update()# Quit Pygame
pygame.quit()

In this code, we load the protagonist character image using

pygame.image.load()

, specify the initial position of the protagonist, and then draw the character on the screen within the game loop.

Next request.

AI User:

Instruction: Implement movement controls for the protagonist character.
Input: None

AI Assistant:

Solution:
To implement movement controls for the protagonist character, you can use keyboard input to move the character left and right. Here’s an example of how to do this:

import pygame

# Initialize Pygame
pygame.init()# Set up the game window
screen_width =800
screen_height =600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Enchanted Forest Adventure")# Load the protagonist character image
protagonist_image = pygame.image.load('protagonist.png')
protagonist_x =50# Initial x position of the protagonist
protagonist_y =300# Initial y position of the protagonist
protagonist_speed =5# Speed of protagonist movement# Game loop
running =Truewhile running:for event in pygame.event.get():if event.type== pygame.QUIT:
            running =False# Get the state of the keyboard
    keys = pygame.key.get_pressed()# Move the protagonist based on the keyboard inputif keys[pygame.K_LEFT]:
        protagonist_x -= protagonist_speed
    if keys[pygame.K_RIGHT]:
        protagonist_x += protagonist_speed

    # Draw the protagonist character on the screen
    screen.blit(protagonist_image,(protagonist_x, protagonist_y))# Update the display
    pygame.display.update()# Quit Pygame
pygame.quit()

In this code, we use

pygame.key.get_pressed()

to get the state of the keyboard and then move the protagonist character left or right based on the arrow key input within the game loop.

Next request.

AI User:

Instruction: Add a background image to the game window.
Input: None

AI Assistant:

Solution:
To add a background image to the game window, you can load an image and draw it on the screen behind the game elements. Here’s an example of how to do this:

import pygame

# Initialize Pygame
pygame.init()# Set up the game window
screen_width =800
screen_height =600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Enchanted Forest Adventure")# Load the background image
background_image = pygame.image.load('background.png')# Load the protagonist character image
protagonist_image = pygame.image.load('protagonist.png')
protagonist_x =50# Initial x position of the protagonist
protagonist_y =300# Initial y position of the protagonist
protagonist_speed =5# Speed of protagonist movement# Game loop
running =Truewhile running:for event in pygame.event.get():if event.type== pygame.QUIT:
            running =False# Draw the background image on the screen
    screen.blit(background_image,(0,0))# Draw the protagonist character on the screen
    screen.blit(protagonist_image,(protagonist_x, protagonist_y))# Update the display
    pygame.display.update()# Quit Pygame
pygame.quit()

In this code, we load the background image using

pygame.image.load()

and then draw it on the screen before drawing the protagonist character. This creates the effect of a background image behind the game elements.

Next request.

AI User:

Instruction: Create a class for magical creatures in the game.
Input: None

AI Assistant:

Solution:
To create a class for magical creatures in the game, you can define a class that represents the magical creatures with attributes and methods to handle their behavior. Here’s an example of how to do this:

import pygame

classMagicalCreature:def__init__(self, x, y, image_path, speed):
        self.x = x
        self.y = y
        self.image = pygame.image.load(image_path)
        self.speed = speed

    defmove(self):# Implement the movement behavior of the magical creaturepassdefdraw(self, screen):# Draw the magical creature on the screen
        screen.blit(self.image,(self.x, self.y))# Example usage
creature = MagicalCreature(200,400,'creature.png',3)

In this code, we define a

MagicalCreature

class with an

__init__

method to initialize the creature’s position, image, and speed. We also include

move

and

draw

methods to handle the movement and drawing of the creature on the screen.

You can further expand the class by adding behavior methods, collision detection, and any other functionality specific to the magical creatures in your game.

Next request.

AI User:

Instruction: Integrate the magical creature class into the game loop and draw the creature on the screen.
Input: None

AI Assistant:

Solution:
To integrate the magical creature class into the game loop and draw the creature on the screen, you can create an instance of the

MagicalCreature

class and update its position within the game loop. Here’s an example of how to do this:

import pygame

classMagicalCreature:def__init__(self, x, y, image_path, speed):
        self.x = x
        self.y = y
        self.image = pygame.image.load(image_path)
        self.speed = speed

    defmove(self):# Implement the movement behavior of the magical creature
        self.x -= self.speed  # Example: Move the creature to the leftdefdraw(self, screen):# Draw the magical creature on the screen
        screen.blit(self.image,(self.x, self.y))# Initialize Pygame
pygame.init()# Set up the game window
screen_width =800
screen_height =600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Enchanted Forest Adventure")# Load the background image
background_image = pygame.image.load('background.png')# Create a magical creature
creature = MagicalCreature(600,400,'creature.png',3)# Game loop
running =Truewhile running:for event in pygame.event.get():if event.type== pygame.QUIT:
            running =False# Draw the background image on the screen
    screen.blit(background_image,(0,0))# Move and draw the magical creature
    creature.move()
    creature.draw(screen)# Update the display
    pygame.display.update()# Quit Pygame
pygame.quit()

In this code, we integrate the

MagicalCreature

class by creating an instance of the class and then calling its

move

and

draw

methods within the game loop. This allows the magical creature to move and be drawn on the screen.

Next request.

AI User:

Instruction: Add collision detection between the protagonist character and the magical creature.
Input: None

AI Assistant:

Solution:
To add collision detection between the protagonist character and the magical creature, you can check for collisions between their bounding rectangles. Here’s an example of how to do this:

import pygame
import sys

classMagicalCreature:# ... (previous MagicalCreature class code)# Initialize Pygame
pygame.init()# Set up the game window
screen_width =800
screen_height =600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Enchanted Forest Adventure")# Load the background image
background_image = pygame.image.load('background.png')# Load the protagonist character image
protagonist_image = pygame.image.load('protagonist.png')
protagonist_x =50
protagonist_y =300
protagonist_speed =5# Create a magical creature
creature = MagicalCreature(600,400,'creature.png',3)# Game loop
running =Truewhile running:for event in pygame.event.get():if event.type== pygame.QUIT:
            running =False# Move the protagonist based on the keyboard input
    keys = pygame.key.get_pressed()if keys[pygame.K_LEFT]:
        protagonist_x -= protagonist_speed
    if keys[pygame.K_RIGHT]:
        protagonist_x += protagonist_speed

    # Draw the background image on the screen
    screen.blit(background_image,(0,0))# Move and draw the magical creature
    creature.move()
    creature.draw(screen)# Draw the protagonist character on the screen
    screen.blit(protagonist_image,(protagonist_x, protagonist_y))# Perform collision detection
    protagonist_rect = protagonist_image.get_rect(topleft=(protagonist_x, protagonist_y))
    creature_rect = creature.image.get_rect(topleft=(creature.x, creature.y))if protagonist_rect.colliderect(creature_rect):print("Collision detected!")# Replace with your collision handling logic# Update the display
    pygame.display.update()# Quit Pygame
pygame.quit()
sys.exit()

In this code, we use the

colliderect

method to check for collisions between the bounding rectangles of the protagonist character and the magical creature. When a collision is detected, you can implement your specific collision handling logic, such as reducing the protagonist’s health or triggering a game event.

Next request.

AI User:

<CAMEL_TASK_DONE>

AI Assistant:

Great! The collision detection between the protagonist character and the magical creature has been successfully implemented. If you have any more tasks related to your game development, feel free to ask!


# 参考
* https://github.com/camel-ai/camel
* https://colab.research.google.com/drive/1AzP33O8rnMW__7ocWJhVBXjKziJXPtim?usp=sharing#scrollTo=-IhYiAWDme66
* https://arxiv.org/pdf/2303.17760.pdf

本文转载自: https://blog.csdn.net/zgpeace/article/details/134962116
版权归原作者 AI架构师易筋 所有, 如有侵权,请联系我们删除。

“LangChain 27 AI Agents角色扮演多轮对话解决问题CAMEL”的评论:

还没有评论