chore: native files and openai responses docs
Some checks are pending
Build uv cache / build-cache (3.10) (push) Waiting to run
Build uv cache / build-cache (3.11) (push) Waiting to run
Build uv cache / build-cache (3.12) (push) Waiting to run
Build uv cache / build-cache (3.13) (push) Waiting to run
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (python) (push) Waiting to run
Check Documentation Broken Links / Check broken links (push) Waiting to run
Notify Downstream / notify-downstream (push) Waiting to run

This commit is contained in:
Greyson LaLonde
2026-01-23 18:24:00 -05:00
committed by GitHub
parent c4c9208229
commit 0f3208197f
7 changed files with 897 additions and 0 deletions

View File

@@ -131,6 +131,7 @@
"en/concepts/production-architecture", "en/concepts/production-architecture",
"en/concepts/knowledge", "en/concepts/knowledge",
"en/concepts/llms", "en/concepts/llms",
"en/concepts/files",
"en/concepts/processes", "en/concepts/processes",
"en/concepts/collaboration", "en/concepts/collaboration",
"en/concepts/training", "en/concepts/training",
@@ -597,6 +598,7 @@
"pt-BR/concepts/production-architecture", "pt-BR/concepts/production-architecture",
"pt-BR/concepts/knowledge", "pt-BR/concepts/knowledge",
"pt-BR/concepts/llms", "pt-BR/concepts/llms",
"pt-BR/concepts/files",
"pt-BR/concepts/processes", "pt-BR/concepts/processes",
"pt-BR/concepts/collaboration", "pt-BR/concepts/collaboration",
"pt-BR/concepts/training", "pt-BR/concepts/training",
@@ -1048,6 +1050,7 @@
"ko/concepts/production-architecture", "ko/concepts/production-architecture",
"ko/concepts/knowledge", "ko/concepts/knowledge",
"ko/concepts/llms", "ko/concepts/llms",
"ko/concepts/files",
"ko/concepts/processes", "ko/concepts/processes",
"ko/concepts/collaboration", "ko/concepts/collaboration",
"ko/concepts/training", "ko/concepts/training",

267
docs/en/concepts/files.mdx Normal file
View File

