ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

读书笔记(ai agents in action)-赋能智能体行动力(第5章)聊天查询省份城市天气

读书笔记(ai agents in action)-赋能智能体行动力(第5章)聊天查询省份城市天气 前面的示例解释了sk中函数/插件的注册和手工调用但实际项目中它们是注册后是由agent在根据任务需要自动选择和调用的。下面的示例是一个聊天查询天气需要提供省份城市信息就可以查询最近一周的天气。import urllib.request as urlreq from bs4 import BeautifulSoup from urllib.error import HTTPError from typing import Annotated class WeatherPlugin: week weather plugin. kernel_function(description获取最近一周天气信息,在使用前需要把省份按单个汉字的拼音取第一个字母大写只取2个前汉字的城市转换为全小写拼音.) def week_weather(self, province:Annotated[str, 接受2个大写字母作为省份.],city:str) - str: Returns the date weather. base_url http://www.nmc.cn/ endpoint f{base_url}/publish/forecast/A{province}/{city}.html req urlreq.Request(endpoint) result [] try: response urlreq.urlopen(req).read().decode(utf-8) soup BeautifulSoup(response, html.parser) weather_wraps soup.find_all(div, class_weatherWrap) for item in weather_wraps: tags item.find_all(div) if len(tags) 11: date tags[0].get_text(stripTrue) desc tags[2].get_text(stripTrue) windd tags[3].get_text(stripTrue) winds tags[4].get_text(stripTrue) tmp tags[5].get_text(stripTrue) tmp_l tags[6].get_text(stripTrue) desc_l tags[8].get_text(stripTrue) windd_l tags[9].get_text(stripTrue) winds_l tags[10].get_text(stripTrue) result.append(f{date}高{desc} {windd} {winds} {tmp}低{desc_l} {windd_l} {winds_l} {tmp_l}) except HTTPError as e: return(e) if len(result) 0: return 该城市代码特别不能正确查询。 return \n.join(result)基于前面文章的示例继承下来这里只是更新了WeatherPlugin类用一个具体的实例真实查询天气。在测试中拼音转换有时不准确另有些城市的拼音不完全是字面拼音等会查询失败。这段代码只是一般python类需要注意的是1参数推荐标注类型sk推荐是用Annotated标注例如Annotated[str, 接受2个大写字母作为省份.]2函数的参数使用默认值时sk自动调用时仍需要赋值如果它分析不到相应的参数值调用会失败。async def main(): kernel get_kernel() kernel.add_plugin(WeatherPlugin(), plugin_nameweather) kernel.add_plugin(HisgoodsPlugin(), plugin_nameHisgoodsPlugin) kernel.add_function(prompt_template_configprompt_template_config, function_namegetgoods, plugin_nameBuygoodsPlugin,) settings kernel.get_prompt_execution_settings_from_service_id(service_idservice_id) settings.function_choice_behavior FunctionChoiceBehavior.Auto() agent ChatCompletionAgent( kernelkernel, nameRecommend, instructions回答购物相关提问., argumentsKernelArguments(settingssettings), ) thread: ChatHistoryAgentThread None chatting True print( 欢迎使用!\ \n 输入 exit 将退出.\ \n 可以试试查询省市的天气. ) while chatting: try: user_input input(User: ) if user_input exit: print(\n\nExiting chat...) chatting False else: async for response in agent.invoke(messagesuser_input, threadthread): print(f# Agent: {response}) thread response.thread except KeyboardInterrupt: print(\n\nExiting chat...) chatting False except EOFError: print(\n\nExiting chat...) chatting False #finally # await thread.delete() if thread else None if __name__ __main__: asyncio.run(main())这里构建了一个简陋的聊天agent。这里注意注册函数/插件时我们没有留取函数/插件的引用。因我们不需要了函数的执行是有agent自主决定和执行。另settings.function_choice_behavior FunctionChoiceBehavior.Auto() 把这个自主权明确设置。最后agent ChatCompletionAgent(...定义的是agent实例后面调用使用的是agent.invoke()而不同于kernel.invoke。到这sk的基本用法就梳理完了也就是本章的核心内容全部了。有兴趣继续sk学习可已进入源码阅读。
返回列表