可视化是个非常非常非常有用和友好的东西。本文我们来实现 LangGraph 结构的可视化,当你创建的 LangGraph 结构越来越复杂时,可以利用它来方便地调查和优化逻辑。
安装 grandalf 即可:
ingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif;overflow-x: auto;border-radius: 8px;padding: 1em;margin: 10px 8px;">pipinstall-Ugrandalf-ihttps://pypi.tuna.tsinghua.edu.cn/simpleingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif;font-size: 1.2em;font-weight: bold;display: table;margin: 4em auto 2em;padding-right: 0.2em;padding-left: 0.2em;background: rgb(15, 76, 129);color: rgb(255, 255, 255);">0.3 运行结果ingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif;margin: 1.5em 8px;letter-spacing: 0.1em;color: rgb(63, 63, 63);">可以看到它可视化的图与上篇文章我自己画的图一样:
代码很简单,就两行有效代码:
(1)app = chat_agent_executor.create_function_calling_executor(model, tools),创建一个 Graph。
(2)app.get_graph().print_ascii(),以 ASCII 的形式打印出图形。
create_function_calling_executor这个其实就是将我们上篇文章实现的 LangGraph 创建的过程做了一下封装而已,源码如下:
print_ascii从运行结果来看,它最终实现的效果其实就是将节点和边打印出来,多了一些空格和星号。实现原理并不难,但是想要组织好这个这个显示的效果(空格和星号的数量等),感觉很难。部分源码如下,看看就好,会用就行:
defdraw_ascii(self)->str:returndraw_ascii({node.id:node_data_str(node)fornodeinself.nodes.values()},[(edge.source,edge.target)foredgeinself.edges],)defprint_ascii(self)->None:print(self.draw_ascii())#noqa:T201defdraw_ascii(vertices:Mapping[str,str],edges:Sequence[Tuple[str,str]])->str:"""BuildaDAGanddrawitinASCII.Args:vertices(list):listofgraphvertices.edges(list):listofgraphedges.Returns:str:ASCIIrepresentationExample:>>>fromdvc.dagasciiimportdraw>>>vertices=[1,2,3,4]>>>edges=[(1,2),(2,3),(2,4),(1,4)]>>>print(draw(vertices,edges))+---++---+|3||4|+---+*+---+***********+---+*|2|*+---+*******+---+|1|+---+"""教程中还写了另一种可视化的方式,结果如下:
代码如下:
#app.get_graph().print_ascii()##替换掉这一句fromIPython.displayimportImageImage(app.get_graph().draw_png())
运行前需要先安装如下依赖库:
pipinstall-Uprompt_toolkit-ihttps://pypi.tuna.tsinghua.edu.cn/simplepipinstall-Ugrandalf-ihttps://pypi.tuna.tsinghua.edu.cn/simple
安装过程中你可能会遇到如下问题:ERROR: Could not build wheels for pygraphviz, which is required to install pyproject.toml-based projects
Windows平台的解决方法可参考这篇文章: https://savleen307.medium.com/pygraphviz-installation-in-windows-f45cc6fed981
本文介绍了两种将 LangGraph 可视化的方法,一行代码就可以搞定:
app.get_graph().print_ascii()
或
Image(app.get_graph().draw_png())
其中app是你构建的 LangGraph:
workflow=StateGraph(AgentState)......app=workflow.compile()
•https://github.com/langchain-ai/langgraph/blob/main/examples/visualization.ipynb
| 欢迎光临 链载Ai (https://www.lianzai.com/) | Powered by Discuz! X3.5 |