네이티브 툴
네이티브 툴
네이티브 툴은 LLM 프로바이더가 제공하고 실행해요. 반면 공용 툴은 Pydantic AI가 실행하는 커스텀 구현이에요.
Pydantic AI는 다음 네이티브 툴을 지원해요:
WebSearchTool: 에이전트가 웹을 검색하게 함XSearchTool: 에이전트가 X/Twitter를 검색하게 함(xAI 전용)CodeExecutionTool: 에이전트가 안전한 환경에서 코드를 실행하게 함ImageGenerationTool: 에이전트가 이미지를 생성하게 함WebFetchTool: 에이전트가 웹 페이지를 가져오게 함MemoryTool: 에이전트가 메모리를 사용하게 함MCPServerTool: 에이전트가 원격 MCP 서버를 사용하게 함. 통신은 모델 프로바이더가 처리FileSearchTool: 에이전트가 벡터 검색(RAG)으로 업로드된 파일을 검색하게 함AdvisorTool: 더 빠른 실행 모델이 생성 중에 더 강한 어드바이저 모델에 상담하게 함(Anthropic, OpenRouter)
이 툴들은 에이전트의 capabilities 목록에 NativeTool로 감싸 전달되고, 모델 프로바이더의 인프라가 실행해요.
프로바이더 지원
모든 모델 프로바이더가 네이티브 툴을 지원하지는 않아요. 지원하지 않는 프로바이더에서 네이티브 툴을 사용하면 에이전트를 실행하려고 할 때 Pydantic AI가 UserError를 발생시켜요.
프로바이더가 Pydantic AI가 현재 지원하지 않는 네이티브 툴을 지원하면 이슈를 제기해 주세요.
프로바이더 적응형 기능
모델 무관의 더 하이레벨 접근을 위해 프로바이더 적응형 툴 기능을 고려하세요: WebSearch, WebFetch, ImageGeneration, MCP. 이것들은 모델의 네이티브 툴이 지원되면 자동으로 사용하고, 코드 변경 없이 에이전트가 프로바이더 전반에서 작동하도록 local=로 활성화한 로컬 구현으로 폴백해요. 두 가지는 다르게 작동해요. ImageGeneration은 fallback_image_model= 또는 fallback_subagent_model=로 내장 폴백도 활성화하고, MCP는 기본으로 로컬에서 실행되며 native=True로 네이티브 MCP를 옵트인해요.
출처: 문서
본문
Google 툴 조합
Gemini 3 모델은 네이티브 툴을 함수 툴(출력 툴과 NativeOutput 포함)과 결합하는 것을 지원해요. 이전 Gemini 모델은 이 조합을 사용할 수 없어요. 네이티브 툴과 함께 구조화된 출력에는 PromptedOutput을 사용하세요.
동적 구성
가끔 실행 컨텍스트(예: 사용자 의존성)에 따라 네이티브 툴을 동적으로 구성하거나 조건부로 생략해야 해요. capabilities에서 NativeTool로 함수를 감싸면 이를 달성할 수 있어요. 함수는 RunContext를 인자로 받고 AbstractNativeTool 또는 None을 반환해요.
이것은 WebSearchTool 같은 툴에 특히 유용해요. 현재 요청에 따라 사용자 위치를 설정하거나, 사용자가 위치를 제공하지 않으면 툴을 비활성화하고 싶을 수 있으니까요.
from pydantic_ai import Agent, RunContext, WebSearchTool
from pydantic_ai.capabilities import NativeTool
async def prepared_web_search(ctx: RunContext[dict]) -> WebSearchTool | None:
if not ctx.deps.get('location'):
return None
return WebSearchTool(
user_location={'city': ctx.deps['location']},
)
agent = Agent(
'openai-responses:gpt-5.2',
capabilities=[NativeTool(prepared_web_search)],
deps_type=dict,
)
# Run with location
result = agent.run_sync(
'What is the weather like?',
deps={'location': 'London'},
)
print(result.output)
#> It's currently raining in London.
# Run without location (tool will be omitted)
result = agent.run_sync(
'What is the capital of France?',
deps={'location': None},
)
print(result.output)
#> The capital of France is Paris.
fallback_subagent_model 아래에서 None 반환
생략은 네이티브 툴이 유일한 경로인 곳에서 None이 의미하는 것이에요. XSearch와 ImageGeneration은 예외예요. fallback_subagent_model이 설정되면 팩토리가 None을 반환할 때마다 그들의 서브에이전트 툴이 모델에 제공되고, 그것을 호출하면 기본 설정으로 실행하는 대신 UserError를 발생시켜요. X Search와 Image Generation 참고.
웹 검색 툴
팁
local='duckduckgo'로 선택적 로컬 폴백이 있는 모델 무관 접근은 WebSearch 기능을 참고하세요.
WebSearchTool은 에이전트가 웹을 검색하게 해줘요. 최신 데이터가 필요한 쿼리에 이상적이에요.
프로바이더 지원
| 프로바이더 | 지원 | 참고 |
|---|---|---|
| OpenAI Responses | ✅ | 전체 기능 지원. ModelResponse.native_tool_calls로 사용 가능한 NativeToolReturnPart에 검색 결과를 포함하려면 OpenAIResponsesModelSettings.openai_include_web_search_sources 모델 설정을 활성화 |
| Anthropic | ✅ | 전체 기능 지원 |
| ✅ | 매개변수 지원 없음. 스트리밍 시 NativeToolCallPart나 NativeToolReturnPart가 생성되지 않음. Google 툴 조합 참고 |
|
| xAI | ✅ | blocked_domains, allowed_domains, user_location 매개변수 지원 |
| Groq | ✅ | 제한된 매개변수 지원. Groq에서 웹 검색 기능을 쓰려면 compound models를 사용해야 함 |
| OpenRouter | ✅ | OpenRouter의 Beta 웹 검색 서버 툴 사용. 모델이 0-N번 검색할 수 있음. 기록된 요청은 OpenRouter가 매개변수 이름을 받아들인다는 것만 검증. 아래 엔진별 효과는 OpenRouter 문서에 따른 것: 네이티브 검색은 search_context_size를 무시, user_location은 네이티브 전용, 네이티브 OpenAI는 blocked_domains를 무시, max_uses는 비네이티브 또는 Anthropic 네이티브 검색으로 작동. 검색 소스는 비네이티브 엔진이 검색했을 때만 provider_details['annotations']에 나타남 |
| OpenAI Chat Completions | ❌ | 미지원 |
| Bedrock | ❌ | 미지원 |
| Mistral | ❌ | 미지원 |
| Cohere | ❌ | 미지원 |
| HuggingFace | ❌ | 미지원 |
사용법
from pydantic_ai import Agent, WebSearchTool
from pydantic_ai.capabilities import NativeTool
agent = Agent('anthropic:claude-sonnet-4-6', capabilities=[NativeTool(WebSearchTool())])
result = agent.run_sync('Give me a sentence with the biggest news in AI this week.')
print(result.output)
#> Scientists have developed a universal AI detector that can identify deepfake videos.
(이 예제는 완전해서 "그대로" 실행할 수 있어요)
Anthropic에서는 검색 횟수가 RequestUsage.details의 web_search_requests로 보고되고 RunUsage.cost에 포함돼요.
OpenAI에서는 웹 검색 툴에 접근하려면 Responses API를 사용해야 해요.
from pydantic_ai import Agent, WebSearchTool
from pydantic_ai.capabilities import NativeTool
agent = Agent('openai-responses:gpt-5.2', capabilities=[NativeTool(WebSearchTool())])
result = agent.run_sync('Give me a sentence with the biggest news in AI this week.')
print(result.output)
#> Scientists have developed a universal AI detector that can identify deepfake videos.
(이 예제는 완전해서 "그대로" 실행할 수 있어요)
구성 옵션
WebSearchTool은 여러 구성 매개변수를 지원해요:
from pydantic_ai import Agent, WebSearchTool, WebSearchUserLocation
from pydantic_ai.capabilities import NativeTool
agent = Agent(
'anthropic:claude-sonnet-4-6',
capabilities=[
NativeTool(
WebSearchTool(
search_context_size='high',
user_location=WebSearchUserLocation(
city='San Francisco',
country='US',
region='CA',
timezone='America/Los_Angeles',
),
blocked_domains=['example.com', 'spam-site.net'],
allowed_domains=None, # Cannot use both blocked_domains and allowed_domains with Anthropic
max_uses=5, # Anthropic only: limit tool usage
)
)
],
)
result = agent.run_sync('Use the web to get the current time.')
print(result.output)
#> In San Francisco, it's 8:21:41 pm PDT on Wednesday, August 6, 2025.
(이 예제는 완전해서 "그대로" 실행할 수 있어요)
프로바이더 지원
| 매개변수 | OpenAI | Anthropic | xAI | Groq | OpenRouter |
|---|---|---|---|---|---|
search_context_size |
✅ | ❌ | ❌ | ❌ | ✅ |
user_location |
✅ | ✅ | ✅ | ❌ | ✅ |
blocked_domains |
✅ | ✅ | ✅ | ✅ | ✅ |
allowed_domains |
✅ | ✅ | ✅ | ✅ | ✅ |
max_uses |
❌ | ✅ | ❌ | ❌ | ✅* |
external_web_access |
✅ | ❌ | ❌ | ❌ | ❌ |
- OpenRouter 문서에 따르면 네이티브 프로바이더 검색은
max_uses를 Anthropic에만 전달해요. 다른 네이티브 프로바이더는 무시해요.
Anthropic 도메인 필터링
Anthropic에서는 blocked_domains 또는 allowed_domains 중 하나만 사용할 수 있어요. 둘 다는 안 돼요.
Anthropic 웹 검색 툴 버전
Pydantic AI는 dynamic_filtering 옵션을 노출하지 않아요. Anthropic에 대해 Pydantic AI는 모델 프로필과 Anthropic 클라이언트에서 웹 검색 툴 버전을 선택해요. Anthropic의 동적 필터링 웹 툴을 지원하는 모델·플랫폼에는 web_search_20260209, 그 외에는 web_search_20250305를 선택해요. 레거시 Amazon Bedrock 클라이언트는 Anthropic 웹 검색을 지원하지 않으므로, AsyncAnthropicBedrock과 함께 WebSearchTool을 쓰면 Pydantic AI가 UserError를 발생시켜요. Vertex AI에서 WebSearchTool은 항상 web_search_20250305를 사용해요. Anthropic이 거기서 동적 필터링 버전을 제공하지 않으므로 동적 필터링은 그 외 지원되는 모델에서도 사용할 수 없어요. 현재 모델 지원과 플랫폼 가용성은 Anthropic 웹 검색 문서와 툴 참조 참고.
CodeExecutionTool은 Anthropic의 독립형 코드 실행 툴을 원할 때만 추가하세요. web_search_20260209를 사용하는 데는 필요하지 않아요. _20260209 웹 툴의 Zero Data Retention 동작은 Anthropic의 서버 툴 문서를 참고하세요.
X 검색 툴
팁
서브에이전트 폴백이 있는 모델 무관 접근은 XSearch 기능을 참고하세요.
XSearchTool은 에이전트가 실시간 게시물과 콘텐츠를 위해 X/Twitter를 검색하게 해줘요. xAI 모델에서 네이티브 지원되고, fallback_subagent_model이 설정된 XSearch 기능으로 다른 모델에서 사용할 수 있어요. 자세한 내용은 xAI X Search 문서 참고.
사용법
from pydantic_ai import Agent, XSearchTool
from pydantic_ai.capabilities import NativeTool
agent = Agent('xai:grok-4.3', capabilities=[NativeTool(XSearchTool())])
result = agent.run_sync('What are people saying about AI on X today?')
print(result.output)
#> There's a lot of excitement about new AI models being released...
(이 예제는 완전해서 "그대로" 실행할 수 있어요)
구성 옵션
XSearchTool은 여러 구성 매개변수를 지원해요:
from datetime import datetime
from pydantic_ai import Agent, XSearchTool
from pydantic_ai.capabilities import NativeTool
agent = Agent(
'xai:grok-4.3',
capabilities=[
NativeTool(
XSearchTool(
allowed_x_handles=['OpenAI', 'AnthropicAI', 'dasfacc'],
from_date=datetime(2024, 1, 1),
to_date=datetime(2024, 12, 31),
enable_image_understanding=True,
enable_video_understanding=True,
)
)
],
)
result = agent.run_sync('What have AI companies been posting about?')
print(result.output)
"""
OpenAI announced their latest model updates, while Anthropic shared research on AI safety...
"""
(이 예제는 완전해서 "그대로" 실행할 수 있어요)
핸들 필터링
allowed_x_handles 또는 excluded_x_handles 중 하나만 사용할 수 있어요. 둘 다는 안 돼요. 각 목록은 최대 20개 핸들로 제한돼요.
원시 검색 결과 포함
기본적으로 xAI는 검색의 모델 텍스트 요약만 반환해요. 기본 게시물, 소스, 메타데이터에 프로그래매틱하게 접근하려면 XSearchTool에 include_output=True를 설정하세요(OpenAI 웹 검색의 OpenAIResponsesModelSettings.openai_include_web_search_sources와 유사). 그러면 원시 결과가 ModelResponse.native_tool_calls로 노출된 NativeToolReturnPart에서 사용할 수 있어요. 대안으로 XaiModelSettings.xai_include_x_search_output 모델 설정으로 전역 활성화할 수 있어요. 권장되는 XSearch 기능 기반 접근은 xAI 문서 참고.
코드 실행 툴
CodeExecutionTool은 에이전트가 안전한 환경에서 코드를 실행하게 해줘요. 계산 작업, 데이터 분석, 수학 연산에 완벽해요.
프로바이더 지원
| 프로바이더 | 지원 | 참고 |
|---|---|---|
| OpenAI Responses | ✅ | ModelResponse.native_tool_calls로 사용 가능한 NativeToolReturnPart에 코드 실행 출력을 포함하려면 OpenAIResponsesModelSettings.openai_include_code_execution_outputs 모델 설정을 활성화. 코드 실행이 차트 같은 이미지를 생성하면 ModelResponse.images에서 BinaryImage 객체로 사용 가능. 생성된 이미지는 에이전트 실행의 이미지 출력으로도 사용 가능 |
| ✅ | Google 툴 조합 참고 | |
| Anthropic | ✅ | 호환되는 Anthropic 모델에서 사용 가능. Pydantic AI가 호환 코드 실행 툴 버전을 자동 선택. 덮어쓰려면 Anthropic 코드 실행 툴 버전 참고 |
| xAI | ✅ | 전체 기능 지원 |
| Groq | ❌ | |
| Bedrock | ✅ | Nova 2.0 모델에서만 사용 가능 |
| OpenAI Chat Completions | ❌ | 미지원; OpenAIResponsesModel 사용 |
| Mistral | ❌ | |
| Cohere | ❌ | |
| HuggingFace | ❌ |
사용법
from pydantic_ai import Agent, CodeExecutionTool
from pydantic_ai.capabilities import NativeTool
agent = Agent('anthropic:claude-sonnet-4-6', capabilities=[NativeTool(CodeExecutionTool())])
result = agent.run_sync('Calculate the factorial of 15.')
print(result.output)
#> The factorial of 15 is **1,307,674,368,000**.
print(result.response.native_tool_calls)
"""
[
(
NativeToolCallPart(
tool_name='code_execution',
args={'command': 'python3 -c "import math; print(math.factorial(15))"'},
tool_call_id='srvtoolu_017qRH1J3XrhnpjP2XtzPCmJ',
provider_name='anthropic',
provider_details={'anthropic_tool_name': 'bash_code_execution'},
),
NativeToolReturnPart(
tool_name='code_execution',
content={
'content': [],
'return_code': 0,
'stderr': '',
'stdout': '1307674368000\n',
'type': 'bash_code_execution_result',
},
tool_call_id='srvtoolu_017qRH1J3XrhnpjP2XtzPCmJ',
timestamp=datetime.datetime(...),
provider_name='anthropic',
provider_details={'anthropic_tool_name': 'bash_code_execution'},
),
)
]
"""
(이 예제는 완전해서 "그대로" 실행할 수 있어요)
텍스트 출력 외에도 OpenAI로 코드 실행은 응답의 일부로 이미지를 생성할 수 있어요. ModelResponse.images나 이미지 출력으로 이 이미지에 접근하려면 OpenAIResponsesModelSettings.openai_include_code_execution_outputs 모델 설정이 활성화되어야 해요.
from pydantic_ai import Agent, BinaryImage, CodeExecutionTool
from pydantic_ai.capabilities import NativeTool
from pydantic_ai.models.openai import OpenAIResponsesModelSettings
agent = Agent(
'openai-responses:gpt-5.2',
capabilities=[NativeTool(CodeExecutionTool())],
output_type=BinaryImage,
model_settings=OpenAIResponsesModelSettings(openai_include_code_execution_outputs=True),
)
result = agent.run_sync('Generate a chart of y=x^2 for x=-5 to 5.')
assert isinstance(result.output, BinaryImage)
(이 예제는 완전해서 "그대로" 실행할 수 있어요)
파일 업로드
프로바이더의 Files API로 파일을 업로드하고 코드 실행 컨테이너에서 사용 가능하게 할 수 있어요. 이를 통해 에이전트가 데이터 파일을 처리하고, CSV를 분석하고, 이미지로 작업할 수 있어요. UploadedFile.provider_name이 모델 프로바이더와 일치하지 않는 파일은 무시돼요.
Anthropic
import asyncio
import anthropic
from pydantic_ai import Agent, CodeExecutionTool, UploadedFile
from pydantic_ai.capabilities import NativeTool
async def main():
# Upload a file via the Anthropic Files API
client = anthropic.AsyncAnthropic()
with open('data.csv', 'rb') as f:
file = await client.beta.files.upload(file=('data.csv', f.read(), 'text/csv'), betas=['files-api-2025-04-14'])
# Create an agent with CodeExecutionTool that has access to the uploaded file
agent = Agent(
'anthropic:claude-sonnet-4-6',
capabilities=[NativeTool(CodeExecutionTool(files=[UploadedFile(file_id=file.id, provider_name='anthropic')]))],
)
result = await agent.run('Analyze the data.csv file and summarize the key statistics.')
print(result.output)
#> The CSV file contains 1000 rows with columns: name, age, salary...
asyncio.run(main())
파일 관리, 영속성, 컨테이너 동작에 대한 자세한 내용은 Anthropic Files API 문서를 참고하세요.
OpenAI
import asyncio
from openai import AsyncOpenAI
from pydantic_ai import Agent, CodeExecutionTool, UploadedFile
from pydantic_ai.capabilities import NativeTool
async def main():
# Upload a file via the OpenAI Files API
client = AsyncOpenAI()
with open('data.csv', 'rb') as f:
file = await client.files.create(file=f, purpose='assistants')
# Create an agent with CodeExecutionTool that has access to the uploaded file
agent = Agent(
'openai-responses:gpt-5.2',
capabilities=[NativeTool(CodeExecutionTool(files=[UploadedFile(file_id=file.id, provider_name='openai')]))],
)
result = await agent.run('Analyze the data.csv file and summarize the key statistics.')
print(result.output)
#> The CSV file contains 1000 rows with columns: name, age, salary...
asyncio.run(main())
파일 관리, 컨테이너 라이프사이클, 영속성 동작에 대한 자세한 내용은 OpenAI Responses API 문서를 참고하세요.
프로바이더 지원
| 매개변수 | Anthropic | OpenAI | xAI | |
|---|---|---|---|---|
files |
✅ | ✅ | ❌ | ❌ |
이미지 생성 툴
팁
전용 이미지 모델로 애플리케이션 제어 생성·편집은 직접 이미지 생성 API를 참고하세요. 모델의 네이티브 이미지 생성을 사용하고 local=ImageGenerator(...) 또는 fallback_image_model=로 그 같은 API에 폴백하는 에이전트 툴은 ImageGeneration 기능을 참고하세요.
ImageGenerationTool은 에이전트가 이미지를 생성하게 해줘요.
프로바이더 지원
| 프로바이더 | 지원 | 참고 |
|---|---|---|
| OpenAI Responses | ✅ | 전체 기능 지원. gpt-5.2보다 새로운 모델만 지원. 기본 이미지 모델에 보내진 revised_prompt 같은 생성 이미지 메타데이터는 ModelResponse.native_tool_calls로 사용 가능한 NativeToolReturnPart에서 사용 가능 |
| ✅ | 제한된 매개변수 지원. gemini-3-pro-image, gemini-3.1-flash-image 같은 이미지 생성 모델만 지원. 이 모델들은 함수 툴을 지원하지 않으며, 이 네이티브 툴을 명시적으로 지정하지 않아도 항상 이미지 생성 옵션이 있음 |
|
| Anthropic | ❌ | |
| xAI | ❌ | |
| Groq | ❌ | |
| Bedrock | ❌ | |
| Mistral | ❌ | |
| Cohere | ❌ | |
| HuggingFace | ❌ |
사용법
생성된 이미지는 ModelResponse.images에서 BinaryImage 객체로 사용할 수 있어요:
from pydantic_ai import Agent, BinaryImage, ImageGenerationTool
from pydantic_ai.capabilities import NativeTool
agent = Agent('openai-responses:gpt-5.2', capabilities=[NativeTool(ImageGenerationTool())])
result = agent.run_sync('Tell me a two-sentence story about an axolotl with an illustration.')
print(result.output)
"""
Once upon a time, in a hidden underwater cave, lived a curious axolotl named Pip who loved to explore. One day, while venturing further than usual, Pip discovered a shimmering, ancient coin that granted wishes!
"""
assert isinstance(result.response.images[0], BinaryImage)
(이 예제는 완전해서 "그대로" 실행할 수 있어요)
Google 이미지 생성 모델로 이미지 생성은 ImageGenerationTool 네이티브 툴을 명시적으로 지정할 필요가 없어요:
from pydantic_ai import Agent, BinaryImage
agent = Agent('google:gemini-3-pro-image')
result = agent.run_sync('Tell me a two-sentence story about an axolotl with an illustration.')
print(result.output)
"""
Once upon a time, in a hidden underwater cave, lived a curious axolotl named Pip who loved to explore. One day, while venturing further than usual, Pip discovered a shimmering, ancient coin that granted wishes!
"""
assert isinstance(result.response.images[0], BinaryImage)
(이 예제는 완전해서 "그대로" 실행할 수 있어요)
ImageGenerationTool은 output_type=BinaryImage와 함께 사용해 이미지 출력을 얻을 수 있어요. ImageGenerationTool 네이티브 툴이 명시적으로 지정되지 않으면 자동으로 활성화돼요:
from pydantic_ai import Agent, BinaryImage
agent = Agent('openai-responses:gpt-5.2', output_type=BinaryImage)
result = agent.run_sync('Generate an image of an axolotl.')
assert isinstance(result.output, BinaryImage)
(이 예제는 완전해서 "그대로" 실행할 수 있어요)
구성 옵션
ImageGenerationTool은 여러 구성 매개변수를 지원해요:
from pydantic_ai import Agent, BinaryImage, ImageGenerationTool
from pydantic_ai.capabilities import NativeTool
agent = Agent(
'openai-responses:gpt-5.2',
capabilities=[
NativeTool(
ImageGenerationTool(
action='generate',
background='transparent',
input_fidelity='high',
model='gpt-image-2',
moderation='low',
output_compression=100,
output_format='png',
partial_images=3,
quality='high',
size='1024x1024',
)
)
],
output_type=BinaryImage,
)
result = agent.run_sync('Generate an image of an axolotl.')
assert isinstance(result.output, BinaryImage)
(이 예제는 완전해서 "그대로" 실행할 수 있어요)
OpenAI Responses 모델은 aspect_ratio 매개변수도 존중해요. OpenAI API가 이산 이미지 크기만 노출하므로 Pydantic AI는 '1:1' → 1024x1024, '2:3' → 1024x1536, '3:2' → 1536x1024로 매핑해요. 다른 종횡비를 제공하면 오류가 나고, size도 설정했다면 계산된 값과 일치해야 해요.
OpenAI Responses 이미지 생성 툴은 기본 action='auto'인데, 모델이 새 이미지를 생성할지 이미 컨텍스트의 이미지를 편집할지 결정해요. 어느 쪽이든 강제하려면 action='generate' 또는 action='edit'를 사용하세요. model을 설정해 툴이 사용하는 기본 이미지 생성 모델을 선택할 수도 있어요(예: model='gpt-image-2'). 이것은 에이전트의 대화 모델을 바꾸지 않아요.
Gemini 이미지 모델을 쓸 때 종횡비를 제어하려면 ImageGenerationTool을 명시적으로 포함하세요:
from pydantic_ai import Agent, BinaryImage, ImageGenerationTool
from pydantic_ai.capabilities import NativeTool
agent = Agent(
'google:gemini-3-pro-image',
capabilities=[NativeTool(ImageGenerationTool(aspect_ratio='16:9'))],
output_type=BinaryImage,
)
result = agent.run_sync('Generate a wide illustration of an axolotl city skyline.')
assert isinstance(result.output, BinaryImage)
(이 예제는 완전해서 "그대로" 실행할 수 있어요)
Google 이미지 생성 모델(Gemini 3 Pro Image부터)로 이미지 해상도를 제어하려면 size 매개변수를 사용하세요:
from pydantic_ai import Agent, BinaryImage, ImageGenerationTool
from pydantic_ai.capabilities import NativeTool
agent = Agent(
'google:gemini-3-pro-image',
capabilities=[NativeTool(ImageGenerationTool(aspect_ratio='16:9', size='4K'))],
output_type=BinaryImage,
)
result = agent.run_sync('Generate a high-resolution wide landscape illustration of an axolotl.')
assert isinstance(result.output, BinaryImage)
(이 예제는 완전해서 "그대로" 실행할 수 있어요)
자세한 내용은 API 문서를 확인하세요.
프로바이더 지원
| 매개변수 | OpenAI | |
|---|---|---|
action |
✅ (auto (기본), generate, edit) | ❌ |
background |
✅ | ❌ |
input_fidelity |
✅ | ❌ |
moderation |
✅ | ❌ |
model |
✅ (gpt-image-2, gpt-image-1.5, gpt-image-1, gpt-image-1-mini, 또는 다른 OpenAI 이미지 모델 ID) | ❌ |
output_compression |
✅ (100 (기본), jpeg 또는 webp만) | ✅ (75 (기본), jpeg만, Google Cloud만) |
output_format |
✅ | ✅ (Google Cloud만) |
partial_images |
✅ | ❌ |
quality |
✅ | ❌ |
size |
✅ (auto (기본), 1024x1024, 1024x1536, 1536x1024) | ✅ (512, 1K (기본), 2K, 4K) |
aspect_ratio |
✅ (1:1, 2:3, 3:2) | ✅ (1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9) |
참고
- OpenAI:
auto는 모델이 값을 선택하게 해요. - Google Cloud:
output_compression을 설정하면output_format을 지정하지 않을 때 기본값으로jpeg를 써요.
웹 페치 툴
팁
local=True로 선택적 로컬 폴백이 있는 모델 무관 접근은 WebFetch 기능을 참고하세요.
WebFetchTool은 에이전트가 URL 콘텐츠를 컨텍스트로 가져오게 해줘요. 웹에서 최신 정보를 가져올 수 있게 해요.
프로바이더 지원
| 프로바이더 | 지원 | 참고 |
|---|---|---|
| Anthropic | ✅ | 전체 기능 지원. URL 콘텐츠를 검색하기 위해 Anthropic의 Web Fetch Tool을 내부적으로 사용 |
| ✅ | 매개변수 지원 없음. 한도는 요청당 20 URL, URL당 최대 34MB로 고정. Google 툴 조합 참고 | |
| xAI | ❌ | 웹 탐색은 xAI에서 WebSearchTool의 일부로 구현됨 |
| OpenAI | ❌ | |
| Groq | ❌ | |
| Bedrock | ❌ | |
| Mistral | ❌ | |
| Cohere | ❌ | |
| HuggingFace | ❌ |
사용법
from pydantic_ai import Agent, WebFetchTool
from pydantic_ai.capabilities import NativeTool
agent = Agent('google:gemini-3-flash-preview', capabilities=[NativeTool(WebFetchTool())])
result = agent.run_sync('What is this? https://ai.pydantic.dev')
print(result.output)
#> A Python agent framework for building Generative AI applications.
(이 예제는 완전해서 "그대로" 실행할 수 있어요)
구성 옵션
WebFetchTool은 여러 구성 매개변수를 지원해요:
from pydantic_ai import Agent, WebFetchTool
from pydantic_ai.capabilities import NativeTool
agent = Agent(
'anthropic:claude-sonnet-4-6',
capabilities=[
NativeTool(
WebFetchTool(
allowed_domains=['ai.pydantic.dev', 'docs.pydantic.dev'],
max_uses=10,
enable_citations=True,
max_content_tokens=50000,
)
)
],
)
result = agent.run_sync(
'Compare the documentation at https://ai.pydantic.dev and https://docs.pydantic.dev'
)
print(result.output)
"""
Both sites provide comprehensive documentation for Pydantic projects. ai.pydantic.dev focuses on PydanticAI, a framework for building AI agents, while docs.pydantic.dev covers Pydantic, the data validation library. They share similar documentation styles and both emphasize type safety and developer experience.
"""
(이 예제는 완전해서 "그대로" 실행할 수 있어요)
프로바이더 지원
| 매개변수 | Anthropic | |
|---|---|---|
max_uses |
✅ | ❌ |
allowed_domains |
✅ | ❌ |
blocked_domains |
✅ | ❌ |
enable_citations |
✅ | ❌ |
max_content_tokens |
✅ | ❌ |
Anthropic 도메인 필터링
Anthropic에서는 blocked_domains 또는 allowed_domains 중 하나만 사용할 수 있어요. 둘 다는 안 돼요.
Anthropic 웹 페치 툴 버전
Pydantic AI는 dynamic_filtering 옵션을 노출하지 않아요. Anthropic에 대해 Pydantic AI는 모델 프로필과 Anthropic 클라이언트에서 웹 페치 툴 버전을 선택해요. Anthropic의 동적 필터링 웹 툴을 지원하는 모델·플랫폼에는 web_fetch_20260209, 그 외에는 web_fetch_20250910을 선택해요. WebFetchTool은 레거시 Amazon Bedrock과 Vertex AI Anthropic 클라이언트에서 사용할 수 없으므로, AsyncAnthropicBedrock 또는 AsyncAnthropicVertex와 함께 쓰면 Pydantic AI가 UserError를 발생시켜요. 현재 모델 지원과 플랫폼 가용성은 Anthropic 웹 페치 문서와 툴 참조 참고.
CodeExecutionTool은 Anthropic의 독립형 코드 실행 툴을 원할 때만 추가하세요. web_fetch_20260209를 사용하는 데는 필요하지 않아요. _20260209 웹 툴의 Zero Data Retention 동작은 Anthropic의 서버 툴 문서를 참고하세요.
메모리 툴
MemoryTool은 에이전트가 메모리를 사용하게 해줘요.
프로바이더 지원
| 프로바이더 | 지원 | 참고 |
|---|---|---|
| Anthropic | ✅ | 특정 하위 명령을 구현하는 memory라는 툴이 정의돼 있어야 함. 아래 문서화된 대로 anthropic.lib.tools.BetaAbstractMemoryTool의 서브클래스를 사용할 수 있음 |
| ❌ | ||
| OpenAI | ❌ | |
| Groq | ❌ | |
| Bedrock | ❌ | |
| Mistral | ❌ | |
| Cohere | ❌ | |
| HuggingFace | ❌ |
사용법
Anthropic SDK는 직접 메모리 저장 솔루션(예: 데이터베이스, 클라우드 저장, 암호화 파일 등)을 만들기 위해 서브클래싱할 수 있는 추상 BetaAbstractMemoryTool 클래스를 제공해요. 그들의 LocalFilesystemMemoryTool 예제가 출발점이 될 수 있어요.
다음 예제는 특정 메모리를 하드코딩한 서브클래스를 사용해요. Pydantic AI에 관한 부분은 MemoryTool 네이티브 툴과, 명령을 BetaAbstractMemoryTool 서브클래스의 call 메서드로 전달하는 memory 툴 정의예요.
from typing import Any
from anthropic.lib.tools import BetaAbstractMemoryTool
from anthropic.types.beta import (
BetaMemoryTool20250818CreateCommand,
BetaMemoryTool20250818DeleteCommand,
BetaMemoryTool20250818InsertCommand,
BetaMemoryTool20250818RenameCommand,
BetaMemoryTool20250818StrReplaceCommand,
BetaMemoryTool20250818ViewCommand,
)
from pydantic_ai import Agent, MemoryTool
from pydantic_ai.capabilities import NativeTool
class FakeMemoryTool(BetaAbstractMemoryTool):
def view(self, command: BetaMemoryTool20250818ViewCommand) -> str:
return 'The user lives in Mexico City.'
def create(self, command: BetaMemoryTool20250818CreateCommand) -> str:
return f'File created successfully at {command.path}'
def str_replace(self, command: BetaMemoryTool20250818StrReplaceCommand) -> str:
return f'File {command.path} has been edited'
def insert(self, command: BetaMemoryTool20250818InsertCommand) -> str:
return f'Text inserted at line {command.insert_line} in {command.path}'
def delete(self, command: BetaMemoryTool20250818DeleteCommand) -> str:
return f'File deleted: {command.path}'
def rename(self, command: BetaMemoryTool20250818RenameCommand) -> str:
return f'Renamed {command.old_path} to {command.new_path}'
def clear_all_memory(self) -> str:
return 'All memory cleared'
fake_memory = FakeMemoryTool()
agent = Agent('anthropic:claude-sonnet-4-6', capabilities=[NativeTool(MemoryTool())])
@agent.tool_plain
def memory(**command: Any) -> Any:
return fake_memory.call(command)
result = agent.run_sync('Remember that I live in Mexico City')
print(result.output)
"""
Got it! I've recorded that you live in Mexico City. I'll remember this for future reference.
"""
result = agent.run_sync('Where do I live?')
print(result.output)
#> You live in Mexico City.
(이 예제는 완전해서 "그대로" 실행할 수 있어요)
어드바이저 툴
AdvisorTool은 실행 모델이 생성 중에 다른 모델에 상담하게 해줘요. 현재 모델 호환성은 Anthropic과 OpenRouter 문서를 참고하세요.
프로바이더 지원
| 프로바이더 | 지원 | 참고 |
|---|---|---|
| Anthropic | ✅ | Claude API와 AWS의 Claude Platform에서 사용 가능 |
| OpenRouter | ✅ | 어떤 실행 모델과도 작동 |
| OpenAI | ❌ | |
| ❌ | ||
| xAI | ❌ | |
| Groq | ❌ | |
| Bedrock | ❌ | |
| Mistral | ❌ | |
| Cohere | ❌ | |
| HuggingFace | ❌ |
사용법
from pydantic_ai import AdvisorTool, Agent
from pydantic_ai.capabilities import NativeTool
agent = Agent(
'anthropic:claude-sonnet-5',
capabilities=[NativeTool(AdvisorTool(model='claude-opus-4-8'))],
)
result = agent.run_sync('Design a caching strategy for our API. Consult your advisor first.')
print(result.output)
OpenRouter에서는 아무 openrouter: 실행기를 사용하고 model에 OpenRouter 모델 슬러그(예: anthropic/claude-opus-4.8)를 전달하세요. Pydantic AI는 forward_transcript=false를 보내요. max_uses와 caching은 무시돼요. Pydantic AI는 ModelResponse.provider_details ['server_tool_use'] 아래 집계 상담 횟수를 노출해요.
Anthropic에서는 Pydantic AI가 일반텍스트와 암호화된 어드바이저 결과를 메시지 이력에 보존하고, 툴이 더 이상 활성화되지 않으면 어드바이저 블록을 제거해요. 어드바이저가 실행되는 동안 스트리밍이 일시정지돼요. 어드바이저 사용량은 RequestUsage.details의 advisor_* 키 아래 보고되고 실행기의 최상위 토큰 총계에서 제외돼요.
구성 옵션
| 매개변수 | Anthropic | OpenRouter |
|---|---|---|
model |
✅ (필수 — 상담할 어드바이저 모델) | ✅ (필수 — OpenRouter 카탈로그 슬러그) |
max_uses |
✅ (요청당 어드바이저 상담 상한) | ❌ (고정 gateway 한도; 무시됨) |
max_tokens |
✅ (어드바이저 출력 토큰 상한, 최소 1024; 결과에 stop_reason이 생김) |
✅ (max_completion_tokens에 매핑) |
caching |
✅ ('5m' 또는 '1h' — 어드바이저 컨텍스트의 임시 캐싱) |
❌ (대응물 없음; 무시됨) |
MCP 서버 툴
팁
자동 로컬 폴백이 있는 모델 무관 접근은 MCP 기능을 참고하세요.
MCPServerTool은 에이전트가 원격 MCP 서버를 사용하게 해줘요. 통신은 모델 프로바이더가 처리해요.
이것은 MCP 서버가 프로바이더가 도달할 수 있는 공개 URL에 있어야 하고 Pydantic AI의 에이전트 측 MCP 지원의 많은 고급 기능을 지원하지 않지만, Pydantic AI로의 왕복이 없어 더 최적화된 컨텍스트 사용과 캐싱, 더 빠른 성능을 낼 수 있어요.
프로바이더 지원
| 프로바이더 | 지원 | 참고 |
|---|---|---|
| OpenAI Responses | ✅ | 전체 기능 지원. x-openai-connector:<connector_id> 특수 URL로 Connectors 사용 가능 |
| Anthropic | ✅ | 전체 기능 지원 |
| xAI | ✅ | 전체 기능 지원 |
| ❌ | 미지원 | |
| Groq | ❌ | 미지원 |
| OpenAI Chat Completions | ❌ | 미지원 |
| Bedrock | ❌ | 미지원 |
| Mistral | ❌ | 미지원 |
| Cohere | ❌ | 미지원 |
| HuggingFace | ❌ | 미지원 |
사용법
from pydantic_ai import Agent, MCPServerTool
from pydantic_ai.capabilities import NativeTool
agent = Agent(
'anthropic:claude-sonnet-4-6',
capabilities=[
NativeTool(
MCPServerTool(
id='deepwiki',
url='https://mcp.deepwiki.com/mcp', # (1)
)
)
]
)
result = agent.run_sync('Tell me about the pydantic/pydantic-ai repo.')
print(result.output)
"""
The pydantic/pydantic-ai repo is a Python agent framework for building Generative AI applications.
"""
- DeepWiki MCP 서버는 권한 부여가 필요하지 않아요.
(이 예제는 완전해서 "그대로" 실행할 수 있어요)
OpenAI에서는 MCP 서버 툴에 접근하려면 Responses API를 사용해야 해요:
from pydantic_ai import Agent, MCPServerTool
from pydantic_ai.capabilities import NativeTool
agent = Agent(
'openai-responses:gpt-5.2',
capabilities=[
NativeTool(
MCPServerTool(
id='deepwiki',
url='https://mcp.deepwiki.com/mcp', # (1)
)
)
]
)
result = agent.run_sync('Tell me about the pydantic/pydantic-ai repo.')
print(result.output)
"""
The pydantic/pydantic-ai repo is a Python agent framework for building Generative AI applications.
"""
- DeepWiki MCP 서버는 권한 부여가 필요하지 않아요.
(이 예제는 완전해서 "그대로" 실행할 수 있어요)
구성 옵션
MCPServerTool은 커스텀 MCP 서버를 위한 여러 구성 매개변수를 지원해요:
import os
from pydantic_ai import Agent, MCPServerTool
from pydantic_ai.capabilities import NativeTool
agent = Agent(
'openai-responses:gpt-5.2',
capabilities=[
NativeTool(
MCPServerTool(
id='github',
url='https://api.githubcopilot.com/mcp/',
authorization_token=os.getenv('GITHUB_ACCESS_TOKEN', 'mock-access-token'), # (1)
allowed_tools=['search_repositories', 'list_commits'],
description='GitHub MCP server',
headers={'X-Custom-Header': 'custom-value'},
)
)
]
)
result = agent.run_sync('Tell me about the pydantic/pydantic-ai repo.')
print(result.output)
"""
The pydantic/pydantic-ai repo is a Python agent framework for building Generative AI applications.
"""
- GitHub MCP 서버는 권한 부여 토큰이 필요해요.
OpenAI Responses에서는 x-openai-connector: 특수 URL로 connector를 사용할 수 있어요:
(이 예제는 완전해서 "그대로" 실행할 수 있어요)
import os
from pydantic_ai import Agent, MCPServerTool
from pydantic_ai.capabilities import NativeTool
agent = Agent(
'openai-responses:gpt-5.2',
capabilities=[
NativeTool(
MCPServerTool(
id='google-calendar',
url='x-openai-connector:connector_googlecalendar',
authorization_token=os.getenv('GOOGLE_API_KEY', 'mock-api-key'), # (1)
)
)
]
)
result = agent.run_sync('What do I have on my calendar today?')
print(result.output)
#> You're going to spend all day playing with Pydantic AI.
- OpenAI의 Google Calendar connector는 권한 부여 토큰이 필요해요.
(이 예제는 완전해서 "그대로" 실행할 수 있어요)
프로바이더 지원
| 매개변수 | OpenAI | Anthropic | xAI |
|---|---|---|---|
authorization_token |
✅ | ✅ | ✅ |
allowed_tools |
✅ | ✅ | ✅ |
description |
✅ | ❌ | ✅ |
headers |
✅ | ❌ | ✅ |
파일 검색 툴
FileSearchTool은 에이전트가 벡터 검색으로 업로드된 파일을 검색하게 해줘요. 완전히 관리되는 검색 증강 생성(RAG) 시스템을 제공해요. 이 툴은 파일 저장, 청킹, 임베딩 생성, 프롬프트로의 컨텍스트 주입을 처리해요.
프로바이더 지원
| 프로바이더 | 지원 | 참고 |
|---|---|---|
| OpenAI Responses | ✅ | 전체 기능 지원. OpenAI Files API로 파일을 벡터 스토어에 업로드해야 함. ModelResponse.native_tool_calls로 사용 가능한 NativeToolReturnPart에 검색 결과를 포함하려면 OpenAIResponsesModelSettings.openai_include_file_search_results 모델 설정을 활성화 |
| Google (Gemini) | ✅ | Gemini Files API로 파일을 업로드해야 함. 파일은 48시간 후 자동 삭제. 파일당 최대 2 GB, 프로젝트당 20 GB 지원. Google 툴 조합 참고 |
| xAI | ✅ | xAI 컬렉션 검색에 매핑. 컬렉션 ID 필요. NativeToolReturnPart에 검색 결과를 포함하려면 XaiModelSettings.xai_include_collections_search_output 모델 설정을 활성화 |
| Google Cloud | ❌ | |
| Anthropic | ❌ | 미지원 |
| Groq | ❌ | 미지원 |
| OpenAI Chat Completions | ❌ | 미지원 |
| Bedrock | ❌ | 미지원 |
| Mistral | ❌ | 미지원 |
| Cohere | ❌ | 미지원 |
| HuggingFace | ❌ | 미지원 |
사용법
OpenAI Responses
OpenAI에서는 먼저 파일을 벡터 스토어에 업로드한 다음 FileSearchTool을 사용할 때 벡터 스토어 ID를 참조해야 해요.
import asyncio
from pydantic_ai import Agent, FileSearchTool
from pydantic_ai.capabilities import NativeTool
from pydantic_ai.models.openai import OpenAIResponsesModel
async def main():
model = OpenAIResponsesModel('gpt-5.2')
with open('my_document.txt', 'rb') as f:
file = await model.client.files.create(file=f, purpose='assistants')
vector_store = await model.client.vector_stores.create(name='my-docs')
await model.client.vector_stores.files.create(
vector_store_id=vector_store.id,
file_id=file.id
)
agent = Agent(
model,
capabilities=[NativeTool(FileSearchTool(file_store_ids=[vector_store.id]))]
)
result = await agent.run('What information is in my documents about pydantic?')
print(result.output)
#> Based on your documents, Pydantic is a data validation library for Python...
asyncio.run(main())
Google (Gemini)
Gemini에서는 먼저 Files API로 파일 검색 스토어를 생성한 다음 파일 검색 스토어 이름을 참조해야 해요.
import asyncio
from pydantic_ai import Agent, FileSearchTool
from pydantic_ai.capabilities import NativeTool
from pydantic_ai.models.google import GoogleModel
async def main():
model = GoogleModel('gemini-3-flash-preview')
store = await model.client.aio.file_search_stores.create(
config={'display_name': 'my-docs'}
)
with open('my_document.txt', 'rb') as f:
await model.client.aio.file_search_stores.upload_to_file_search_store(
file_search_store_name=store.name,
file=f,
config={'mime_type': 'text/plain'}
)
agent = Agent(
model,
capabilities=[NativeTool(FileSearchTool(file_store_ids=[store.name]))]
)
result = await agent.run('Summarize the key points from my uploaded documents.')
print(result.output)
#> The documents discuss the following key points: ...
asyncio.run(main())
xAI
xAI에서는 FileSearchTool이 컬렉션 검색 툴에 매핑돼요. file_store_ids로 컬렉션 ID를 전달하세요.
import asyncio
from pydantic_ai import Agent, FileSearchTool
from pydantic_ai.capabilities import NativeTool
async def main():
agent = Agent(
'xai:grok-4.3',
capabilities=[NativeTool(FileSearchTool(file_store_ids=['collection_abc123']))]
)
result = await agent.run('What does the collection say about pydantic?')
print(result.output)
#> Based on the collection, Pydantic is ...
asyncio.run(main())
xAI의 컬렉션 검색은 결과 수, 랭킹 지침, 검색 전략을 제어하는 옵션도 받아요. 이것들은 FileSearchTool의 max_num_results, instructions, retrieval_mode 필드에 매핑돼요. 생략하면 서버가 자체 기본값(10개 결과, 하이브리드 검색)을 적용해요.
import asyncio
from pydantic_ai import Agent, FileSearchTool
from pydantic_ai.capabilities import NativeTool
async def main():
agent = Agent(
'xai:grok-4.3',
capabilities=[
NativeTool(
FileSearchTool(
file_store_ids=['collection_abc123'],
max_num_results=5,
instructions='Focus on up-to-date, highly relevant documents.',
retrieval_mode='semantic',
)
)
],
)
result = await agent.run('What does the collection say about pydantic?')
print(result.output)
#> Based on the collection, Pydantic is ...
asyncio.run(main())
API 참조
완전한 API 문서는 API Reference를 참고하세요.