首页 > 编程问答 >AI代理返回生成器对象而不是对象

AI代理返回生成器对象而不是对象

时间:2024-07-23 06:29:55浏览次数:8  
标签:python agent crewai

使用crewAI 创建游戏构建器AI 代理。我的代码没有按预期启动代理,而是返回一个对象 <crewai.project.crew_base.CrewBase..WrappedClass object at 0x1012252d0>。

我期待这样的输出:

 [DEBUG]: == Working Agent: Financial Researcher
 [INFO]: == Starting Task: You will create a game using python, these are the instructions:
    Instructions
    ------------
        {game} 

    Your Final answer must be the full python code, only the python code and nothing else.

> Entering new CrewAgentExecutor chain...

在 main.py 中我已尝试使用 str() 转换结果并添加打印语句来识别停止工作的位置:

import os
from dotenv import load_dotenv
load_dotenv()

from crewai.project import CrewBase, crew
from crewai import Crew, Process
from .tasks import GameTasks
from .agents import GameAgents


@CrewBase
class GameBuildCrew():
    tasks = GameTasks()
    agents = GameAgents()

    def __init__(self):
        print("## Welcome to the Game Crew")
        print('-------------------------------')
        self.game = input("What is the game you would like to build? What will be the mechanics?\n")

    @crew
    def crew(self) -> Crew:
        print("crew called")
        return Crew(
            agents=[
                self.agents.senior_engineer_agent(),
                self.agents.qa_engineer_agent(),
                self.agents.chief_qa_engineer_agent()
            ],
            tasks=[
                self.tasks.code_task(self.senior_engineer_agent),
                self.tasks.review_task(self.qa_engineer_agent),
                self.tasks.evaluate_task(self.chief_qa_engineer_agent)
            ],
            process=Process.sequential,
            verbose=2,
        )

    def run(self):
        print("run called")

        crew_instance = self.crew()
        result = crew_instance.kickoff()

        print("\n\n########################")
        print("## Here is the result")
        print("########################\n")
        print("final code for the game:")
        print(result)


if __name__ == '__main__':
    game_build_crew = GameBuildCrew()
    game_build_crew.run()

