직접 모델 요청
직접 모델 요청 (Direct Model Requests)
direct 모듈은 LLM에 명령형 요청을 보내는 저수준 메서드를 제공해요. 유일한 추상화는 입력·출력 스키마 변환이며, 모든 모델을 동일한 API로 쓸 수 있게 해주죠.
이 메서드들은 Model 구현을 얇게 감싼 것으로, Agent의 전체 기능이 필요 없을 때 더 단순한 인터페이스를 제공해요.
다음 함수들을 사용할 수 있어요.
model_request: 모델에 비스트리밍 비동기 요청model_request_sync: 모델에 비스트리밍 동기 요청model_request_stream: 모델에 스트리밍 비동기 요청model_request_stream_sync: 모델에 스트리밍 동기 요청
출처: 문서
본문
기본 예제 (Basic Example)
direct API를 사용해 기본 요청을 보내는 간단한 예제예요.
direct_basic.py
from pydantic_ai import ModelRequest
from pydantic_ai.direct import model_request_sync
# Make a synchronous request to the model
model_response = model_request_sync(
'anthropic:claude-haiku-4-5',
[ModelRequest.user_text_prompt('What is the capital of France?')]
)
print(model_response.parts[0].content)
#> The capital of France is Paris.
print(model_response.usage)
#> RequestUsage(input_tokens=56, output_tokens=7)
(이 예제는 완전해서 그대로 실행할 수 있어요)
Note
지시(instructions)는 메시지 히스토리 전체에 걸쳐 누적되지 않아요. 여러 ModelRequest가 instructions를 포함하면, direct API는 가장 최근 것을 사용해요.
도구 호출이 있는 고급 예제 (Advanced Example with Tool Calling)
direct API를 함수/도구 호출과 함께 쓸 수도 있어요.
여기에서도 Pydantic을 사용해 도구용 JSON 스키마를 만들 수 있어요.
from typing import Literal
from pydantic import BaseModel
from pydantic_ai import ModelRequest, ToolDefinition
from pydantic_ai.direct import model_request
from pydantic_ai.models import ModelRequestParameters
class Divide(BaseModel):
"""Divide two numbers."""
numerator: float
denominator: float
on_inf: Literal['error', 'infinity'] = 'infinity'
async def main():
# Make a request to the model with tool access
model_response = await model_request(
'openai:gpt-5-nano',
[ModelRequest.user_text_prompt('What is 123 / 456?')],
model_request_parameters=ModelRequestParameters(
function_tools=[
ToolDefinition(
name=Divide.__name__.lower(),
description=Divide.__doc__,
parameters_json_schema=Divide.model_json_schema(),
)
],
allow_text_output=True, # Allow model to either use tools or respond directly
),
)
print(model_response)
"""
ModelResponse(
parts=[
ToolCallPart(
tool_name='divide',
args={'numerator': '123', 'denominator': '456'},
tool_call_id='pyd_ai_2e0e396768a14fe482df90a29a78dc7b',
)
],
usage=RequestUsage(input_tokens=55, output_tokens=7),
model_name='gpt-5-nano',
timestamp=datetime.datetime(...),
)
"""
(이 예제를 실행하려면 asyncio를 임포트하고 asyncio.run(main())을 추가하세요. 다른 변경은 필요 없어요.)
direct API를 쓸 때 vs Agent
direct API는 다음과 같은 경우에 이상적이에요.
- 모델 상호작용을 더 직접적으로 제어해야 할 때
- 모델 요청 주변에 맞춤 동작을 구현하고 싶을 때
- 모델 상호작용 위에 자신만의 추상화를 구축할 때
대부분의 애플리케이션 사용 사례에서는 더 높은 수준의 Agent API가 더 편리한 인터페이스를 제공해요. 네이티브 도구 실행, 재시도, 구조화된 출력 파싱 등의 추가 기능을 갖추고 있죠.
OpenTelemetry 또는 Logfire 계측
에이전트와 마찬가지로, 몇 줄만 추가하면 OpenTelemetry/Logfire 계측을 활성화할 수 있어요.
direct_instrumented.py
import logfire
from pydantic_ai import ModelRequest
from pydantic_ai.direct import model_request_sync
logfire.configure()
logfire.instrument_pydantic_ai()
# Make a synchronous request to the model
model_response = model_request_sync(
'anthropic:claude-haiku-4-5',
[ModelRequest.user_text_prompt('What is the capital of France?')],
)
print(model_response.parts[0].content)
#> The capital of France is Paris.
(이 예제는 완전해서 그대로 실행할 수 있어요)
호출 단위로 OpenTelemetry를 활성화할 수도 있어요.
direct_instrumented.py
import logfire
from pydantic_ai import ModelRequest
from pydantic_ai.direct import model_request_sync
logfire.configure()
# Make a synchronous request to the model
model_response = model_request_sync(
'anthropic:claude-haiku-4-5',
[ModelRequest.user_text_prompt('What is the capital of France?')],
instrument=True
)
print(model_response.parts[0].content)
#> The capital of France is Paris.
자세한 내용은 디버깅 및 모니터링을 참고하세요. Logfire 없이 순수 OpenTelemetry로 계측하는 방법도 포함돼 있어요.