PydanticAI:一個基于 Python 的新代理框架,用于構建生產級 LLM 支持的應用程序
01、概述
在AI技術飛速發展的今天,越來越多的應用程序開始依賴大語言模型(LLM)來提供智能化功能。然而,將LLM應用于實際生產環境并非易事。開發者往往會面臨如下挑戰:
- 模型響應不一致,無法始終保證輸出的準確性。
- 缺乏穩健性,在高并發場景下難以保持系統穩定。
- 類型安全性薄弱,導致數據結構不符合預期。
在這種背景下,如何開發一款能夠為用戶提供可靠、精準且上下文適宜的輸出的LLM應用,成為了開發者的首要任務。傳統方法在處理這些問題時顯得力不從心,尤其是當需要高質量和結構化響應時,開發者往往難以快速擴展解決方案。
今天,我們來聊聊一款專為解決這些痛點而生的全新框架——PydanticAI。
02、什么是PydanticAI?
PydanticAI 是一款基于 Python 的智能代理框架,由著名的 Pydantic 團隊開發。它的設計初衷是幫助開發者打造生產級別的LLM應用。PydanticAI 無縫結合了 Pydantic 的強類型校驗功能,并且對LLM模型具備高度的靈活性和兼容性。
這意味著開發者可以在不同的LLM之間自由切換,同時享受Pydantic所帶來的可靠性和安全性。這種“模型無關性”大大提升了開發效率,尤其是在不斷變化的AI生態中,開發者可以靈活選擇最佳模型來滿足業務需求。
03、PydanticAI 的核心功能
1. 類型安全的響應校驗
PydanticAI 最顯著的特點之一是其對LLM輸出的強類型校驗功能。通過 Pydantic,開發者能夠確保模型返回的數據結構與預期完全一致。這在生產環境中尤為重要,因為不一致的響應可能會引發系統錯誤,甚至影響用戶體驗。
示例:開發者希望LLM返回一個用戶信息對象(包括用戶名、郵箱和年齡)。PydanticAI 能夠自動校驗這些字段是否符合預期類型和格式。即使模型偶爾返回錯誤或缺失數據,框架也能及時捕獲并提醒,確保系統運行的可靠性。
2. 支持流式響應
PydanticAI 支持流式響應的生成與驗證。這一特性在需要處理高并發請求或大規模數據時尤為關鍵。例如,實時聊天系統或視頻字幕生成工具,能夠利用這一功能一邊接收數據,一邊校驗其合法性,從而提升整體性能。
3. Logfire 集成:調試與監控
PydanticAI 與 Logfire 集成,提供調試與監控功能。開發者可以通過 Logfire 輕松追蹤系統日志、診斷問題,并快速解決故障。這種高可觀測性對于生產級應用尤為重要,因為在實際運行中,任何問題都需要被迅速定位和修復。
4. 模型無關性
PydanticAI 并不依賴于特定的LLM模型。無論是OpenAI的GPT系列、Meta的LLaMA,還是其他開源模型,開發者都可以輕松接入。這種靈活性為不同業務場景提供了更多選擇,避免了被某單一技術棧鎖定的風險。
04、PydanticAI 為開發者帶來的價值
1. 可靠性提升
PydanticAI 的類型校驗和結構化響應能力幫助開發者大幅減少運行時錯誤。無論是小型聊天機器人還是復雜的企業級應用,PydanticAI 都能保證系統輸出的一致性和可靠性。
2. 開發效率提高
由于其簡潔易用的接口和內置功能,開發者可以專注于核心業務邏輯,而不必花費大量時間在數據驗證、錯誤處理等底層問題上。根據早期用戶反饋,PydanticAI 顯著縮短了開發周期,讓開發者能夠更快地將產品推向市場。
3. 迭代速度加快
PydanticAI 提供了一套以評估驅動的開發工具,開發者可以快速對LLM進行微調和測試,從而在產品上線前確保性能達標??蚣軆戎玫恼{試與監控功能,也進一步支持持續優化和高效運維。
4. 降低運維成本
通過 Logfire 的調試和監控,團隊可以更快速地識別并解決問題,減少因系統故障導致的停機時間。對于運行在生產環境中的應用,這意味著更高的用戶滿意度和更低的運營成本。
05、實戰案例:PydanticAI 的早期用戶反饋
雖然 PydanticAI 還是一款新興框架,但它已經吸引了不少開發者的關注。根據初期用戶反饋,這款框架在處理復雜LLM任務時表現出了出色的簡便性和高效性。
- 案例一:某初創公司使用 PydanticAI 開發了一款企業內部聊天機器人,幫助員工快速獲取公司政策和信息。通過強類型校驗和流式響應功能,這款機器人在處理數千個并發請求時,依舊能夠提供精準的回答。
- 案例二:一家大型電商企業利用 PydanticAI 優化了客戶服務系統,顯著降低了開發時間,并減少了因LLM不一致響應導致的用戶投訴。
#使用案例
from dataclasses import dataclass
from pydantic import BaseModel, Field
from pydantic_ai import Agent, RunContext
from bank_database import DatabaseConn
# SupportDependencies is used to pass data, connections, and logic into the model that will be needed when running
# system prompt and tool functions. Dependency injection provides a type-safe way to customise the behavior of your agents.
@dataclass
class SupportDependencies:
customer_id: int
db: DatabaseConn
# This pydantic model defines the structure of the result returned by the agent.
class SupportResult(BaseModel):
support_advice: str = Field(descriptinotallow='Advice returned to the customer')
block_card: bool = Field(descriptinotallow="Whether to block the customer's card")
risk: int = Field(descriptinotallow='Risk level of query', ge=0, le=10)
# This agent will act as first-tier support in a bank.
# Agents are generic in the type of dependencies they accept and the type of result they return.
# In this case, the support agent has type `Agent[SupportDependencies, SupportResult]`.
support_agent = Agent(
'openai:gpt-4o',
deps_type=SupportDependencies,
# The response from the agent will, be guaranteed to be a SupportResult,
# if validation fails the agent is prompted to try again.
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.'
),
)
# Dynamic system prompts can can make use of dependency injection.
# Dependencies are carried via the `RunContext` argument, which is parameterized with the `deps_type` from above.
# If the type annotation here is wrong, static type checkers will catch it.
@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}"
# `tool` let you register functions which the LLM may call while responding to a user.
# Again, dependencies are carried via `RunContext`, any other arguments become the tool schema passed to the LLM.
# Pydantic is used to validate these arguments, and errors are passed back to the LLM so it can retry.
@support_agent.tool
async def customer_balance(
ctx: RunContext[SupportDependencies], include_pending: bool
) -> float:
"""Returns the customer's current account balance."""
# The docstring of a tool is also passed to the LLM as the description of the tool.
# Parameter descriptions are extracted from the docstring and added to the parameter schema sent to the LLM.
balance = await ctx.deps.db.customer_balance(
id=ctx.deps.customer_id,
include_pending=include_pending,
)
return balance
... # In a real use case, you'd add more tools and a longer system prompt
async def main():
deps = SupportDependencies(customer_id=123, db=DatabaseConn())
# Run the agent asynchronously, conducting a conversation with the LLM until a final response is reached.
# Even in this fairly simple case, the agent will exchange multiple messages with the LLM as tools are called to retrieve a result.
result = await support_agent.run('What is my balance?', deps=deps)
# The result will be validated with Pydantic to guarantee it is a `SupportResult`, since the agent is generic,
# it'll also be typed as a `SupportResult` to aid with static type checking.
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. We are temporarily blocking your card to prevent unauthorized transactions." block_card=True risk=8
"""
from pydantic_ai import Agent
# Define a very simple agent including the model to use, you can also set the model when running the agent.
agent = Agent(
'gemini-1.5-flash',
# Register a static system prompt using a keyword argument to the agent.
# For more complex dynamically-generated system prompts, see the example below.
system_prompt='Be concise, reply with one sentence.',
)
# Run the agent synchronously, conducting a conversation with the LLM.
# Here the exchange should be very short: PydanticAI will send the system prompt and the user query to the LLM,
# the model will return a text response. See below for a more complex run.
result = agent.run_sync('Where does "hello world" come from?')
print(result.data)
"""
The first known use of "hello, world" was in a 1974 textbook about the C programming language."""
06、未來展望
隨著AI技術的不斷進步,像 PydanticAI 這樣的工具將在行業中扮演越來越重要的角色。無論是構建一個簡單的對話機器人,還是開發一個復雜的智能系統,PydanticAI 都能夠為開發者提供強大的支持。
在未來,我們有理由期待更多開發者采納這款工具,從而推動LLM技術在各行各業的廣泛應用。
07、結語
如果你正在尋求一款能夠讓LLM開發變得更加簡單、高效的框架,PydanticAI 無疑是一個值得嘗試的選擇。它通過類型安全、流式響應支持、調試與監控工具,為開發者提供了從開發到生產的一站式解決方案。
趕緊試試PydanticAI,讓你的LLM應用開發如虎添翼!
參考:
本文轉載自公眾號Halo咯咯 作者:基咯咯
原文鏈接:??https://mp.weixin.qq.com/s/ZQsdR1qHsi0BRjBPcXc4-g??