The issue stems from how you're interacting with the crew_instance.kickoff() method and the structure of your CrewBase subclass. Let's break it down:

  1. crew_instance.kickoff() is likely asynchronous: CrewAI likely leverages asynchronous operations for task execution, especially when dealing with potentially time-consuming agent interactions. This means kickoff() might not return the final result immediately. Instead, it could return a representation of the ongoing process (which is why you're seeing the WrappedClass object).

  2. You're attempting to print the result immediately: Your print(result) line executes right after kickoff() , without waiting for the asynchronous operations to complete.

Solution Approach:

To get the intended output, you need to adapt your code to work with CrewAI's asynchronous nature. Without knowing the specifics of crewai , here's a conceptual approach using Python's asyncio :

import asyncio
import os
from dotenv import load_dotenv

load_dotenv()

from crewai.project import CrewBase, crew
from crewai import Crew, Process
from .tasks import GameTasks
from .agents import GameAgents


@CrewBase
class GameBuildCrew:
    # ... (rest of your class code)

    async def run(self):  # Make 'run' asynchronous
        print("run called")

        crew_instance = self.crew()
        result = await crew_instance.kickoff()  # Await the result

        print("\n\n########################")
        print("## Here is the result")
        print("########################\n")
        print("final code for the game:")
        print(result)


if __name__ == "__main__":
    game_build_crew = GameBuildCrew()
    asyncio.run(game_build_crew.run())  # Run within an event loop

Explanation:

  1. async def run() : We define the run method as an asynchronous coroutine using async def . This allows us to use await inside it.

  2. await crew_instance.kickoff() : We use await to pause execution until the kickoff() method completes and provides the actual result.

  3. asyncio.run(game_build_crew.run()) : We utilize asyncio.run() to create an event loop, which is necessary for running asynchronous code.

Important Considerations:

  • CrewAI Documentation: Refer to CrewAI's documentation for the most accurate guidance on handling asynchronous operations and retrieving results.
  • Error Handling: Implement robust error handling (e.g., using try...except blocks) within your asynchronous code to catch potential exceptions during agent execution.

Let me know if you have any questions or need further assistance!

标签:python,agent,crewai
From: 78780910

相关文章

  • AWS Elastic Beanstalk chown PythonPath 错误
    我正在AWS的elasticbeanstalk上部署一个Web应用程序,遇到了同样的错误:[StageApplication].Stoprunningthecommand.Error:chown/var/app/staging/venv/bin/python:nosuchfileordirectory.我在我的环境配置中看到属性:PYTHONPATH:/var/......
  • Python:支持索引的内存对象数据库?
    我正在做一些数据整理,如果我可以将一堆字典放入内存数据库中,然后对其运行简单的查询,这会简单得多。例如,类似:people=db([{"name":"Joe","age":16},{"name":"Jane","favourite_color":"red"},])over_16=db.filter(age__g......
  • 如何构建一维数组的二维数组的特定 Python 结构?
    如何构建一维数组(即行向量)的二维数组的特定结构以满足特定我正在维护的遗留程序的结构?我可以在此结构中生成正确的内容all_measurements[:12]array([[0.,0.,0.,2.],[0.02,0.334,0.04,2.24],[0.04,0.668,0.08,2.48],...........
  • 如何使用 Python Flask 将新的咖啡馆(元素)添加到数据库(SQLite)?
    这是我的代码:@app.route("/add",methods=["POST"])defpost_new_cafe():new_cafe=Cafe(name=request.form.get("name"),map_url=request.form.get("map_url"),img_url=request.form.get("img......
  • 使用 tkinter 为 python 创建 GUI 时如何解决语法错误?
    我是一名Python初学者,决定使用tkinter制作一个小型GUI,该GUI接受用户(潜在餐馆)的3个输入,然后单击按钮后随机输出其中一家餐馆。我不断收到语法错误,并认为它与我的buttonfunc或调用它的命令有关。此代码尚未包含在GUI上输出餐厅的任何位置。任何帮助将不胜感激#Pyth......
  • 在 python 中打开 gnome 终端立即显示为僵尸
    作为背景,我正在编写一个脚本来训练多个pytorch模型。我有一个训练脚本,我希望能够在gnome终端中作为子进程运行。这样做的主要原因是我可以随时关注训练进度。如果我可能有多个GPU,我想在单独的窗口中多次运行我的训练脚本。为了实现这一点,我一直在使用popen。以下代码用于打......
  • python threading.Condition 的意外行为
    我正在尝试同步多个线程。我期望使用threading.Condition和threading.Barrier时的脚本输出大致相同,但事实并非如此。请解释一下为什么会发生这种情况。一般来说,我需要线程在一个无限循环中执行工作(一些IO操作),但是每个循环都是以主线程的权限开始的,而权限是仅在......
  • Python - 逆透视数据框
    我有一个按日期时间索引的表,每个日期时间都有多个层(中心和交货间隔):日期时间中心交货间隔结算点价格2024-01-0101:00:00休斯顿中心1......
  • 试图理解这个错误:致命的Python错误:PyEval_RestoreThread:该函数必须在持有GIL的情况下
    我有一个小型tkinter应用程序,我一直在其中实现最小的“拖放”,主要作为学习实验。我真正关心的是删除文件的文件路径。一切实际上都工作正常,直到我尝试在拖放后打包标签小部件。下面的最小工作示例。有问题的行会用注释指出。我通常不会在调试方面遇到太多麻烦,但我只是不知......
  • 如何使代码格式再次适用于 Python(Mac 上的 Visual Studio Code)?
    在Mac上,Option+Shift+F现在会显示“没有安装用于‘python’文件的格式化程序”。消息框:我尝试安装这个插件,但没有看到这种情况的变化:我已经为Python安装了这两个插件:但是正如@starball提到的,它可能已经减少了支持现在。......