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中渲染

相关推荐
20YC编程社区16 小时前
一分钟学会绘制Mermaid流程图
流程图·markdown·mermaid流程图
SKY -dada1 天前
Understand 使用教程
开发语言·c#·流程图·软件构建·敏捷流程·代码复审·源代码管理
fox_lht1 天前
onPaint函数流程图
java·eclipse·流程图
外太空的莫扎特3 天前
Draw.io免费的流程图绘画工具
流程图·draw.io
沪漂阿龙5 天前
LangGraph 持久化完全指南:从零搭建永不丢失状态的 AI Agent 系统
人工智能·流程图
weixin_416660075 天前
怎么把 AI Markdown 转为 Word (.docx) 文档?
word·流程图
xiami_world9 天前
产品路线图的技术实现升级:从甘特图到AI Agent驱动的无限画布闭环
人工智能·ai·信息可视化·流程图·产品经理·甘特图
xiami_world10 天前
国内外4大流程图工具深度横评(2026年):从架构、协作、AI能力看选型决策
人工智能·ai·信息可视化·流程图
醉颜凉11 天前
网络协议基础必学:ARP 和 RARP 是什么?有什么区别?原理+流程图+对比详解
网络·网络协议·流程图
GOWIN革文品牌咨询11 天前
图表语法怎么统一:架构图、流程图、数据图如何体现专业感
流程图·b2b品牌策划·b2b品牌设计·b2b全案策划·b2b品牌战略·b2b营销