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

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_dotenvdef 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, Fieldclass 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, Markdownproject = '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 pdcosts = 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.lryc.cn/news/472924.html

相关文章:

  • Git的.gitignore文件
  • 网站安全,WAF网站保护暴力破解
  • 深度学习:梯度下降算法简介
  • SparkSQL整合Hive后,如何启动hiveserver2服务
  • 前端路由如何从0开始配置?vue-router 的使用
  • Java中的运算符【与C语言的区别】
  • 二、基础语法
  • DB-GPT系列(一):DB-GPT能帮你做什么?
  • 【Python各个击破】numpy
  • 【STM32 Blue Pill编程实例】-4位7段数码管使用
  • [进阶]java基础之集合(三)数据结构
  • 《Apache Cordova/PhoneGap 使用技巧分享》
  • SCP(Secure Copy
  • uniApp 省市区自定义数据
  • 图解Redis 06 | Hash数据类型的原理及应用场景
  • 在 Windows 系统上设置 MySQL8.0以支持远程连接
  • 四种基本的编程命名规范
  • 【前端】在 TypeScript 中使用 AbortController 取消异步请求
  • k8s知识点总结
  • 论文阅读:三星-TinyClick
  • Windows on ARM上使用sherpa-onnx实现语音识别
  • Unity 打包AB Timeline 引用丢失,错误问题
  • 【Kettle的安装与使用】使用Kettle实现mysql和hive的数据传输(使用Kettle将mysql数据导入hive、将hive数据导入mysql)
  • STM32的hal库在实现延时函数(例如:Delay_ms 等)为什么用滴答定时(Systick)而不是定时器定时中断,也不是RTC?
  • 刚刚买的域名被DNS劫持了怎么处理
  • 递归 算法专题
  • Logstash 迁移索引元数据(设置和映射)
  • 用python将pdf转成图片转换成对应的word文件
  • list(c++)
  • 51单片机STC8G串口Uart配置