@@ -0,0 +1,267 @@
---
title: Files
description: Pass images, PDFs, audio, video, and text files to your agents for multimodal processing.
icon: file-image
---
## Overview
CrewAI supports native multimodal file inputs, allowing you to pass images, PDFs, audio, video, and text files directly to your agents. Files are automatically formatted for each LLM provider's API requirements.
<Note type="info" title="Optional Dependency">
File support requires the optional `crewai-files` package. Install it with:
```bash
uv add 'crewai[file-processing]'
```
</Note>
<Note type="warning" title="Early Access">
The file processing API is currently in early access.
</Note>
## File Types
CrewAI supports five specific file types plus a generic `File` class that auto-detects the type:
| Type | Class | Use Cases |
|:-----|:------|:----------|
| **Image** | `ImageFile` | Photos, screenshots, diagrams, charts |
| **PDF** | `PDFFile` | Documents, reports, papers |
| **Audio** | `AudioFile` | Voice recordings, podcasts, meetings |
| **Video** | `VideoFile` | Screen recordings, presentations |
| **Text** | `TextFile` | Code files, logs, data files |
| **Generic** | `File` | Auto-detect type from content |
```python
from crewai_files import File, ImageFile, PDFFile, AudioFile, VideoFile, TextFile
image = ImageFile(source="screenshot.png")
pdf = PDFFile(source="report.pdf")
audio = AudioFile(source="meeting.mp3")
video = VideoFile(source="demo.mp4")
text = TextFile(source="data.csv")
file = File(source="document.pdf")
```
## File Sources
The `source` parameter accepts multiple input types and auto-detects the appropriate handler:
### From Path
```python
from crewai_files import ImageFile
image = ImageFile(source="./images/chart.png")
```
### From URL
```python
from crewai_files import ImageFile
image = ImageFile(source="https://example.com/image.png")
```
### From Bytes
```python
from crewai_files import ImageFile, FileBytes
image_bytes = download_image_from_api()
image = ImageFile(source=FileBytes(data=image_bytes, filename="downloaded.png"))
image = ImageFile(source=image_bytes)
```
## Using Files
Files can be passed at multiple levels, with more specific levels taking precedence.
### With Crews
Pass files when kicking off a crew:
```python
from crewai import Crew
from crewai_files import ImageFile
crew = Crew(agents=[analyst], tasks=[analysis_task])
result = crew.kickoff(
inputs={"topic": "Q4 Sales"},
input_files={
"chart": ImageFile(source="sales_chart.png"),
"report": PDFFile(source="quarterly_report.pdf"),
}
)
```
### With Tasks
Attach files to specific tasks:
```python
from crewai import Task
from crewai_files import ImageFile
task = Task(
description="Analyze the sales chart and identify trends in {chart}",
expected_output="A summary of key trends",
input_files={
"chart": ImageFile(source="sales_chart.png"),
}
)
```
### With Flows
Pass files to flows, which automatically inherit to crews:
```python
from crewai.flow.flow import Flow, start
from crewai_files import ImageFile
class AnalysisFlow(Flow):
@start()
def analyze(self):
return self.analysis_crew.kickoff()
flow = AnalysisFlow()
result = flow.kickoff(
input_files={"image": ImageFile(source="data.png")}
)
```
### With Standalone Agents
Pass files directly to agent kickoff:
```python
from crewai import Agent
from crewai_files import ImageFile
agent = Agent(
role="Image Analyst",
goal="Analyze images",
backstory="Expert at visual analysis",
llm="gpt-4o",
)
result = agent.kickoff(
messages="What's in this image?",
input_files={"photo": ImageFile(source="photo.jpg")},
)
```
## File Precedence
When files are passed at multiple levels, more specific levels override broader ones:
```
Flow input_files < Crew input_files < Task input_files
```
For example, if both Flow and Task define a file named `"chart"`, the Task's version is used.
## Provider Support
Different providers support different file types. CrewAI automatically formats files for each provider's API.
| Provider | Image | PDF | Audio | Video | Text |
|:---------|:-----:|:---:|:-----:|:-----:|:----:|
| **OpenAI** (completions API) | ✓ | | | | |
| **OpenAI** (responses API) | ✓ | ✓ | ✓ | | |
| **Anthropic** (claude-3.x) | ✓ | ✓ | | | |
| **Google Gemini** (gemini-1.5, 2.0, 2.5) | ✓ | ✓ | ✓ | ✓ | ✓ |
| **AWS Bedrock** (claude-3) | ✓ | ✓ | | | |
| **Azure OpenAI** (gpt-4o) | ✓ | | ✓ | | |
<Note type="info" title="Gemini for Maximum File Support">
Google Gemini models support all file types including video (up to 1 hour, 2GB). Use Gemini when you need to process video content.
</Note>
<Note type="warning" title="Unsupported File Types">
If you pass a file type that the provider doesn't support (e.g., video to OpenAI), you'll receive an `UnsupportedFileTypeError`. Choose your provider based on the file types you need to process.
</Note>
## How Files Are Sent
CrewAI automatically chooses the optimal method to send files to each provider:
| Method | Description | Used When |
|:-------|:------------|:----------|
| **Inline Base64** | File embedded directly in the request | Small files (< 5MB typically) |
| **File Upload API** | File uploaded separately, referenced by ID | Large files that exceed threshold |
| **URL Reference** | Direct URL passed to the model | File source is already a URL |
### Provider Transmission Methods
| Provider | Inline Base64 | File Upload API | URL References |
|:---------|:-------------:|:---------------:|:--------------:|
| **OpenAI** | ✓ | ✓ (> 5 MB) | ✓ |
| **Anthropic** | ✓ | ✓ (> 5 MB) | ✓ |
| **Google Gemini** | ✓ | ✓ (> 20 MB) | ✓ |
| **AWS Bedrock** | ✓ | | ✓ (S3 URIs) |
| **Azure OpenAI** | ✓ | | ✓ |
<Note type="info" title="Automatic Optimization">
You don't need to manage this yourself. CrewAI automatically uses the most efficient method based on file size and provider capabilities. Providers without file upload APIs use inline base64 for all files.
</Note>
## File Handling Modes
Control how files are processed when they exceed provider limits:
```python
from crewai_files import ImageFile, PDFFile
image = ImageFile(source="large.png", mode="strict")
image = ImageFile(source="large.png", mode="auto")
image = ImageFile(source="large.png", mode="warn")
pdf = PDFFile(source="large.pdf", mode="chunk")
```
## Provider Constraints
Each provider has specific limits for file sizes and dimensions:
### OpenAI
- **Images**: Max 20 MB, up to 10 images per request
- **PDFs**: Max 32 MB, up to 100 pages
- **Audio**: Max 25 MB, up to 25 minutes
### Anthropic
- **Images**: Max 5 MB, max 8000x8000 pixels, up to 100 images
- **PDFs**: Max 32 MB, up to 100 pages
### Google Gemini
- **Images**: Max 100 MB
- **PDFs**: Max 50 MB
- **Audio**: Max 100 MB, up to 9.5 hours
- **Video**: Max 2 GB, up to 1 hour
### AWS Bedrock
- **Images**: Max 4.5 MB, max 8000x8000 pixels
- **PDFs**: Max 3.75 MB, up to 100 pages
## Referencing Files in Prompts
Use the file's key name in your task descriptions to reference files:
```python
task = Task(
description="""
Analyze the provided materials:
1. Review the chart in {sales_chart}
2. Cross-reference with data in {quarterly_report}
3. Summarize key findings
""",
expected_output="Analysis summary with key insights",
input_files={
"sales_chart": ImageFile(source="chart.png"),
"quarterly_report": PDFFile(source="report.pdf"),
}
)
```

