跳转到主要内容

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 秘密访问密钥。

用法

当使用代理程序与 `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 SDK (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 存储中存储信息的任务特别有用。