pydantic ai集成ollama简单试用

就是一个示例学习,体验下pydantic ai,llm 基于了ollama

参考代码

  • app.py

一个集成ollama 的测试

import asyncio
from  openai import AsyncOpenAI
from pydantic import BaseModel,Field
from pydantic_ai import Agent,RunContext
from pydantic_ai.models.openai import OpenAIModel
from typing import Any

USERS = {
    "dalong":4
}

client = AsyncOpenAI(api_key='demo',base_url="http://localhost:11434/v1")
model = OpenAIModel('qwen2.5:3b', openai_client=client)

class UserResult(BaseModel):
    age: int = Field(description='年龄')


agent = Agent(
    model= model,
    result_retries=3,
    )


@agent.system_prompt
async def add_customer_name(ctx: RunContext[Any]) -> str:
    customer_name =  ctx.deps["user_name"]
    print("from system_prompt",customer_name)
    return f"姓名是 {customer_name!r}"


@agent.tool
async def get_user_age(ctx: RunContext[Any]) -> int:
   """返回用户年龄 """
   user_age = USERS.get(ctx.deps["user_name"])
   print("from tools",user_age)
   return user_age

async def main():
    result = await agent.run('我的年龄是多少?', deps={"user_name": "dalong"})
    # 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)

if __name__ == "__main__":
    asyncio.run(main())
  • 效果

注意模型太小的函数调用可能不会太稳定

说明

对于工具的使用需要支持函数调用,推荐使用最新的ollama 以及模式

参考资料

https://github.com/pydantic/pydantic-ai

https://ai.pydantic.dev/install/

posted on   荣锋亮  阅读(143)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2022-12-03 使用jdwp 调试dremio
2022-12-03 dremio 联邦数据源arp 扩展简单说明
2021-12-03 haproxy 推荐的性能优化参数
2021-12-03 支持prometheus+lua haproxy 2.5 rpm 包
2021-12-03 edgedb 候选版3发布了
2021-12-03 haproxy ssl 支持
2021-12-03 haproxy 2.5 发布

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示