View File

@@ -207,6 +207,37 @@ In this section, you'll find detailed examples that help you select, configure,
| o3-mini | 200,000 tokens | Lightweight reasoning model | | o3-mini | 200,000 tokens | Lightweight reasoning model |
| o4-mini | 200,000 tokens | Next-gen efficient reasoning | | o4-mini | 200,000 tokens | Next-gen efficient reasoning |
**Responses API:**
OpenAI offers two APIs: Chat Completions (default) and the newer Responses API. The Responses API was designed from the ground up with native multimodal support—text, images, audio, and function calls are all first-class citizens. It provides better performance with reasoning models and supports additional features like auto-chaining and built-in tools.
```python Code
from crewai import LLM
# Use the Responses API instead of Chat Completions
llm = LLM(
model="openai/gpt-4o",
api="responses", # Enable Responses API
store=True, # Store responses for multi-turn (optional)
auto_chain=True, # Auto-chain for reasoning models (optional)
)
```
**Responses API Parameters:**
- `api`: Set to `"responses"` to use the Responses API (default: `"completions"`)
- `instructions`: System-level instructions (Responses API only)
- `store`: Whether to store responses for multi-turn conversations
- `previous_response_id`: ID of previous response for multi-turn
- `include`: Additional data to include in response (e.g., `["reasoning.encrypted_content"]`)
- `builtin_tools`: List of OpenAI built-in tools: `"web_search"`, `"file_search"`, `"code_interpreter"`, `"computer_use"`
- `parse_tool_outputs`: Return structured `ResponsesAPIResult` with parsed built-in tool outputs
- `auto_chain`: Automatically track and use response IDs for multi-turn conversations
- `auto_chain_reasoning`: Track encrypted reasoning items for ZDR (Zero Data Retention) compliance
<Tip>
Use the Responses API for new projects, especially when working with reasoning models (o1, o3, o4) or when you need native multimodal support for [files](/en/concepts/files).
</Tip>
**Note:** To use OpenAI, install the required dependencies: **Note:** To use OpenAI, install the required dependencies:
```bash ```bash
uv add "crewai[openai]" uv add "crewai[openai]"

267
docs/ko/concepts/files.mdx Normal file
View File

