本文介绍了Langgraph服务的四种调用方式:

1. 通过LangGraph Studio UI界面手动测试;

2. 使用Python SDK进行同步/异步调用;

3. 通过REST API测试;

4. 使用JavaScript SDK接入。

Langgraph 服务端代码 graph.py

from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agentllm = ChatOpenAI(model='qwq-32b',temperature=0.8,api_key='sk-****',streaming=True,base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",# extra_body={'chat_template_kwargs': {'enable_thinking': False}},
)
#
def get_weather(city: str) -> str:"""Get weather for a given city."""return f"在 {city},今天天气不错!"graph = create_react_agent(llm,tools=[get_weather],prompt="你是一个智能助手"
)

通过命令langgraph dev 启动服务,可以看到控制台返回的API地址

1.第一种访问方式:LangGraph Studio

当启动服务后,浏览器中会自动打开 Studio UI的地址,页面如下

可手动输入message,完成调用

2.第二种访问方式:PythonSDK测试

先安装依赖:pip install langgraph-sdk

1)异步测试

langgraph_async_test.py文件内容:

from langgraph_sdk import get_client
import asyncioclient = get_client(url="http://localhost:2024")async def main():async for chunk in client.runs.stream(None,  # Threadless run"agent", # Name of assistant. Defined in langgraph.json.input={"messages": [{"role": "human","content": "上海今天的天气",}],},stream_mode="messages-tuple",):# print(f"Receiving new event of type: {chunk.event}...")# print(chunk.data)if isinstance(chunk.data,list) and 'type' in chunk.data[0] and chunk.data[0]['type'] == 'AIMessageChunk':print(chunk.data[0]['content'], end='', flush=True)asyncio.run(main())

运行结果:

2)同步测试

langgraph_sync_test.py文件内容:

