S3WriterTool

描述

S3WriterTool 用于将内容写入 Amazon S3 存储桶中的文件。此工具允许 CrewAI 代理在 S3 中创建或更新文件,非常适合需要将数据、配置文件或任何其他内容存储到 AWS S3 存储的工作流程。

安装

要使用此工具,您需要安装所需的依赖项

uv add boto3

入门步骤

要有效使用 S3WriterTool,请按照以下步骤操作

  1. 安装依赖项:使用上述命令安装所需的软件包。
  2. 配置 AWS 凭证:将您的 AWS 凭证设置为环境变量。
  3. 初始化工具:创建一个工具实例。
  4. 指定 S3 路径和内容:提供您要写入文件的 S3 路径以及要写入的内容。

示例

以下示例演示了如何使用 S3WriterTool 将内容写入 S3 存储桶中的文件

代码
from crewai import Agent, Task, Crew
from crewai_tools.aws.s3 import S3WriterTool

# Initialize the tool
s3_writer_tool = S3WriterTool()

# Define an agent that uses the tool
file_writer_agent = Agent(
    role="File Writer",
    goal="Write content to files in S3 buckets",
    backstory="An expert in storing and managing files in cloud storage.",
    tools=[s3_writer_tool],
    verbose=True,
)

# Example task to write a report
write_task = Task(
    description="Generate a summary report of the quarterly sales data and save it to {my_bucket}.",
    expected_output="Confirmation that the report was successfully saved to S3.",
    agent=file_writer_agent,
)

# Create and run the crew
crew = Crew(agents=[file_writer_agent], tasks=[write_task])
result = crew.kickoff(inputs={"my_bucket": "s3://my-bucket/reports/quarterly-summary.txt"})

参数

当代理使用 S3WriterTool 时,它接受以下参数

  • file_path:必需。S3 文件路径,格式为 s3://bucket-name/file-name
  • content:必需。要写入文件的内容。

AWS 凭证

该工具需要 AWS 凭证才能访问 S3 存储桶。您可以使用环境变量配置这些凭证

  • CREW_AWS_REGION:您的 S3 存储桶所在的 AWS 区域。默认为 us-east-1
  • CREW_AWS_ACCESS_KEY_ID:您的 AWS 访问密钥 ID。
  • CREW_AWS_SEC_ACCESS_KEY:您的 AWS secret access key。

用法

当代理使用 S3WriterTool 时,代理需要同时提供 S3 文件路径和要写入的内容

代码
# Example of using the tool with an agent
file_writer_agent = Agent(
    role="File Writer",
    goal="Write content to files in S3 buckets",
    backstory="An expert in storing and managing files in cloud storage.",
    tools=[s3_writer_tool],
    verbose=True,
)

# Create a task for the agent to write a specific file
write_config_task = Task(
    description="""
    Create a configuration file with the following database settings:
    - host: db.example.com
    - port: 5432
    - username: app_user
    - password: secure_password
    
    Save this configuration as JSON to {my_bucket}.
    """,
    expected_output="Confirmation that the configuration file was successfully saved to S3.",
    agent=file_writer_agent,
)

# Run the task
crew = Crew(agents=[file_writer_agent], tasks=[write_config_task])
result = crew.kickoff(inputs={"my_bucket": "s3://my-bucket/config/db-config.json"})

错误处理

S3WriterTool 包含对常见 S3 问题的错误处理

  • 无效的 S3 路径格式
  • 权限问题(例如,对存储桶没有写入权限)
  • AWS 凭证问题
  • 存储桶不存在

发生错误时,该工具将返回包含问题详细信息的错误消息。

实现细节

S3WriterTool 使用适用于 Python 的 AWS 开发工具包 (boto3) 与 S3 交互

代码
class S3WriterTool(BaseTool):
    name: str = "S3 Writer Tool"
    description: str = "Writes content to a file in Amazon S3 given an S3 file path"
    
    def _run(self, file_path: str, content: str) -> str:
        try:
            bucket_name, object_key = self._parse_s3_path(file_path)

            s3 = boto3.client(
                's3',
                region_name=os.getenv('CREW_AWS_REGION', 'us-east-1'),
                aws_access_key_id=os.getenv('CREW_AWS_ACCESS_KEY_ID'),
                aws_secret_access_key=os.getenv('CREW_AWS_SEC_ACCESS_KEY')
            )

            s3.put_object(Bucket=bucket_name, Key=object_key, Body=content.encode('utf-8'))
            return f"Successfully wrote content to {file_path}"
        except ClientError as e:
            return f"Error writing file to S3: {str(e)}"

结论

S3WriterTool 提供了一种将内容写入 Amazon S3 存储桶中文件的直接方法。通过使代理能够在 S3 中创建和更新文件,它简化了需要基于云的文件存储的工作流程。此工具对于数据持久性、配置管理、报告生成以及任何涉及将信息存储在 AWS S3 存储中的任务都特别有用。