@@ -0,0 +1,267 @@
---
title: 파일
description: 멀티모달 처리를 위해 이미지, PDF, 오디오, 비디오, 텍스트 파일을 에이전트에 전달하세요.
icon: file-image
---
## 개요
CrewAI는 네이티브 멀티모달 파일 입력을 지원하여 이미지, PDF, 오디오, 비디오, 텍스트 파일을 에이전트에 직접 전달할 수 있습니다. 파일은 각 LLM 프로바이더의 API 요구사항에 맞게 자동으로 포맷됩니다.
<Note type="info" title="선택적 의존성">
파일 지원을 위해서는 선택적 `crewai-files` 패키지가 필요합니다. 다음 명령어로 설치하세요:
```bash
uv add 'crewai[file-processing]'
```
</Note>
<Note type="warning" title="얼리 액세스">
파일 처리 API는 현재 얼리 액세스 단계입니다.
</Note>
## 파일 타입
CrewAI는 5가지 특정 파일 타입과 타입을 자동 감지하는 일반 `File` 클래스를 지원합니다:
| 타입 | 클래스 | 사용 사례 |
|:-----|:------|:----------|
| **이미지** | `ImageFile` | 사진, 스크린샷, 다이어그램, 차트 |
| **PDF** | `PDFFile` | 문서, 보고서, 논문 |
| **오디오** | `AudioFile` | 음성 녹음, 팟캐스트, 회의 |
| **비디오** | `VideoFile` | 화면 녹화, 프레젠테이션 |
| **텍스트** | `TextFile` | 코드 파일, 로그, 데이터 파일 |
| **일반** | `File` | 콘텐츠에서 타입 자동 감지 |
```python
from crewai_files import File, ImageFile, PDFFile, AudioFile, VideoFile, TextFile
image = ImageFile(source="screenshot.png")
pdf = PDFFile(source="report.pdf")
audio = AudioFile(source="meeting.mp3")
video = VideoFile(source="demo.mp4")
text = TextFile(source="data.csv")
file = File(source="document.pdf")
```
## 파일 소스
`source` 파라미터는 여러 입력 타입을 받아들이고 적절한 핸들러를 자동으로 감지합니다:
### 경로에서
```python
from crewai_files import ImageFile
image = ImageFile(source="./images/chart.png")
```
### URL에서
```python
from crewai_files import ImageFile
image = ImageFile(source="https://example.com/image.png")
```
### 바이트에서
```python
from crewai_files import ImageFile, FileBytes
image_bytes = download_image_from_api()
image = ImageFile(source=FileBytes(data=image_bytes, filename="downloaded.png"))
image = ImageFile(source=image_bytes)
```
## 파일 사용하기
파일은 여러 레벨에서 전달할 수 있으며, 더 구체적인 레벨이 우선순위를 가집니다.
### Crew와 함께
crew를 킥오프할 때 파일을 전달합니다:
```python
from crewai import Crew
from crewai_files import ImageFile
crew = Crew(agents=[analyst], tasks=[analysis_task])
result = crew.kickoff(
inputs={"topic": "Q4 Sales"},
input_files={
"chart": ImageFile(source="sales_chart.png"),
"report": PDFFile(source="quarterly_report.pdf"),
}
)
```
### Task와 함께
특정 작업에 파일을 첨부합니다:
```python
from crewai import Task
from crewai_files import ImageFile
task = Task(
description="매출 차트를 분석하고 {chart}에서 트렌드를 파악하세요",
expected_output="주요 트렌드 요약",
input_files={
"chart": ImageFile(source="sales_chart.png"),
}
)
```
### Flow와 함께
flow에 파일을 전달하면 자동으로 crew에 상속됩니다:
```python
from crewai.flow.flow import Flow, start
from crewai_files import ImageFile
class AnalysisFlow(Flow):
@start()
def analyze(self):
return self.analysis_crew.kickoff()
flow = AnalysisFlow()
result = flow.kickoff(
input_files={"image": ImageFile(source="data.png")}
)
```
### 단독 에이전트와 함께
에이전트 킥오프에 직접 파일을 전달합니다:
```python
from crewai import Agent
from crewai_files import ImageFile
agent = Agent(
role="Image Analyst",
goal="Analyze images",
backstory="Expert at visual analysis",
llm="gpt-4o",
)
result = agent.kickoff(
messages="What's in this image?",
input_files={"photo": ImageFile(source="photo.jpg")},
)
```
## 파일 우선순위
여러 레벨에서 파일이 전달될 때, 더 구체적인 레벨이 상위 레벨을 오버라이드합니다:
```
Flow input_files < Crew input_files < Task input_files
```
예를 들어, Flow와 Task 모두 `"chart"`라는 이름의 파일을 정의하면, Task의 버전이 사용됩니다.
## 프로바이더 지원
각 프로바이더는 서로 다른 파일 타입을 지원합니다. CrewAI는 각 프로바이더의 API에 맞게 파일을 자동으로 포맷합니다.
| 프로바이더 | 이미지 | PDF | 오디오 | 비디오 | 텍스트 |
|:---------|:-----:|:---:|:-----:|:-----:|:----:|
| **OpenAI** (completions API) | ✓ | | | | |
| **OpenAI** (responses API) | ✓ | ✓ | ✓ | | |
| **Anthropic** (claude-3.x) | ✓ | ✓ | | | |
| **Google Gemini** (gemini-1.5, 2.0, 2.5) | ✓ | ✓ | ✓ | ✓ | ✓ |
| **AWS Bedrock** (claude-3) | ✓ | ✓ | | | |
| **Azure OpenAI** (gpt-4o) | ✓ | | ✓ | | |
<Note type="info" title="최대 파일 지원을 위한 Gemini">
Google Gemini 모델은 비디오를 포함한 모든 파일 타입을 지원합니다 (최대 1시간, 2GB). 비디오 콘텐츠를 처리해야 할 때 Gemini를 사용하세요.
</Note>
<Note type="warning" title="지원되지 않는 파일 타입">
프로바이더가 지원하지 않는 파일 타입을 전달하면 (예: OpenAI에 비디오) `UnsupportedFileTypeError`가 발생합니다. 처리해야 하는 파일 타입에 따라 프로바이더를 선택하세요.
</Note>
## 파일 전송 방식
CrewAI는 각 프로바이더에 파일을 전송하는 최적의 방법을 자동으로 선택합니다:
| 방식 | 설명 | 사용 조건 |
|:-------|:------------|:----------|
| **인라인 Base64** | 파일이 요청에 직접 임베드됨 | 작은 파일 (일반적으로 < 5MB) |
| **파일 업로드 API** | 파일이 별도로 업로드되고 ID로 참조됨 | 임계값을 초과하는 큰 파일 |
| **URL 참조** | 직접 URL이 모델에 전달됨 | 파일 소스가 이미 URL인 경우 |
### 프로바이더 전송 방식
| 프로바이더 | 인라인 Base64 | 파일 업로드 API | URL 참조 |
|:---------|:-------------:|:---------------:|:--------------:|
| **OpenAI** | ✓ | ✓ (> 5 MB) | ✓ |
| **Anthropic** | ✓ | ✓ (> 5 MB) | ✓ |
| **Google Gemini** | ✓ | ✓ (> 20 MB) | ✓ |
| **AWS Bedrock** | ✓ | | ✓ (S3 URI) |
| **Azure OpenAI** | ✓ | | ✓ |
<Note type="info" title="자동 최적화">
이를 직접 관리할 필요가 없습니다. CrewAI는 파일 크기와 프로바이더 기능에 따라 가장 효율적인 방법을 자동으로 사용합니다. 파일 업로드 API가 없는 프로바이더는 모든 파일에 인라인 base64를 사용합니다.
</Note>
## 파일 처리 모드
프로바이더 제한을 초과할 때 파일 처리 방식을 제어합니다:
```python
from crewai_files import ImageFile, PDFFile
image = ImageFile(source="large.png", mode="strict")
image = ImageFile(source="large.png", mode="auto")
image = ImageFile(source="large.png", mode="warn")
pdf = PDFFile(source="large.pdf", mode="chunk")
```
## 프로바이더 제약사항
각 프로바이더는 파일 크기와 규격에 대한 특정 제한이 있습니다:
### OpenAI
- **이미지**: 최대 20 MB, 요청당 최대 10개 이미지
- **PDF**: 최대 32 MB, 최대 100 페이지
- **오디오**: 최대 25 MB, 최대 25분
### Anthropic
- **이미지**: 최대 5 MB, 최대 8000x8000 픽셀, 최대 100개 이미지
- **PDF**: 최대 32 MB, 최대 100 페이지
### Google Gemini
- **이미지**: 최대 100 MB
- **PDF**: 최대 50 MB
- **오디오**: 최대 100 MB, 최대 9.5시간
- **비디오**: 최대 2 GB, 최대 1시간
### AWS Bedrock
- **이미지**: 최대 4.5 MB, 최대 8000x8000 픽셀
- **PDF**: 최대 3.75 MB, 최대 100 페이지
## 프롬프트에서 파일 참조하기
작업 설명에서 파일의 키 이름을 사용하여 파일을 참조합니다:
```python
task = Task(
description="""
제공된 자료를 분석하세요:
1. {sales_chart}에서 차트 검토
2. {quarterly_report}의 데이터와 교차 참조
3. 주요 발견사항 요약
""",
expected_output="주요 인사이트가 포함된 분석 요약",
input_files={
"sales_chart": ImageFile(source="chart.png"),
"quarterly_report": PDFFile(source="report.pdf"),
}
)
```

