pydantic AI Graph 打印流程图

wiki

https://ai.pydantic.dev/graph/#stateful-graphs

code

python 复制代码
from __future__ import annotations

import asyncio
from dataclasses import dataclass

from rich.prompt import Prompt

from pydantic_graph import BaseNode, End, Graph, GraphRunContext

# 状态
@dataclass
class MachineState:
    user_balance: float = 0.0       # 用户投币总额
    product: str | None = None      # 选择的商品


@dataclass
class InsertCoin(BaseNode[MachineState]):
    async def run(self, ctx: GraphRunContext[MachineState]) -> CoinsInserted:
        return CoinsInserted(float(Prompt.ask('Insert coins')))


@dataclass
class CoinsInserted(BaseNode[MachineState]):
    amount: float

    async def run(
        self, ctx: GraphRunContext[MachineState]
    ) -> SelectProduct | Purchase:
        ctx.state.user_balance += self.amount
        if ctx.state.product is not None:
            # 商品还有则继续购买
            return Purchase(ctx.state.product)
        else:
            # 选择的商品为空则重新选择商品
            return SelectProduct()


@dataclass
class SelectProduct(BaseNode[MachineState]):
    async def run(self, ctx: GraphRunContext[MachineState]) -> Purchase:
        # 获取用户想买的商品
        return Purchase(Prompt.ask('Select product'))

# 商品价格表
PRODUCT_PRICES = {
    'water': 1.25,
    'soda': 1.50,
    'crisps': 1.75,
    'chocolate': 2.00,
}


@dataclass
class Purchase(BaseNode[MachineState, None, None]):
    product: str

    async def run(
        self, ctx: GraphRunContext[MachineState]
    ) -> End | InsertCoin | SelectProduct:
        if price := PRODUCT_PRICES.get(self.product):
            ctx.state.product = self.product
            if ctx.state.user_balance >= price:
                # 金额足够
                ctx.state.user_balance -= price
                return End(None)
            else:
                # 金额不足
                diff = price - ctx.state.user_balance
                print(f'Not enough money for {self.product}, need {diff:0.2f} more')
                #> Not enough money for crisps, need 0.75 more
                return InsertCoin()
        else:
            # 商品表找不到该商品
            print(f'No such product: {self.product}, try again')
            return SelectProduct()


vending_machine_graph = Graph(
    nodes=[InsertCoin, CoinsInserted, SelectProduct, Purchase]
)


async def main():
    state = MachineState()
    await vending_machine_graph.run(InsertCoin(), state=state)
    print(f'purchase successful item={state.product} change={state.user_balance:0.2f}')
    #> purchase successful item=crisps change=0.25



print(vending_machine_graph.mermaid_code(start_node=InsertCoin))

输出

mermaid语法.

python 复制代码
---
title: vending_machine_graph
---
stateDiagram-v2
  [*] --> InsertCoin
  InsertCoin --> CoinsInserted
  CoinsInserted --> SelectProduct
  CoinsInserted --> Purchase
  SelectProduct --> Purchase
  Purchase --> InsertCoin
  Purchase --> SelectProduct
  Purchase --> [*]

拷贝到在线网址渲染

https://mermaid.live/edit#pako:eNptkDFvwyAQhf-KdWNlWwQcjBm6pEu3SN1ad0DmYluNIcJQtbXy32tcpZGVbO-97x0HTNBYjSBh9MrjU69ap4bsk9YmSd4e3pMse0yezYjO72xvYnp1C4xi_MtQR74KlsoLHrHxe2d1aPz9yj64plMjRrqq39CLvnOzFbpZuqLz0yCF1vUapHcBUxjQDSpamGK7Bt_hgDXIWWrlPmqozXmeOSnzau1wGXM2tB3IgzqOswsnff3F_9Sh0eh2NhgPkhXLGSAn-AJJS5ZzxqqKbThndFum8A1SiJwUgnIhCN1yIopzCj_LUpKXrCBcVIxsioqUM_oFvzaPyg

mermaid pycharm markdown中渲染

相关推荐
CNRio1 天前
Day 13:Git文件状态:工作区、暂存区、仓库的状态转换状态转换图+命令对照表(附状态机流程图)
git·流程图
secondyoung1 天前
TLE9180短路检测功能总结
经验分享·嵌入式硬件·mcu·汽车·流程图·infineon·tle9180
AC赳赳老秦3 天前
DeepSeek 赋能医疗信息化:基于电子病历的结构化诊疗建议模板生成
mongodb·信息可视化·流程图·ambari·数据库开发·数据库架构·deepseek
Heigl swift3 天前
[react工程]算法流程图编辑器
react.js·编辑器·流程图
AC赳赳老秦4 天前
汽车制造:DeepSeek辅助设备故障预测与停机时间降低方案
信息可视化·汽车·流程图·甘特图·memcached·智能电视·deepseek
川西胖墩墩5 天前
中文PC端跨职能流程图模板免费下载
大数据·论文阅读·人工智能·架构·流程图
dajun1811234565 天前
简单快速跨职能流程图在线设计工具 中文
人工智能·架构·流程图
程途拾光1585 天前
企业部门协作泳道图制作工具 PC端
大数据·运维·流程图
dajun1811234565 天前
PC端中文免费在线跨职能泳道图制作工具
运维·架构·流程图·敏捷流程·交通物流
数说星榆1815 天前
项目管理跨职能泳道图在线生成方法
论文阅读·流程图·论文笔记