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

AI Agents - 自动化项目:计划、评估和分配

Agents:

  • Role 角色
  • Goal 目标
  • Backstory 背景故事

Tasks:

  • Description 描述
  • Expected Output 期望输出
  • Agent 代理

Automated Project: Planning, Estimation, and Allocation

Initial Imports

1.本地文件helper.py

# Add your utilities or helper functions to this file.

import os
from dotenv import load_dotenv, find_dotenv

                                                                                                                                  
def load_env():
    _ = load_dotenv(find_dotenv())

def get_openai_api_key():
    load_env()
    openai_api_key = os.getenv("OPENAI_API_KEY")
    return openai_api_key

2. pip install crewai

3. 导入相应库

# Warning control
import warnings
warnings.filterwarnings('ignore')

# Load environment variables
from helper import load_env
load_env()

import os
import yaml
from crewai import Agent, Task, Crew

Set OpenAI Model

os.environ['OPENAI_MODEL_NAME'] = 'gpt-4o-mini'

Loading Tasks and Agents YAML files

# Define file paths for YAML configurations
files = {
    'agents': 'config/agents.yaml',
    'tasks': 'config/tasks.yaml'
}

# Load configurations from YAML files
configs = {}
for config_type, file_path in files.items():
    with open(file_path, 'r') as file:
        configs[config_type] = yaml.safe_load(file)

# Assign loaded configurations to specific variables
agents_config = configs['agents']
tasks_config = configs['tasks']

Create Pydantic Models for Structured Output

from typing import List
from pydantic import BaseModel, Field

class TaskEstimate(BaseModel):
    task_name: str = Field(..., description="Name of the task")
    estimated_time_hours: float = Field(..., description="Estimated time to complete the task in hours")
    required_resources: List[str] = Field(..., description="List of resources required to complete the task")

class Milestone(BaseModel):
    milestone_name: str = Field(..., description="Name of the milestone")
    tasks: List[str] = Field(..., description="List of task IDs associated with this milestone")

class ProjectPlan(BaseModel):
    tasks: List[TaskEstimate] = Field(..., description="List of tasks with their estimates")
    milestones: List[Milestone] = Field(..., description="List of project milestones")

Create Crew, Agents and Tasks

# Creating Agents
project_planning_agent = Agent(
  config=agents_config['project_planning_agent']
)

estimation_agent = Agent(
  config=agents_config['estimation_agent']
)

resource_allocation_agent = Agent(
  config=agents_config['resource_allocation_agent']
)

# Creating Tasks
task_breakdown = Task(
  config=tasks_config['task_breakdown'],
  agent=project_planning_agent
)

time_resource_estimation = Task(
  config=tasks_config['time_resource_estimation'],
  agent=estimation_agent
)

resource_allocation = Task(
  config=tasks_config['resource_allocation'],
  agent=resource_allocation_agent,
  output_pydantic=ProjectPlan # This is the structured output we want
)

# Creating Crew
crew = Crew(
  agents=[
    project_planning_agent,
    estimation_agent,
    resource_allocation_agent
  ],
  tasks=[
    task_breakdown,
    time_resource_estimation,
    resource_allocation
  ],
  verbose=True
)

Crew's Inputs

from IPython.display import display, Markdown

project = 'Website'
industry = 'Technology'
project_objectives = 'Create a website for a small business'
team_members = """
- John Doe (Project Manager)
- Jane Doe (Software Engineer)
- Bob Smith (Designer)
- Alice Johnson (QA Engineer)
- Tom Brown (QA Engineer)
"""
project_requirements = """
- Create a responsive design that works well on desktop and mobile devices
- Implement a modern, visually appealing user interface with a clean look
- Develop a user-friendly navigation system with intuitive menu structure
- Include an "About Us" page highlighting the company's history and values
- Design a "Services" page showcasing the business's offerings with descriptions
- Create a "Contact Us" page with a form and integrated map for communication
- Implement a blog section for sharing industry news and company updates
- Ensure fast loading times and optimize for search engines (SEO)
- Integrate social media links and sharing capabilities
- Include a testimonials section to showcase customer feedback and build trust
"""

# Format the dictionary as Markdown for a better display in Jupyter Lab
formatted_output = f"""
**Project Type:** {project}

**Project Objectives:** {project_objectives}

**Industry:** {industry}

**Team Members:**
{team_members}
**Project Requirements:**
{project_requirements}
"""
# Display the formatted output as Markdown
display(Markdown(formatted_output))

Kicking off the crew

# The given Python dictionary
inputs = {
  'project_type': project,
  'project_objectives': project_objectives,
  'industry': industry,
  'team_members': team_members,
  'project_requirements': project_requirements
}

# Run the crew
result = crew.kickoff(
  inputs=inputs
)

Usage Metrics and Costs

import pandas as pd

costs = 0.150 * (crew.usage_metrics.prompt_tokens + crew.usage_metrics.completion_tokens) / 1_000_000
print(f"Total costs: ${costs:.4f}")

# Convert UsageMetrics instance to a DataFrame
df_usage_metrics = pd.DataFrame([crew.usage_metrics.dict()])
df_usage_metrics

Result

result.pydantic.dict()

Inspect further

tasks = result.pydantic.dict()['tasks']
df_tasks = pd.DataFrame(tasks)

# Display the DataFrame as an HTML table
df_tasks.style.set_table_attributes('border="1"').set_caption("Task Details").set_table_styles(
    [{'selector': 'th, td', 'props': [('font-size', '120%')]}]
)

Inspecting Milestones

milestones = result.pydantic.dict()['milestones']
df_milestones = pd.DataFrame(milestones)

# Display the DataFrame as an HTML table
df_milestones.style.set_table_attributes('border="1"').set_caption("Task Details").set_table_styles(
    [{'selector': 'th, td', 'props': [('font-size', '120%')]}]
)


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

相关文章:

  • 怎么理解ES6 Proxy
  • 软件行业似乎要消失了
  • 闭包 - 2024最新版前端秋招面试短期突击面试题【100道】
  • 微信小程序时间弹窗——年月日时分
  • Java知识巩固(十二)
  • 晓羽扫码点餐快销版系统源码
  • JAVA的设计模式都有那些
  • ppt演示如何计时?分享2个ppt使用技巧,轻松搞定ppt计时!
  • STM32 从0开始系统学习4 编写LED驱动
  • 基于Java语言的充电桩管理系统
  • DICOM标准:DICOM服务类详解,了解存储服务类、查询/检索服务类(Q/R Service Class)和工作流管理服务类等原理
  • 无人机协同控制技术详解!
  • pdf免费压缩软件 pdf文件压缩免费软件 软件工具方法
  • 人类借助AI发现第 52 个梅森素数
  • cloak斗篷伪装下的独立站
  • 被上传文件于后端的命名策略
  • Typora 、 Minio and PicGo 图床搭建
  • uniapp 图片bug(图片为线上地址,url不变,内容更新)
  • 红黑树模拟封装map和set
  • 关于我、重生到500年前凭借C语言改变世界科技vlog.12——深入理解指针(2)
  • 【热门主题】000013 C++游戏开发全攻略
  • 青少年编程与数学 02-002 Sql Server 数据库应用 20课题、连接与ORM
  • 基于springboot+vue实现的公司财务管理系统(源码+L文+ppt)4-102
  • QT访问数据库:应用提示Driver not loaded
  • 无人机螺旋桨动平衡分析测试台
  • 了解elasticsearch