View File

@@ -150,6 +150,37 @@ CrewAI는 고유한 기능, 인증 방법, 모델 역량을 제공하는 다양
| o1-mini | 128,000 토큰 | 빠른 추론, 복잡한 추론 | | o1-mini | 128,000 토큰 | 빠른 추론, 복잡한 추론 |
| o1-preview | 128,000 토큰 | 빠른 추론, 복잡한 추론 | | o1-preview | 128,000 토큰 | 빠른 추론, 복잡한 추론 |
| o1 | 200,000 토큰 | 빠른 추론, 복잡한 추론 | | o1 | 200,000 토큰 | 빠른 추론, 복잡한 추론 |
**Responses API:**
OpenAI는 Chat Completions(기본값)와 새로운 Responses API, 두 가지 API를 제공합니다. Responses API는 네이티브 멀티모달 지원을 기반으로 처음부터 설계되었으며, 텍스트, 이미지, 오디오, 함수 호출이 모두 일급 객체입니다. 추론 모델에서 더 나은 성능을 제공하고 자동 체이닝 및 내장 도구와 같은 추가 기능을 지원합니다.
```python Code
from crewai import LLM
# Chat Completions 대신 Responses API 사용
llm = LLM(
model="openai/gpt-4o",
api="responses", # Responses API 활성화
store=True, # 멀티턴을 위한 응답 저장 (선택사항)
auto_chain=True, # 추론 모델용 자동 체이닝 (선택사항)
)
```
**Responses API 파라미터:**
- `api`: Responses API를 사용하려면 `"responses"`로 설정 (기본값: `"completions"`)
- `instructions`: 시스템 레벨 지침 (Responses API 전용)
- `store`: 멀티턴 대화를 위한 응답 저장 여부
- `previous_response_id`: 멀티턴을 위한 이전 응답 ID
- `include`: 응답에 포함할 추가 데이터 (예: `["reasoning.encrypted_content"]`)
- `builtin_tools`: OpenAI 내장 도구 목록: `"web_search"`, `"file_search"`, `"code_interpreter"`, `"computer_use"`
- `parse_tool_outputs`: 파싱된 내장 도구 출력과 함께 구조화된 `ResponsesAPIResult` 반환
- `auto_chain`: 멀티턴 대화를 위한 응답 ID 자동 추적 및 사용
- `auto_chain_reasoning`: ZDR(제로 데이터 보존) 준수를 위한 암호화된 추론 항목 추적
<Tip>
새 프로젝트, 특히 추론 모델(o1, o3, o4)을 사용하거나 [파일](/ko/concepts/files)에 대한 네이티브 멀티모달 지원이 필요한 경우 Responses API를 사용하세요.
</Tip>
</Accordion> </Accordion>
<Accordion title="Meta-Llama"> <Accordion title="Meta-Llama">