from langgraph_sdk import  get_sync_clientclient = get_sync_client(url="http://localhost:2024")for chunk in client.runs.stream(None,  # Threadless run"agent", # Name of assistant. Defined in langgraph.json.input={"messages": [{"role": "human","content": "上海今天的天气",}],},stream_mode="messages-tuple",):# print(f"Receiving new event of type: {chunk.event}...")# print(chunk.data)if isinstance(chunk.data,list) and 'type' in chunk.data[0] and chunk.data[0]['type'] == 'AIMessageChunk':print(chunk.data[0]['content'], end='', flush=True)

运行结果:

后面2种方式,可自动测试,参考如下

3.第三种访问方式:REST API测试

curl -s --request POST \--url "http://localhost:2024/runs/stream" \--header 'Content-Type: application/json' \--data "{\"assistant_id\": \"agent\",\"input\": {\"messages\": [{\"role\": \"human\",\"content\": \"上海的天气?\"}]},\"stream_mode\": \"messages-tuple\"}"

4.第四种访问方式:JavaScript SDK测试

安装 LangGraph JS SDK:npm install @langchain/langgraph-sdk

向LangGraph服务区发送消息:

const { Client } = await import("@langchain/langgraph-sdk");// only set the apiUrl if you changed the default port when calling langgraph dev
const client = new Client({ apiUrl: "http://localhost:2024"});const streamResponse = client.runs.stream(null, // Threadless run"agent", // Assistant ID{input: {"messages": [{ "role": "user", "content": "上海的天气?"}]},streamMode: "messages-tuple",}
);for await (const chunk of streamResponse) {console.log(`Receiving new event of type: ${chunk.event}...`);console.log(JSON.stringify(chunk.data));console.log("\n\n");
}

graph.py中的get_weather方法可替找成工具

TAVILY_API_KEY='tvly-dev-***'def get_weather(city: str) -> str:"""Get real-time weather for a given city using Tavily search."""from langchain_community.tools import TavilySearchResultsimport re# 创建 Tavily 搜索工具实例search_tool = TavilySearchResults(max_results=1,search_depth="advanced",include_answer=True,api_key=TAVILY_API_KEY)# 构造搜索查询query = f"{city} 当前天气 温度 湿度 风力 风向 天气状况"try:# 执行搜索results = search_tool.invoke({"query": query})# 解析结果if isinstance(results, list) and len(results) > 0:result = results[0]content = result.get('content', '暂无详细信息')# 修复编码问题的函数def fix_encoding(text):if not isinstance(text, str):return text# 尝试多种编码修复方法encodings_to_try = [('latin1', 'utf-8'),('cp1252', 'utf-8'),]for from_enc, to_enc in encodings_to_try:try:# 将字符串以from_enc编码方式重新编码,再以to_enc解码return text.encode(from_enc).decode(to_enc)except (UnicodeEncodeError, UnicodeDecodeError):continue# 如果上面的方法都不行,尝试直接使用raw_unicode_escapetry:return text.encode('raw_unicode_escape').decode('utf-8')except (UnicodeEncodeError, UnicodeDecodeError):pass# 如果所有方法都失败,返回原始内容return text# 修复编码fixed_content = fix_encoding(content)print(f"处理后内容: {fixed_content}")# 从修复后的内容中提取天气信息def extract_weather_info(text):info = {}# 提取天气状况(如晴、多云、阴等)weather_conditions = ['晴', '多云', '阴', '雨', '雪', '雾', '霾', '雷阵雨', '小雨', '中雨', '大雨', '暴雨']for condition in weather_conditions:if condition in text:info['condition'] = conditionbreak# 如果没找到中文天气状况,尝试用正则表达式if 'condition' not in info:condition_match = re.search(r'天气[:\s]*([^\s,,。\.]+)', text)if condition_match:info['condition'] = condition_match.group(1)# 提取温度 (寻找数字+度/℃)temp_match = re.search(r'(\d+\.?\d*)[度℃]', text)if temp_match:info['temperature'] = temp_match.group(1) + "℃"# 提取湿度humidity_match = re.search(r'湿度[:\s]*([0-9]+\.?[0-9]*)[%%]', text)if humidity_match:info['humidity'] = humidity_match.group(1) + "%"# 提取风向wind_dir_match = re.search(r'风向[:\s]*([东南西北风]+)', text)if wind_dir_match:info['wind_direction'] = wind_dir_match.group(1)# 提取风力wind_speed_match = re.search(r'风力[:\s]*([0-9]+\.?[0-9]*[级m/s])', text)if wind_speed_match:info['wind_speed'] = wind_speed_match.group(1)return info# 提取天气信息weather_info = extract_weather_info(fixed_content)# 构建最终输出格式if weather_info:output_parts = [f"{city} 天气"]if 'condition' in weather_info:output_parts.append(f"{weather_info['condition']}")output_parts.append("实时天气情况")if 'temperature' in weather_info:output_parts.append(f"温度{weather_info['temperature']}")if 'humidity' in weather_info:output_parts.append(f"湿度{weather_info['humidity']}")if 'wind_direction' in weather_info:output_parts.append(f"风向{weather_info['wind_direction']}")if 'wind_speed' in weather_info:output_parts.append(f"风力{weather_info['wind_speed']}")return " ".join(output_parts)else:# 如果无法提取结构化信息,则返回修复后的内容return f"{city}天气信息: {fixed_content}"else:return f"无法获取{city}的天气信息"except Exception as e:# 异常处理return f"查询{city}天气时出现错误: {str(e)}"

替换后再次测试,结果如下:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/web/94719.shtml
繁体地址,请注明出处:http://hk.pswp.cn/web/94719.shtml
英文地址,请注明出处:http://en.pswp.cn/web/94719.shtml

如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

HEI-612 HART/EtherNet/IPModbus TCP 网关:打通工业通信壁垒

在工业自动化领域,HART 协议设备的广泛应用与以太网网络的高效管理常面临 “协议孤岛” 难题 —— 老旧 HART 传感器、变送器难以接入 EtherNet/IP 或 Modbus TCP 系统,数据双向交互卡顿、调试复杂、兼容性差等问题,严重制约生产效率提升。上…

OSPF 的工作过程、Router ID 机制、报文结构

视频版讲解>>>>>>>>>>>>>>路由协议深度解析:从静态路由到 OSPF 实战 一、回顾静态路由:拓扑与核心逻辑 我们先回到上周讲解的拓扑图,这张图是理解静态路由的核心载体 —— 路由器作为网段分割的…

Qt 6 与 Qt 5 存在的兼容性差异

之前有提到。我的是Qt5,我朋友的是Qt 6,由于版本不兼容问题,在迁移时会有问题。所以这一我们说说这两个的区别。( 正文开始喽! 总结来说:Qt5迁移至 Qt 6 需:1. 破坏性变更(必须修改…

本地windows电脑部署html网页到互联网:html+node.js+ngrok/natapp

目录 核心概念:为什么不能直接分享HTML文件? 1,html文件修改 2,安装设置node.js 3,路由器虚拟服务器 4,采用ngrok工具进行内网穿透(国外工具) 5,采用natapp工具进行…

electron离线开发核心环境变量npm_config_cache

npm_config_cache 这个环境变量。它在离线环境配置中扮演着核心角色。什么是 npm_config_cache?npm_config_cache 是一个环境变量,用于直接设置 npm 的缓存目录的绝对路径。npm 在安装包时,会遵循一个特定的工作流程:检查缓存&…

CTFshow系列——命令执行web57-60

本篇文章介绍命令执行的另一种情况,CTFshow的Web57-60关的讲解解析;要想了解其它关卡可查看我以往的文章,感谢关注。 文章目录Web57(新方法)Web58(POST型)不可用函数可用函数Web59第二种方法&am…

域名、ip、DSN、URL

目录 1、ip 2、域名 3、DSN 4、URL 1、ip 每个连接到Internet上的主机都会分配一个IP地址,此ip是该计算机在互联网上的逻辑地址的唯一标识,计算机之间的访问就是通过IP地址来进行的。写法:十进制的形式,用“.”分开&#xff0…

【JAVA实现websocket】

JAVA实现websocket背景依赖问题代码实现测试背景 近期项目中需要用到websocket&#xff0c;实现即时通信。 依赖 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></depen…

2.6 提示词调优编码实战(一)

目录 写在前面 一,需求定义 二,简单提示词 2.1 代码示例 2.2 输出结果 三,提示词模版 3.1 提示词 3.1.1 任务描述 3.1.2 用户输入 3.1.3 模型输出格式 3.1.4 Prompt模版 3.2 输出结果 写在前面 前面我们总结了提示词对于模型的意义,接下来我们来通过向模型输入…

使用Stone 3D快速制作第一人称视角在线小游戏

首先得有个怪物模型&#xff0c;怪物带有idle, attack动作 然后有个场景模型&#xff0c;把怪物&#xff08;如果模型较大&#xff0c;建议使用remote-mesh来加载&#xff09;摆放到想放的位置。 给相机加上fps-controls和character组件 给所有怪物加上character组件 可以在…

嵌入式第三十七课!!!TCP机制与HTTP协议

TCP的其他机制TCP头部标志位SYN&#xff1a;请求建立连接标志位 ACK&#xff1a;响应报文标志位 PSH&#xff1a;携带数据标志位&#xff0c;通知接收方该从缓冲区读数据 FIN&#xff1a; 请求断开连接标志位 RST&#xff1a;复位标志位 URG: 紧急数据标志…

【测试】pytest测试环境搭建

使用pytest进行API测试&#xff0c;vscode运行 创建虚拟环境&#xff0c;安装pytest&#xff0c;httpx&#xff0c;requests&#xff0c;dotenvvscode中ctrlshiftp&#xff0c;选择python: Configure Tests&#xff0c;选择pytest&#xff0c;目录左侧插件testing里面可以看到有…

javaweb开发笔记——微头条项目开发

第八章 微头条项目开发 一 项目简介 1.1 微头条业务简介 微头条新闻发布和浏览平台,主要包含业务如下 用户功能 注册功能 登录功能 头条新闻 新闻的分页浏览 通过标题关键字搜索新闻 查看新闻详情 新闻的修改和删除 权限控制 用户只能修改和自己发布的头条新闻 1.…

Linux(二十二)——服务器初始化指南

文章目录前言一、配置国内 Yum 源&#xff08;加速软件安装&#xff09;二、更新系统与安装必备工具三、网络连接验证四、配置主机名五、同步时间六、配置防火墙6.1 使用 iptables6.1.1 整体思路6.1.2 详细步骤6.1.3 完整配置脚本示例6.1.4 常用管理命令6.2 使用 firewalld总结…

我用Photoshop Firefly+Blender,拯救被环境毁掉的人像大片

今日阳光正好。这样的天气对于摄影师来说是种馈赠&#xff0c;但也让我想起了这个行业最普遍也最无奈的痛点&#xff1a;我们精心策划了一场拍摄&#xff0c;模特的表现、光线的质感都近乎完美&#xff0c;但最终却因为一个平淡的阴天、一处杂乱的背景&#xff0c;或是一个无法…

【线性代数】常见矩阵类型

目录 1. 方阵(Square Matrix) 2. 对称矩阵(Symmetric Matrix) 3. 反对称矩阵 / 斜对称矩阵(Skew-Symmetric Matrix) 4. 对角矩阵(Diagonal Matrix) 5. 三角矩阵 6. 正交矩阵(Orthogonal Matrix) 7. 幂等矩阵(Idempotent Matrix) 8. 正定矩阵 / 半正定矩阵 …

达梦数据库统计信息收集

达梦数据库统计信息收集 检查统计信息收集情况 如何手动收集统计信息 查看统计信息收集结果 统计信息手动收集策略 统计信息的自动收集 检查统计信息收集情况 检查最近一次统计信息收集时间: --表的最近一次统计信息收集时间 SQL> select owner,table_name,last_analyzed…

【目标检测】论文阅读4

Fast and accurate object detector for autonomous driving based on improved YOLOv5 发表时间&#xff1a;2023年&#xff1b;期刊&#xff1a;scientific reports 论文地址 摘要 自动驾驶是人工智能的一个重要分支&#xff0c;实时准确的目标检测是保证自动驾驶车辆安全稳…

wpf之DockPanel

前言 DockPanel是一个容器控件&#xff0c;容器中的子控件通过设置DockPanel.Dock属性来调整位置 1、DockPanel.Dock DockPanel.Dock的值有Left、Right、Top、Bottom 1.1 Left 指示控件靠左停靠 1.2 Right 指示控件靠右停靠 1.3 Top 指示控件靠上停靠 1.4 Bottom 指示…

解决VSCode中Cline插件的Git锁文件冲突问题

文章目录 问题现象 错误分析 解决方案 方法一:手动删除锁文件(推荐) 方法二:检查并终止Git进程 方法三:重置检查点目录 方法四:完全重新初始化 预防措施 总结 在使用VSCode进行开发时,许多开发者会选择安装Cline插件来提升工作效率。然而,在使用过程中,可能会遇到一些…