微信扫码
添加专属顾问
我要投稿
可视化是个非常非常非常有用和友好的东西。本文我们来实现 LangGraph 结构的可视化,当你创建的 LangGraph 结构越来越复杂时,可以利用它来方便地调查和优化逻辑。
一行代码即可搞定,非常简单。
先上完整代码,跑通再说
from langchain_openai import ChatOpenAIfrom langchain_community.tools.tavily_search import TavilySearchResultsfrom langgraph.prebuilt import chat_agent_executorfrom langchain_core.messages import HumanMessagetools = [TavilySearchResults(max_results=1)]model = ChatOpenAI()app = chat_agent_executor.create_function_calling_executor(model, tools)app.get_graph().print_ascii()
运行时遇到问题:
安装 grandalf 即可:
pip install -U grandalf -i https://pypi.tuna.tsinghua.edu.cn/simple
可以看到它可视化的图与上篇文章我自己画的图一样:
代码很简单,就两行有效代码:
(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
从运行结果来看,它最终实现的效果其实就是将节点和边打印出来,多了一些空格和星号。实现原理并不难,但是想要组织好这个这个显示的效果(空格和星号的数量等),感觉很难。部分源码如下,看看就好,会用就行:
def draw_ascii(self) -> str: return draw_ascii( {node.id: node_data_str(node) for node in self.nodes.values()}, [(edge.source, edge.target) for edge in self.edges], )def print_ascii(self) -> None: print(self.draw_ascii()) # noqa: T201def draw_ascii(vertices: Mapping[str, str], edges: Sequence[Tuple[str, str]]) -> str: """Build a DAG and draw it in ASCII. Args: vertices (list): list of graph vertices. edges (list): list of graph edges. Returns: str: ASCII representation Example: >>> from dvc.dagascii import draw >>> 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() ## 替换掉这一句from IPython.display import ImageImage(app.get_graph().draw_png())
运行前需要先安装如下依赖库:
pip install -U prompt_toolkit -i https://pypi.tuna.tsinghua.edu.cn/simplepip install -U grandalf -i https://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
53AI,企业落地大模型首选服务商
产品:场景落地咨询+大模型应用平台+行业解决方案
承诺:免费场景POC验证,效果验证后签署服务协议。零风险落地应用大模型,已交付160+中大型企业
2025-02-01
2024-07-25
2025-01-01
2025-02-04
2024-08-13
2024-04-25
2024-06-13
2024-08-21
2024-09-23
2024-04-26
2025-04-30
2025-04-30
2025-04-29
2025-04-29
2025-04-29
2025-04-29
2025-04-29
2025-04-29