View File

@@ -0,0 +1,267 @@
---
title: Arquivos
description: Passe imagens, PDFs, áudio, vídeo e arquivos de texto para seus agentes para processamento multimodal.
icon: file-image
---
## Visão Geral
O CrewAI suporta entradas de arquivos multimodais nativos, permitindo que você passe imagens, PDFs, áudio, vídeo e arquivos de texto diretamente para seus agentes. Os arquivos são formatados automaticamente para os requisitos da API de cada provedor LLM.
<Note type="info" title="Dependência Opcional">
O suporte a arquivos requer o pacote opcional `crewai-files`. Instale com:
```bash
uv add 'crewai[file-processing]'
```
</Note>
<Note type="warning" title="Acesso Antecipado">
A API de processamento de arquivos está atualmente em acesso antecipado.
</Note>
## Tipos de Arquivo
O CrewAI suporta cinco tipos de arquivo específicos mais uma classe genérica `File` que detecta automaticamente o tipo:
| Tipo | Classe | Casos de Uso |
|:-----|:------|:----------|
| **Imagem** | `ImageFile` | Fotos, capturas de tela, diagramas, gráficos |
| **PDF** | `PDFFile` | Documentos, relatórios, artigos |
| **Áudio** | `AudioFile` | Gravações de voz, podcasts, reuniões |
| **Vídeo** | `VideoFile` | Gravações de tela, apresentações |
| **Texto** | `TextFile` | Arquivos de código, logs, arquivos de dados |
| **Genérico** | `File` | Detecta automaticamente o tipo do conteúdo |
```python
from crewai_files import File, ImageFile, PDFFile, AudioFile, VideoFile, TextFile
image = ImageFile(source="screenshot.png")
pdf = PDFFile(source="report.pdf")
audio = AudioFile(source="meeting.mp3")
video = VideoFile(source="demo.mp4")
text = TextFile(source="data.csv")
file = File(source="document.pdf")
```
## Fontes de Arquivo
O parâmetro `source` aceita múltiplos tipos de entrada e detecta automaticamente o handler apropriado:
### De Caminho
```python
from crewai_files import ImageFile
image = ImageFile(source="./images/chart.png")
```
### De URL
```python
from crewai_files import ImageFile
image = ImageFile(source="https://example.com/image.png")
```
### De Bytes
```python
from crewai_files import ImageFile, FileBytes
image_bytes = download_image_from_api()
image = ImageFile(source=FileBytes(data=image_bytes, filename="downloaded.png"))
image = ImageFile(source=image_bytes)
```
## Usando Arquivos
Arquivos podem ser passados em múltiplos níveis, com níveis mais específicos tendo precedência.
### Com Crews
Passe arquivos ao iniciar uma crew:
```python
from crewai import Crew
from crewai_files import ImageFile
crew = Crew(agents=[analyst], tasks=[analysis_task])
result = crew.kickoff(
inputs={"topic": "Q4 Sales"},
input_files={
"chart": ImageFile(source="sales_chart.png"),
"report": PDFFile(source="quarterly_report.pdf"),
}
)
```
### Com Tasks
Anexe arquivos a tasks específicas:
```python
from crewai import Task
from crewai_files import ImageFile
task = Task(
description="Analise o gráfico de vendas e identifique tendências em {chart}",
expected_output="Um resumo das principais tendências",
input_files={
"chart": ImageFile(source="sales_chart.png"),
}
)
```
### Com Flows
Passe arquivos para flows, que automaticamente herdam para crews:
```python
from crewai.flow.flow import Flow, start
from crewai_files import ImageFile
class AnalysisFlow(Flow):
@start()
def analyze(self):
return self.analysis_crew.kickoff()
flow = AnalysisFlow()
result = flow.kickoff(
input_files={"image": ImageFile(source="data.png")}
)
```
### Com Agentes Standalone
Passe arquivos diretamente no kickoff do agente:
```python
from crewai import Agent
from crewai_files import ImageFile
agent = Agent(
role="Image Analyst",
goal="Analyze images",
backstory="Expert at visual analysis",
llm="gpt-4o",
)
result = agent.kickoff(
messages="What's in this image?",
input_files={"photo": ImageFile(source="photo.jpg")},
)
```
## Precedência de Arquivos
Quando arquivos são passados em múltiplos níveis, níveis mais específicos sobrescrevem os mais amplos:
```
Flow input_files < Crew input_files < Task input_files
```
Por exemplo, se tanto Flow quanto Task definem um arquivo chamado `"chart"`, a versão da Task é usada.
## Suporte por Provedor
Diferentes provedores suportam diferentes tipos de arquivo. O CrewAI formata automaticamente os arquivos para a API de cada provedor.
| Provedor | Imagem | PDF | Áudio | Vídeo | Texto |
|:---------|:-----:|:---:|:-----:|:-----:|:----:|
| **OpenAI** (API completions) | ✓ | | | | |
| **OpenAI** (API responses) | ✓ | ✓ | ✓ | | |
| **Anthropic** (claude-3.x) | ✓ | ✓ | | | |
| **Google Gemini** (gemini-1.5, 2.0, 2.5) | ✓ | ✓ | ✓ | ✓ | ✓ |
| **AWS Bedrock** (claude-3) | ✓ | ✓ | | | |
| **Azure OpenAI** (gpt-4o) | ✓ | | ✓ | | |
<Note type="info" title="Gemini para Máximo Suporte de Arquivos">
Os modelos Google Gemini suportam todos os tipos de arquivo incluindo vídeo (até 1 hora, 2GB). Use Gemini quando precisar processar conteúdo de vídeo.
</Note>
<Note type="warning" title="Tipos de Arquivo Não Suportados">
Se você passar um tipo de arquivo que o provedor não suporta (ex: vídeo para OpenAI), você receberá um `UnsupportedFileTypeError`. Escolha seu provedor baseado nos tipos de arquivo que você precisa processar.
</Note>
## Como os Arquivos São Enviados
O CrewAI escolhe automaticamente o método ideal para enviar arquivos para cada provedor:
| Método | Descrição | Usado Quando |
|:-------|:------------|:----------|
| **Base64 Inline** | Arquivo embutido diretamente na requisição | Arquivos pequenos (< 5MB tipicamente) |
| **API de Upload de Arquivo** | Arquivo enviado separadamente, referenciado por ID | Arquivos grandes que excedem o limite |
| **Referência por URL** | URL direta passada para o modelo | Fonte do arquivo já é uma URL |
### Métodos de Transmissão por Provedor
| Provedor | Base64 Inline | API de Upload | Referências URL |
|:---------|:-------------:|:---------------:|:--------------:|
| **OpenAI** | ✓ | ✓ (> 5 MB) | ✓ |
| **Anthropic** | ✓ | ✓ (> 5 MB) | ✓ |
| **Google Gemini** | ✓ | ✓ (> 20 MB) | ✓ |
| **AWS Bedrock** | ✓ | | ✓ (S3 URIs) |
| **Azure OpenAI** | ✓ | | ✓ |
<Note type="info" title="Otimização Automática">
Você não precisa gerenciar isso. O CrewAI usa automaticamente o método mais eficiente baseado no tamanho do arquivo e nas capacidades do provedor. Provedores sem APIs de upload de arquivo usam base64 inline para todos os arquivos.
</Note>
## Modos de Tratamento de Arquivo
Controle como os arquivos são processados quando excedem os limites do provedor:
```python
from crewai_files import ImageFile, PDFFile
image = ImageFile(source="large.png", mode="strict")
image = ImageFile(source="large.png", mode="auto")
image = ImageFile(source="large.png", mode="warn")
pdf = PDFFile(source="large.pdf", mode="chunk")
```
## Restrições por Provedor
Cada provedor tem limites específicos para tamanhos e dimensões de arquivo:
### OpenAI
- **Imagens**: Máx 20 MB, até 10 imagens por requisição
- **PDFs**: Máx 32 MB, até 100 páginas
- **Áudio**: Máx 25 MB, até 25 minutos
### Anthropic
- **Imagens**: Máx 5 MB, máx 8000x8000 pixels, até 100 imagens
- **PDFs**: Máx 32 MB, até 100 páginas
### Google Gemini
- **Imagens**: Máx 100 MB
- **PDFs**: Máx 50 MB
- **Áudio**: Máx 100 MB, até 9,5 horas
- **Vídeo**: Máx 2 GB, até 1 hora
### AWS Bedrock
- **Imagens**: Máx 4,5 MB, máx 8000x8000 pixels
- **PDFs**: Máx 3,75 MB, até 100 páginas
## Referenciando Arquivos em Prompts
Use o nome da chave do arquivo nas descrições das suas tasks para referenciar arquivos:
```python
task = Task(
description="""
Analise os materiais fornecidos:
1. Revise o gráfico em {sales_chart}
2. Faça referência cruzada com dados em {quarterly_report}
3. Resuma as principais descobertas
""",
expected_output="Resumo da análise com insights principais",
input_files={
"sales_chart": ImageFile(source="chart.png"),
"quarterly_report": PDFFile(source="report.pdf"),
}
)
```

