PydanticAI: Pydantic으로 제너레이티브 AI 앱을 구축하면 프로덕션급 AI 앱을 더 쉽게 구축할 수 있습니다.

최신 AI 리소스8 개월 전에 게시 됨 AI 공유 서클
2.6K 00

일반 소개

PydanticAI는 생성형 AI 애플리케이션의 개발을 간소화하도록 설계된 Pydantic 기반 Python 에이전트 프레임워크입니다. Pydantic 팀이 개발한 이 프레임워크는 다양한 모델(예: OpenAI, Gemini, Groq 등)을 지원하며 유형 안전 제어 흐름과 에이전트 조합을 제공하며, 구조화된 응답 검증 및 스트리밍 응답을 통해 생성 AI 애플리케이션의 효율성과 안정성을 보장합니다. 고유한 종속성 주입 시스템은 테스트 및 반복 개발을 용이하게 하며, 애플리케이션 성능 디버깅 및 모니터링을 위해 Logfire를 통합합니다.PydanticAI는 현재 초기 베타 버전이며 API는 변경될 수 있으며 사용자 피드백을 환영합니다.

 

기능 목록

  • 다중 모델 지원OpenAI, Gemini, Groq 및 기타 여러 생성 AI 모델과 호환됩니다.
  • 유형 안전데이터 유형 보안을 보장하기 위해 Pydantic을 사용한 구조화된 응답 유효성 검사.
  • 종속성 주입 시스템간편한 테스트와 반복 개발을 위해 유형 안전 종속성 주입 기능을 제공합니다.
  • 스트리밍 응답스트리밍 응답 및 유효성 검사를 지원하여 애플리케이션 응답성과 안정성을 개선합니다.
  • Logfire 통합생성형 AI 애플리케이션의 성능과 동작을 디버깅하고 모니터링하는 데 사용됩니다.
  • 간단한 인터페이스다른 모델과 쉽게 확장하고 통합할 수 있도록 깔끔한 인터페이스를 제공합니다.

 

도움말 사용

설치 프로세스

  1. PydanticAI 설치파이썬 버전이 3.9 이상인지 확인하고 다음 명령어를 사용하여 PydanticAI를 설치합니다:
   pip install pydantic-ai
  1. 종속성 설치PydanticAI는 여러 핵심 라이브러리 및 LLM API에 의존하며, 이러한 종속성은 설치 중에 자동으로 처리됩니다.

사용 가이드라인

간단한 프록시 만들기

  1. 에이전트 정의: 간단한 에이전트를 만들고 사용할 모델을 지정합니다.
   from pydantic_ai import Agent
agent = Agent(
'gemini-1.5-flash',
system_prompt='Be concise, reply with one sentence.',
)
  1. 에이전트 실행간단한 대화를 위해 에이전트를 동시에 실행합니다.
   result = agent.run_sync('Where does "hello world" come from?')
print(result.data)

복잡한 프록시 예제

  1. 종속성 및 결과 모델 정의Pydantic을 사용하여 종속성 및 결과 모델을 정의합니다.
   from dataclasses import dataclass
from pydantic import BaseModel, Field
from pydantic_ai import Agent, RunContext
from bank_database import DatabaseConn
@dataclass
class SupportDependencies:
customer_id: int
db: DatabaseConn
class SupportResult(BaseModel):
support_advice: str = Field(description='Advice returned to the customer')
block_card: bool = Field(description="Whether to block the customer's card")
risk: int = Field(description='Risk level of query', ge=0, le=10)
  1. 지원 상담원 만들기시스템 힌트 및 유틸리티 기능을 정의합니다.
   support_agent = Agent(
'openai:gpt-4o',
deps_type=SupportDependencies,
result_type=SupportResult,
system_prompt=(
'You are a support agent in our bank, give the '
'customer support and judge the risk level of their query.'
),
)
@support_agent.system_prompt
async def add_customer_name(ctx: RunContext[SupportDependencies]) -> str:
customer_name = await ctx.deps.db.customer_name(id=ctx.deps.customer_id)
return f"The customer's name is {customer_name!r}"
@support_agent.tool
async def customer_balance(ctx: RunContext[SupportDependencies], include_pending: bool) -> float:
"""Returns the customer's current account balance."""
return await ctx.deps.db.customer_balance(id=ctx.deps.customer_id, include_pending=include_pending)
  1. 지원 에이전트 실행: 정의된 종속성으로 에이전트를 실행합니다.
   async def main():
deps = SupportDependencies(customer_id=123, db=DatabaseConn())
result = await support_agent.run('What is my balance?', deps=deps)
print(result.data)
# 输出示例:support_advice='Hello John, your current account balance, including pending transactions, is $123.45.' block_card=False risk=1
result = await support_agent.run('I just lost my card!', deps=deps)
print(result.data)
# 输出示例:support_advice="I'm sorry to hear that, John. Your card has been blocked for security reasons." block_card=True risk=7

디버깅 및 모니터링

PydanticAI는 생성형 AI 애플리케이션의 성능과 동작을 디버깅하고 모니터링하기 위해 Logfire를 통합합니다. Logfire를 사용하면 에이전트 작동을 실시간으로 확인하고, 응답 데이터를 분석하고, 애플리케이션 성능을 최적화할 수 있습니다.

피드백 및 개선

PydanticAI는 현재 초기 베타 버전이며 API는 변경될 수 있습니다. 사용 중 문제가 발생하거나 개선할 사항이 있으면 GitHub를 통해 피드백을 제출해 주시기 바랍니다.

© 저작권 정책
AiPPT

관련 문서

댓글 없음

댓글에 참여하려면 로그인해야 합니다!
지금 로그인
없음
댓글 없음...