View File

@@ -150,6 +150,37 @@ Nesta seção, você encontrará exemplos detalhados que ajudam a selecionar, co
| o1-mini | 128.000 tokens | Raciocínio rápido, tarefas complexas | | o1-mini | 128.000 tokens | Raciocínio rápido, tarefas complexas |
| o1-preview | 128.000 tokens | Raciocínio rápido, tarefas complexas | | o1-preview | 128.000 tokens | Raciocínio rápido, tarefas complexas |
| o1 | 200.000 tokens | Raciocínio rápido, tarefas complexas | | o1 | 200.000 tokens | Raciocínio rápido, tarefas complexas |
**Responses API:**
A OpenAI oferece duas APIs: Chat Completions (padrão) e a nova Responses API. A Responses API foi projetada desde o início com suporte multimodal nativo—texto, imagens, áudio e chamadas de função são todos cidadãos de primeira classe. Ela oferece melhor performance com modelos de raciocínio e suporta recursos adicionais como auto-encadeamento e ferramentas integradas.
```python Code
from crewai import LLM
# Usar Responses API em vez de Chat Completions
llm = LLM(
model="openai/gpt-4o",
api="responses", # Habilitar Responses API
store=True, # Armazenar respostas para multi-turno (opcional)
auto_chain=True, # Auto-encadeamento para modelos de raciocínio (opcional)
)
```
**Parâmetros da Responses API:**
- `api`: Defina como `"responses"` para usar a Responses API (padrão: `"completions"`)
- `instructions`: Instruções de nível de sistema (apenas Responses API)
- `store`: Se deve armazenar respostas para conversas multi-turno
- `previous_response_id`: ID da resposta anterior para multi-turno
- `include`: Dados adicionais para incluir na resposta (ex: `["reasoning.encrypted_content"]`)
- `builtin_tools`: Lista de ferramentas integradas da OpenAI: `"web_search"`, `"file_search"`, `"code_interpreter"`, `"computer_use"`
- `parse_tool_outputs`: Retornar `ResponsesAPIResult` estruturado com saídas de ferramentas integradas parseadas
- `auto_chain`: Rastrear e usar automaticamente IDs de resposta para conversas multi-turno
- `auto_chain_reasoning`: Rastrear itens de raciocínio criptografados para conformidade ZDR (Zero Data Retention)
<Tip>
Use a Responses API para novos projetos, especialmente ao trabalhar com modelos de raciocínio (o1, o3, o4) ou quando precisar de suporte multimodal nativo para [arquivos](/pt-BR/concepts/files).
</Tip>
</Accordion> </Accordion>
<Accordion title="Meta-Llama"> <Accordion title="Meta-Llama">