大语言模型的发展日新月异,记得在去年这个时候,函数调用还是gpt-4的专属。到今年本地运行的大模型无论是推理能力还是文本的输出质量都已经非常接近gpt-4了。而在去年gpt-4尚未发布函数调用时,智能体框架的开发者们依赖构建精巧的提示词实现了gpt-3.5的函数调用。目前在本机运行的大模型,基于这一套逻辑也可以实现函数式调用,今天我们就是用本地运行的大模型来实现这个需求。从测试的效果来看,本地大模型对于简单的函数调用成功率已经非常高了,但是受限于本地机器的性能,调用的时间还是比较长。如果有NVIDIA显卡的CUDA环境,质量应该会好很多,今天就以大家都比较熟悉的LLAMA生态作为起点,基于阿里云开源的千问7B模型的量化版作为基座通过C#和SemanticKernel来实现函数调用的功能。

基本调用逻辑参考这张图:

首先我们需要在本机(windows系统)安装Ollama作为LLM的API后端。访问https://ollama.com/,选择Download。选择你需要的版本即可,windows用户请选择Download for Windows。下载完成后,无脑点击下一步下一步即可安装完毕。

 安装完毕后,打开我们的PowerShell即可运行大模型,第一次加载会下载模型文件到本地磁盘,会比较慢。运行起来后就可以通过控制台和模型进行简单的对话,这里我们以阿里发布的千问2:7b为例。执行以下命令即可运行起来:

ollama run qwen2:7b

 接着我们使用ctrl+D退出对话框,并执行ollama serve,看看服务器是否运行起来了,正常情况下会看到11434这个端口已经运行起来了。接下来我们就可以进入到编码阶段

“https://hcx.twitdw.com/tags-63.html” “https://jmgc.nuochengzx.com/caiwu/7hk58PrOVZ.html” “https://jzxy.yingtailawyer.com/wenda/rL9hClISWh.html” “https://cxgd.yijiandaixiao.com/touzi/xTAJe1AjG1.html” “https://cxzy.oszine.com/yuqi/NuNfWTFfk9.html” “https://cxmb.twitdw.com/xieshang/sNinwDfpud.html” “https://cxzy.oszine.com/gezhai/k1SgNFJisz.html” “https://cxgd.yijiandaixiao.com/touzi/xTogDSBmkx.html” “https://www.qqkjcj.com/nwdjkappxzxbbjrgnzyjd.html” “https://cxgd.yijiandaixiao.com/touzi/rbMhDG9K88.html” “https://jmgc.nuochengzx.com/zhaiwu/AE8dA9UVxV.html” “https://cxmb.twitdw.com/xieshang/U8o90wOZI8.html” “https://www.qqkjcj.com/myqkysqtxgzmwzjdxjykjd.html” “https://cxgd.yijiandaixiao.com/caijing/K5sgn4uTaH.html” “https://cxfx.nuochengzx.com/caijing/ORW2nGRwEj.html” “https://cxfx.nuochengzx.com/zhaiwu/VmQqUn5OEX.html” “https://czk.yingtailawyer.com/tags-34 “https://cxmb.twitdw.com/huankuan/8cHENLdYE6.html” “https://czwj.nuochengzx.com/jinri/E6brWTdTrP.html” “https://hcx.twitdw.com/kuaiwen/dJ4dtb85xs.html” “https://hcx.twitdw.com/zhengxin/k2iQxJfNzt.html” “https://jmgc.nuochengzx.com/huankuan/gbh5O1x2gF.html” “https://cxmb.twitdw.com/huankuan/1gV8xZh3L5.html” “https://cdh.twitdw.com/fangchan/hKmZ6gCZ3f.html” “https://jzxy.yingtailawyer.com/zhuanye/YeIkBoNP4r.html” “https://cxgd.yijiandaixiao.com/zhaiwu/vxkRc9jDXG.html” “https://jzxy.yingtailawyer.com/fuwu/PANfeQSmV8.html” “https://cxmb.twitdw.com/xieshang/SRwevgsDqj.html” “https://jmgc.nuochengzx.com/caiwu/QQuioFF5qU.html” “https://www.qqkjcj.com/xykfqtqhkhylxm2024zx.html” “https://ljkc.yushengbang.com/gzzs/m9d0LYemYH.html” “https://cxgd.yijiandaixiao.com/touzi/J84PJCPTqD.html” “https://cdh.twitdw.com/fangchan/v59eKPKWEs.html” “https://czwj.nuochengzx.com/xingye/PZhqdX9Y5F.html” “https://cxgd.yijiandaixiao.com/touzi/hl96IqciTI.html” “https://cdh.twitdw.com/yuqi/fiG9Hk7SFI.html” “https://cxgd.yijiandaixiao.com/zhaiwu/pnkpi2Av7N.html” “https://czm.oszine.com/redian/FXU2wJZOuwib.html” “https://hcx.twitdw.com/zhengxin/ap0sWh3ay4.html” “https://cxzy.oszine.com/zhaiwu/Vzknv1z9Vc.html” “https://jmgc.nuochengzx.com/pochan/0STX6IBavv.html” “https://cxfx.nuochengzx.com/zhaiquan/AihKoodD8C.html” “https://cdh.twitdw.com/hunyin/a7gKpbiuI9.html” “https://cxgd.yijiandaixiao.com/zhaiwu/fuG7nYvIkh.html” “https://ljkc.yushengbang.com/jrsc/rajqP5dq93.html” “https://jzxy.yingtailawyer.com/wenda/8YlqG1jqTw.html” “https://cxgd.yijiandaixiao.com/zhaiwu/o3HDA5tEBg.html” “https://jqtc.yijiandaixiao.com/caiwu/Stntce3ISX.html” “https://jqtc.yijiandaixiao.com/caiwu/5HYaC3D7TZ.html” “https://czm.oszine.com/xingye/3zJS9JW9X7zh.html” “https://czwj.nuochengzx.com/tags-59.html” “https://czwj.nuochengzx.com/tags-34.html” “https://jmgc.nuochengzx.com/caiwu/iMNsK0r5Kd.html” “https://cxzy.oszine.com/tags-49 “https://czk.yingtailawyer.com/tags-50 “https://czwj.nuochengzx.com/baoxian/MhQd8C0hDx.html” “https://jzxy.yingtailawyer.com/tags-42 “https://hcx.twitdw.com/shangan/u4RDWx3GRn.html” “https://cdh.twitdw.com/geren/9jnJvFKzE4.html” “https://cxmb.twitdw.com/zhaiwu/TzlfJtiMd5.html” “https://cdh.twitdw.com/qita/2mTPgir4zx.html” “https://czk.yingtailawyer.com/daikuan/hayxoGRW9I.html” “https://czwj.nuochengzx.com/baoxian/J2NtRd9fbw.html” “https://ljkc.yushengbang.com/gzzs/lN3MTKrSX4.html” “https://cxmb.twitdw.com/huankuan/nXqplbGw0q.html” “https://cdh.twitdw.com/tags-44 “https://cxzy.oszine.com/tags-144 “https://hcx.twitdw.com/xinyong/Bf28Uc9608.html” “https://hcx.twitdw.com/tags-45.html” “https://ljkc.yushengbang.com/zsjf/KYcGjgtDLo.html” “https://hcx.twitdw.com/tags-29.html” “https://cxfx.nuochengzx.com/zhaiwu/EfO04AY6Yz.html” “https://cxfx.nuochengzx.com/caijing/YhlgShsZrQ.html” “https://hcx.twitdw.com/zhengxin/9co7YxvUSm.html” “https://www.qqkjcj.com/gyzlxykyqjrqwdyjh.html” “https://jzxy.yingtailawyer.com/zhuanye/PjRMswgm60.html” “https://cxgd.yijiandaixiao.com/fuzhai/75hhB6c3XC.html” “https://ljkc.yushengbang.com/jrsc/5VdfbTcN3X.html” “https://www.qqkjcj.com/dgdjyxhqspmfzjrwnqwjd.html” “https://www.qqkjcj.com/wdyqhylsddhmszdmjrfxzyjd.html” “https://czm.oszine.com/xingye/hjVGo6ngtYHU.html” “https://cdh.twitdw.com/hunyin/On9Ml7qyZb.html” “https://cxmb.twitdw.com/shangan/CC8YEOhlAh.html” “https://jzxy.yingtailawyer.com/fuwu/YigJrNeP7c.html” “https://czk.yingtailawyer.com/shenka/wJ8fV5zg2p.html” “https://jmgc.nuochengzx.com/caiwu/mb7Fcvy3gR.html” “https://www.qqkjcj.com/llmxytfzynqzzxmjdxjykjd.html” “https://czwj.nuochengzx.com/zhishi/V8cJwcEivl.html” “https://cxmb.twitdw.com/huankuan/ZFI9UIly7U.html” “https://cxmb.twitdw.com/zhaiwu/fbQJHtQa2M.html” “https://czwj.nuochengzx.com/jinrong/HKHOBJb5ar.html” “https://ljkc.yushengbang.com/zsjf/WRSZFHMtpC.html” “https://cdh.twitdw.com/danbao/4DQ3oPTbwn.html” “https://hcx.twitdw.com/gezhai/fAYE7WVMHL.html” “https://jmgc.nuochengzx.com/caiwu/ATkJFG7v6P.html” “https://cxgd.yijiandaixiao.com/touzi/OMmrgor5JO.html” “https://cdh.twitdw.com/qita/6n3gqqOzC2.html” “https://cxzy.oszine.com/tags-36 “https://cxfx.nuochengzx.com/zhaiquan/pkyf2te9jG.html” “https://cdh.twitdw.com/geren/6kW4apVLtj.html” “https://hcx.twitdw.com/xinyong/B8pRaQXbkA.html” “https://cxfx.nuochengzx.com/zhaiwu/mu44XtxX3q.html” “https://jlxj.yingtailawyer.com/tags-44 “https://czwj.nuochengzx.com/xingye/5Q085V9fRk.html” “https://czwj.nuochengzx.com/tags-39.html” “https://czwj.nuochengzx.com/jinrong/fRewkSrHIs.html” “https://jmgc.nuochengzx.com/xinyong/Pv6kUgicIM.html” “https://cxgd.yijiandaixiao.com/caijing/XiyPxMizTb.html” “https://cxfx.nuochengzx.com/zhaiquan/Czm75iAqxV.html” “https://hcx.twitdw.com/zhengxin/EljzeLFBp2.html” “https://cxzy.oszine.com/tags-72 “https://jmgc.nuochengzx.com/zhaiwu/oqTkNxELEc.html” “https://www.qqkjcj.com/ “https://jmgc.nuochengzx.com/huankuan/tD2RmW6ezf.html” “https://cxgd.yijiandaixiao.com/touzi/LPdD22ftkS.html” “https://jqtc.yijiandaixiao.com/caiwu/ND8uyqb1ZR.html” “https://ljkc.yushengbang.com/cczs/aDSGZxUtOw.html” “https://cxmb.twitdw.com/huankuan/HJqQcqCklk.html” “https://cxmb.twitdw.com/xieshang/af4Q1caKtp.html” “https://ljkc.yushengbang.com/gzzs/KowL5rF6Hc.html” “https://ljkc.yushengbang.com/gzzs/7v2J7GmUOW.html” “https://czm.oszine.com/wenda/5SgPb6Qwydum.html” “https://czm.oszine.com/caidaoxing/4FDdZrT0kAt1.html” “https://cxmb.twitdw.com/huankuan/VLsp1ADAUe.html” “https://cxfx.nuochengzx.com/licai/NF9CP4oaY0.html” “https://hcx.twitdw.com/xinyong/DbWzYVCmhJ.html” “https://cxmb.twitdw.com/xieshang/aeMJn52zfH.html” “https://czwj.nuochengzx.com/caijing/vI6mBE3vs7.html” “https://czm.oszine.com/jinrong/f1K0IjFhQ3p3.html” “https://cxfx.nuochengzx.com/zhaiquan/wckkXtMgY9.html” “https://czk.yingtailawyer.com/tags-6 “https://jmgc.nuochengzx.com/xinyong/8QmcJTxekO.html” “https://cxfx.nuochengzx.com/yuqi/ruYce25cNI.html” “https://www.qqkjcj.com/yjhtsxykjtbwzyjs.html” “https://jqtc.yijiandaixiao.com/caiwu/6qlM0dVO8t.html” “https://cxgd.yijiandaixiao.com/yuqi/3nUAfpD0YZ.html” “https://cxfx.nuochengzx.com/caijing/wy4VmoCiio.html” “https://cxzy.oszine.com/gezhai/ “https://cxgd.yijiandaixiao.com/zhaiwu/LdPzQ6r7J5.html” “https://hcx.twitdw.com/kuaiwen/icZGTsFNg6.html” “https://cdh.twitdw.com/yuqi/pTnlICUICF.html” “https://hcx.twitdw.com/zhengxin/oGEoPTYDTs.html” “https://czk.yingtailawyer.com/daikuan/OK5gbxZRc3.html” “https://czm.oszine.com/xingye/mBcK6C6nXPGr.html” “https://czk.yingtailawyer.com/shenka/GMKyWAvkql.html” “https://cxfx.nuochengzx.com/zhaiquan/kI3rTgVWNn.html” “https://czwj.nuochengzx.com/xingye/2zzfxzs9su.html” “https://czm.oszine.com/redian/llWaluMr0g8f.html” “https://czk.yingtailawyer.com/daikuan/c1wO1SdMEC.html” “https://hcx.twitdw.com/xinyong/fpvECCGSXX.html” “https://cxmb.twitdw.com/xieshang/6s4POJTLEw.html” “https://jmgc.nuochengzx.com/caiwu/OLa6Qxpk7m.html” “https://czwj.nuochengzx.com/caijing/p1nwEcdxtO.html” “https://hcx.twitdw.com/gezhai/GzdDCKXAOB.html” “https://jqtc.yijiandaixiao.com/zhaiwu/TuL8S7TI7Z.html” “https://czwj.nuochengzx.com/xingye/5UwDpKCRZp.html” “https://jqtc.yijiandaixiao.com/zhaiwu/DGtZ1g84lC.html” “https://cxmb.twitdw.com/zhaiwu/i51VGLrvIm.html” “https://www.qqkjcj.com/wsdfwgskxmaqmkxmszdm2024yqhz.html” “https://jmgc.nuochengzx.com/caiwu/YPN6OxImnX.html” “https://www.qqkjcj.com/wdyqlbdyxkdqzdbkl2024jtnews.html” “https://ljkc.yushengbang.com/cczs/jF4v6Nbr7j.html” “https://czm.oszine.com/caizhimen/3ze10tGN1EG4.html” “https://cxmb.twitdw.com/zhaiwu/2EVePByuBm.html” “https://cxgd.yijiandaixiao.com/yuqi/I0x74e9d8A.html” “https://hcx.twitdw.com/zhengxin/4ffSpJ6PPB.html” “https://cxfx.nuochengzx.com/caijing/LwF0QsoFW3.html” “https://www.qqkjcj.com/wdyxkdjdjkyzdjczwjf.html” “https://hcx.twitdw.com/xinyong/sAiJakbWzq.html” “https://czk.yingtailawyer.com/zhaiwu/ZqfW1XvS6s.html” “https://www.qqkjcj.com/fwczfdpmxydcsj2024jtnews.html” “https://jzxy.yingtailawyer.com/wenda/QVwFbgHSGC.html” “https://cxfx.nuochengzx.com/zhaiwu/OI0qGuWECs.html” “https://www.qqkjcj.com/yqdjchbqslh2024zx.html” “https://ljkc.yushengbang.com/cczs/gvVMh3AdzQ.html” “https://czwj.nuochengzx.com/jinrong/IuGg5XwEL9.html” “https://ljkc.yushengbang.com/gzzs/E3PrldD20P.html” “https://cxgd.yijiandaixiao.com/fuzhai/AKc1BBCLdo.html” “https://cxfx.nuochengzx.com/caijing/Zs7bQteqn9.html” “https://cxzy.oszine.com/caixun/0hx30lv7yF.html” “https://cxgd.yijiandaixiao.com/fuzhai/Fc9jkLI51D.html” “https://cdh.twitdw.com/fangchan/CReWuUnJ5W.html” “https://www.qqkjcj.com/yxdkkysqtxgzmjpjdydjd.html” “https://czm.oszine.com/jinxunruiyan “https://cxmb.twitdw.com/xieshang/3ZnawbZymK.html” “https://cxgd.yijiandaixiao.com/zhaiwu/P6I4dGzkjc.html” “https://cxgd.yijiandaixiao.com/zhaiwu/tJIjDkxjjX.html” “https://czk.yingtailawyer.com/tags-23 “https://jqtc.yijiandaixiao.com/zhaiwu/hHjsoIpRfK.html” “https://ljkc.yushengbang.com/cczs/HZLW1mx6n2.html” “https://cdh.twitdw.com/qiye/RMoIKX7nHH.html” “https://cdh.twitdw.com/tags-1 “https://cdh.twitdw.com/tags-117 “https://jmgc.nuochengzx.com/huankuan/uPmyV4xugU.html” “https://cxfx.nuochengzx.com/zhaiwu/MStEP4VkTA.html” “https://jzxy.yingtailawyer.com/caijing/3NT90bsBgC.html” “https://jlxj.yingtailawyer.com/toutiao “https://jxtx.oszine.com/shishi/BR8SZej2h8.html” “https://czwj.nuochengzx.com/zhishi/ffh4wrOgNZ.html” “https://ljkc.yushengbang.com/zsjf/7uAmvf844W.html” “https://jzxy.yingtailawyer.com/zhuanye/tJQq51Dioj.html” “https://cdh.twitdw.com/fangchan/KvB8bwlWpN.html” “https://cxgd.yijiandaixiao.com/fuzhai/V9ciapbVoQ.html” “https://jqtc.yijiandaixiao.com/xinyong/4izmSOhAGM.html” “https://jzxy.yingtailawyer.com/gezhai/68tDWkGNAO.html” “https://cxzy.oszine.com/shenghuo/2c5cJo7XyN.html” “https://ljkc.yushengbang.com/zsjf/p5tM4aGBGo.html” “https://cdh.twitdw.com/tags-24 “https://czk.yingtailawyer.com/shenka/PgmvnNHNaV.html” “https://cdh.twitdw.com/tags-99 “https://cxfx.nuochengzx.com/zhaiwu/vs35jkeoLQ.html” “https://czwj.nuochengzx.com/tags-42.html” “https://ljkc.yushengbang.com/gzzs/ygbJh6W7Kv.html” “https://jzxy.yingtailawyer.com/zhuanye/50kOJ56W9f.html” “https://czm.oszine.com/toutiao/7gaXm5rrjjQ8.html” “https://cxgd.yijiandaixiao.com/zhaiwu/ancXC7aI9c.html” “https://jqtc.yijiandaixiao.com/zhaiwu/1CEEmkV7aW.html” “https://czm.oszine.com/toutiao/ajWYgDfzeBor.html” “https://cxmb.twitdw.com/xieshang/7KojXEnjjk.html” “https://cxgd.yijiandaixiao.com/fuzhai/r7CG3wlJkt.html” “https://cdh.twitdw.com/tags-100 “https://jqtc.yijiandaixiao.com/zhaiwu/9wZMiw8RcJ.html” “https://jqtc.yijiandaixiao.com/zhaiwu/Wa0PIa1dOz.html” “https://hcx.twitdw.com/anli/tjqm8d8SFw.html” “https://cxzy.oszine.com/tags-116 “https://cxfx.nuochengzx.com/licai/Mp2Nf3dEst.html” “https://jqtc.yijiandaixiao.com/xinyong/yKKi16sDED.html” “https://czk.yingtailawyer.com/daikuan/2wioaDT1eB.html” “https://hcx.twitdw.com/shangan/lRBWvH16xj.html” “https://cxmb.twitdw.com/daikuan/tYsRTo1xcw.html” “https://cxzy.oszine.com/yuqi/y3gsqnJT7c.html” “https://czk.yingtailawyer.com/daikuan/6WTUFutSKp.html” “https://czm.oszine.com/zhishi/lMEI9Ry1teFm.html” “https://cxgd.yijiandaixiao.com/yuqi/O5RNVwnIrL.html” “https://jzxy.yingtailawyer.com/caijing/AkPeBttRQl.html” “https://cdh.twitdw.com/tags-55 “https://czwj.nuochengzx.com/shenghuo/umKPTYZDIh.html” “https://jmgc.nuochengzx.com/pochan/6o7swigEhX.html” “https://cxmb.twitdw.com/huankuan/bRlZYLZuGq.html” “https://cxzy.oszine.com/gezhai/EbAc4PXYl5.html” “https://czwj.nuochengzx.com/baoxian/cy1yI7tDKL.html” “https://cxmb.twitdw.com/huankuan/BfdEOzbmGO.html” “https://czk.yingtailawyer.com/daikuan/NGyICHQdho.html” “https://cxmb.twitdw.com/huankuan/UuPGRn3A1R.html” “https://www.qqkjcj.com/yqhyqynfxtgzmbzyzsjrjx.html” “https://cxzy.oszine.com/tags-60 “https://cxgd.yijiandaixiao.com/touzi/wvLBZyQYZ8.html” “https://czwj.nuochengzx.com/tags-26.html” “https://cxfx.nuochengzx.com/caijing/oOcP8iKQ4O.html” “https://cxzy.oszine.com/jinyin/scLIMqsXWB.html” “https://cxzy.oszine.com/zhaiwu/87KqSmUHYc.html” “https://cxmb.twitdw.com/huankuan/mU4YMGOYz6.html” “https://czm.oszine.com/jinrong/ETQdQJLhIZ3p.html” “https://hcx.twitdw.com/zhengxin/72d0WEab8b.html” “https://jqtc.yijiandaixiao.com/caiwu/YM4DwPjqRr.html” “https://jqtc.yijiandaixiao.com/caiwu/JgJE0w8Mox.html” “https://hcx.twitdw.com/lihun/1HqUVMuUnA.html” “https://czm.oszine.com/jincedianjin “https://jqtc.yijiandaixiao.com/zhaiwu/Qw9AxUtByE.html” “https://cxzy.oszine.com/tags-100 “https://ljkc.yushengbang.com/qzzx/2CmXEhPJwF.html” “https://jqtc.yijiandaixiao.com/caiwu/Tuk4y70WtK.html” “https://cxzy.oszine.com/tags-12 “https://jxtx.oszine.com/gezhai/a8anvqhUDO.html” “https://www.qqkjcj.com/wdyqbblyxkmzmbqwjxfnqx.html” “https://ljkc.yushengbang.com/jrsc/Gpo1dHe646.html” “https://cxfx.nuochengzx.com/zhaiquan/tnmz1cQtNZ.html” “https://ljkc.yushengbang.com/zsjf/69V9NeE34E.html” “https://cxmb.twitdw.com/tags-61.html” “https://cxzy.oszine.com/tags-122 “https://cxgd.yijiandaixiao.com/zhaiwu/IPQj6qKyQI.html” “https://cxgd.yijiandaixiao.com/zhaiwu/SewvKZ8Mgf.html” “https://jqtc.yijiandaixiao.com/yuqi/h0sAbkErmV.html” “https://jmgc.nuochengzx.com/tags-22 “https://ljkc.yushengbang.com/gzzs/ETl83rTLbj.html” “https://jqtc.yijiandaixiao.com/zhaiwu/NxqeT1D0ET.html” “https://czwj.nuochengzx.com/jinri/G000fDDLCc.html” “https://ljkc.yushengbang.com/zsjf/loDWMTKNTu.html” “https://jzxy.yingtailawyer.com/gezhai/L2ACwirJTE.html” “https://jqtc.yijiandaixiao.com/yuqi/Y5xbVOntWM.html” “https://cdh.twitdw.com/tags-23 “https://jqtc.yijiandaixiao.com/yuqi/pz3oN37JSJ.html” “https://czwj.nuochengzx.com/zhishi/X6dR1ed22M.html” “https://jmgc.nuochengzx.com/zhaiwu/0hjQsHZqK0.html” “https://cxgd.yijiandaixiao.com/touzi/Q6Kq1sQc7W.html” “https://czk.yingtailawyer.com/baike/mluiPaM6tw.html” “https://czwj.nuochengzx.com/jinri/hexc1ZtNlY.html” “https://www.qqkjcj.com/fxjyqdjhbqxfqtop1jd.html” “https://hcx.twitdw.com/gezhai/HzOmfkw9Mu.html” “https://jzxy.yingtailawyer.com/fuwu/wOgZvKyn3q.html” “https://ljkc.yushengbang.com/jrzs/lDDenlCRab.html” “https://cxzy.oszine.com/gezhai/NemKA5WBsJ.html” “https://jqtc.yijiandaixiao.com/zhaiwu/M5R7S6J71S.html” “https://cdh.twitdw.com/tags-10 “https://jmgc.nuochengzx.com/xinyong/1adfFSmNY3.html” “https://cdh.twitdw.com/fangchan/19EDuA1spL.html” “https://www.qqkjcj.com/qlwdzxbyxkkymjrtkzyjd.html” “https://czm.oszine.com/wenda/Pa2ONDe1w58n.html” “https://czwj.nuochengzx.com/xingye/GzL1SHSkfi.html” “https://czwj.nuochengzx.com/tags-24.html” “https://cdh.twitdw.com/geren/V6UcqyTPcT.html” “https://cxgd.yijiandaixiao.com/fuzhai/MEhXMH56cQ.html” “https://cdh.twitdw.com/danbao/5fxOUDujaX.html” “https://jzxy.yingtailawyer.com/gezhai/fMZQ8JWRE9.html” “https://cxgd.yijiandaixiao.com/zhaiwu/z54lG8tplU.html” “https://cdh.twitdw.com/tags-122 “https://czk.yingtailawyer.com/shenka “https://cxzy.oszine.com/jinyin/sOpuKAYNBb.html” “https://czwj.nuochengzx.com/xingye/958y7Hga0Z.html” “https://czk.yingtailawyer.com/tags-39 “https://jmgc.nuochengzx.com/daikuan/YlRjQL9SnI.html” “https://ljkc.yushengbang.com/cczs/4wDwSH0q8S.html” “https://cxgd.yijiandaixiao.com/fuzhai/1b71ABkWJJ.html” “https://czk.yingtailawyer.com/baike/vdKV0Ybiqr.html” “https://jzxy.yingtailawyer.com/wenda/oZ296CDrz6.html” “https://jqtc.yijiandaixiao.com/zhaiwu/JIdGDOnzsN.html” “https://czwj.nuochengzx.com/shenghuo/rwgHuYW4x1.html” “https://cxzy.oszine.com/caixun/MZGXo92ZUb.html” “https://cxfx.nuochengzx.com/zhaiwu/rLsHiK3PZy.html” “https://czk.yingtailawyer.com/shenka/TgavbPnmaT.html” “https://czm.oszine.com/zhishi/DCt0e3L4w5Ul.html” “https://czm.oszine.com/toutiao/LidS9WrSNuf9.html” “https://czk.yingtailawyer.com/zhaiwu/3Q4Eq8zNEe.html” “https://jzxy.yingtailawyer.com/tags-51

 首先我们创建一个.net8.0的的控制台,接着我们引入三个必要的包

1

2

3

dotnet add package Microsoft.SemanticKernel --version 1.15.0

dotnet add package Newtonsoft.Json --version 13.0.3

dotnet add package OllamaSharp --version 2.0.1

SemanticKernel是我们主要的代理运行框架,OllamaSharp是一个简单的面向Ollama本地API服务的请求封装。避免我们手写httpclient来与本地服务器交互。我这里安装了Newtonsoft.Json来替代system.text.json,主要是用于后期需要一些序列化模型回调来使用,因为模型的回调json可能不是特别标准,使用system.text.json容易导致转义失败。

接下来就是编码阶段,首先我们定义一个函数,这个函数是后面LLM会用到的函数,简单的定义如下:

1

2

3

4

5

6

7

8

public class FunctionTest

{

    [KernelFunction, Description("获取城市的天气状况")]

    public object GetWeather([Description("城市名称")] string CityName, [Description("查询时段,值可以是[白天,夜晚]")] string DayPart)

    {

        return new { CityName, DayPart, CurrentCondition = "多云", LaterCondition = "阴", MinTemperature = 19, MaxTemperature = 23 };

    }

}

这里的KernelFunction和Description特性都是必要的,用于SemanticKernel查询到对应的函数并封装处对应的元数据。

接着我们需要自定义一个继承自接口IChatCompletionService的实现,因为SemanticKernel是基于openai的gpt系列设计的框架,所以要和本地模型调用,我们需要设置独立的ChatCompletionService来让SemanticKernel和本机模型API交互。这里我们主要需要实现的函数是GetChatMessageContentsAsync。因为函数调用我们需要接收到模型完整的回调用于转换json,所以流式传输这里用不上。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

public class CustomChatCompletionService : IChatCompletionService

{

    public IReadOnlyDictionary<stringobject?> Attributes => throw new NotImplementedException();

    public Task<IReadOnlyList<ChatMessageContent>> GetChatMessageContentsAsync(ChatHistory chatHistory, PromptExecutionSettings? executionSettings = null, Kernel? kernel = null, CancellationToken cancellationToken = default)

    {

        throw new NotImplementedException();

    }

    public IAsyncEnumerable<StreamingChatMessageContent> GetStreamingChatMessageContentsAsync(ChatHistory chatHistory, PromptExecutionSettings? executionSettings = null, Kernel? kernel = null, CancellationToken cancellationToken = default)

    {

        throw new NotImplementedException();

    }

}

接下来我们需要定义一个SemanticKernel的实例,这个实例会伴随本次调用贯穿全程。SemanticKernel使用了简单的链式构建。基本代码如下:

1

2

3

4

5

6

var builder = Kernel.CreateBuilder();

//这里我们需要增加刚才我们定义的实例CustomChatCompletionService,有点类似IOC的设计

builder.Services.AddKeyedSingleton<IChatCompletionService>("ollamaChat"new CustomChatCompletionService());

//这里我们需要插入之前定义的插件

builder.Plugins.AddFromType<FunctionTest>();

var kernel = builder.Build();

可以看到基本的构建链式调用代码部分还是比较简单的,接下来就是调用的部分,这里主要的部分就是将LLM可用的函数插入到系统提示词,来引导LLM去调用特定函数:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

//定义一个对话历史

ChatHistory history = [];

//获取刚才定义的插件函数的元数据,用于后续创建prompt

var plugins = kernel.Plugins.GetFunctionsMetadata();

//生成函数调用提示词,引导模型根据用户请求去调用函数

var functionsPrompt = CreateFunctionsMetaObject(plugins);

//创建系统提示词,插入刚才生成的提示词

var prompt = $"""

                  You have access to the following functions. Use them if required:

                  {functionsPrompt}

                  If function calls are used, ensure the output is in JSON format; otherwise, output should be in text format.

                  """;

//添加系统提示词

history.AddSystemMessage(prompt);

//创建一个对话服务实例

var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();

//添加用户的提问

history.AddUserMessage(question);

//链式执行kernel

var result = await chatCompletionService.GetChatMessageContentAsync(

    history,

    executionSettings: null,

    kernel: kernel);

//打印回调内容

Console.WriteLine($"Assistant> {result}");

在这里我们可以debug看看生成的系统提示词细节:

 当代码执行到GetChatMessageContentAsync这里时,就会跳转到我们的CustomChatCompletionService的GetChatMessageContentsAsync函数,在这里我们需要进行ollama的调用来达成目的。

这里比较核心的部分就是将LLM回调的内容使用JSON序列化来检测是否涉及到函数调用,简单来讲由于类似qwen这样没有专门针对function calling专项微调过的(glm-4-9b原生支持function calling)模型,其function calling并不是每次都能准确的回调,所以这里我们需要对回调的内容进行反序列化和信息抽取,确保模型的调用符合回调函数的格式标准。具体代码如下

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

public async Task<IReadOnlyList<ChatMessageContent>> GetChatMessageContentsAsync(ChatHistory chatHistory, PromptExecutionSettings? executionSettings = null, Kernel? kernel = null, CancellationToken cancellationToken = default)

{

    GetDicSearchResult(kernel);

    var prompt = HistoryToText(chatHistory);

    var ollama = new OllamaApiClient("http://127.0.0.1:11434""qwen2:7b");

    var chat = new Chat(ollama, _ => { });

    sw.Start();

    var history = (await chat.Send(prompt, CancellationToken.None)).ToArray();

    sw.Stop();

    Console.WriteLine($"调用耗时:{Math.Round(sw.Elapsed.TotalSeconds,2)}秒");

    var last = history.Last();

    var chatResponse = last.Content;

    try

    {

        JToken jToken = JToken.Parse(chatResponse);

        jToken = ConvertStringToJson(jToken);

        var searchs = DicSearchResult.Values.ToList();

        if (TryFindValues(jToken, ref searchs))

        {

            var firstFunc = searchs.First();

            var funcCallResult = await firstFunc.KernelFunction.InvokeAsync(kernel, firstFunc.FunctionParams);

            chatHistory.AddMessage(AuthorRole.Assistant, chatResponse);

            chatHistory.AddMessage(AuthorRole.Tool, funcCallResult.ToString());

            return await GetChatMessageContentsAsync(chatHistory, kernel: kernel);

        }

        else

        {

        }

    }

    catch(Exception e)

    {

    }

    return new List<ChatMessageContent> { new ChatMessageContent(AuthorRole.Assistant, chatResponse) };

}

这里我们首先使用SemanticKernel的kernel的函数元数据通过GetDicSearchResult构建了一个字典,这部分代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

public static Dictionary<string, SearchResult> DicSearchResult = new Dictionary<string, SearchResult>();

public static void GetDicSearchResult(Kernel kernel)

{

    DicSearchResult = new Dictionary<string, SearchResult>();

    foreach (var functionMetaData in kernel.Plugins.GetFunctionsMetadata())

    {

        string functionName = functionMetaData.Name;

        if (DicSearchResult.ContainsKey(functionName))

            continue;

        var searchResult = new SearchResult

        {

            FunctionName = functionName,

            KernelFunction = kernel.Plugins.GetFunction(null, functionName)

        };

        functionMetaData.Parameters.ToList().ForEach(x => searchResult.FunctionParams.Add(x.Name, null));

        DicSearchResult.Add(functionName, searchResult);

    }

}

接着使用HistoryToText将历史对话信息组装成一个单一的prompt发送给模型,大概会组装成如下内容,其实就是系统提示词+用户提示词组合成一个单一文本:

 接着我们使用OllamaSharp的SDK提供的OllamaApiClient发送信息给模型,等待模型回调后,从模型回调的内容中抽取chatResponse,接着我们需要通过一个try catch来处理,当chatResponse可以被正确的解析成标准JToken后,说明模型的回调是一段json,否则会抛出异常,代表模型输出的是一段文本。如果是文本,我们就直接返回模型输出的内容,如果是json则继续向下处理,通过一个TryFindValues函数从模型中抽取我们所需要的回调函数名、参数,并赋值到一个临时变量中。最后通过SemanticKernel的KernelFunction的InvokeAsync进行真正的函数调用,获取到函数的回调内容,接着我们需要将模型的原始输出和回调内容一同添加到chatHistory后,再度递归发起GetChatMessageContentsAsync调用,这一次模型就会拿到前一次回调的城市天气内容来进行回答了。

 第二次回调前的prompt如下,可以看到模型的输出虽然是json,但是并没有规范的格式,不过使用我们的抽取函数还是获取到了需要的信息,从而正确的构建了底部的回调:

 通过这一轮回调再次喂给llm,llm就可以正确的输出结果了:

 以上就是整个文章的内容了,可以看到在这个过程中我们主要做的工作就是通过系统提示词诱导模型输出回调函数json,解析json获取参数,调用本地的函数后再次回调给模型,这个过程其实有点类似的RAG,只不过RAG是通过用户的提示词直接进行近似度搜索获取到近似度相关的文本组合到系统提示词,而函数调用给了模型更大的自由度,可以让模型自行决策是否调用函数,从而使本地Agent代理可以实现诸如帮你操控电脑,打印文件,编写邮件等等助手性质的功能。

下面是核心部分的代码,请大家自取

program.cs:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

using ConsoleApp4;

using Microsoft.SemanticKernel.ChatCompletion;

using Microsoft.SemanticKernel;

using Microsoft.Extensions.DependencyInjection;

using System.ComponentModel;

using Newtonsoft.Json.Linq;

await Ollama("我想知道西安今天晚上的天气情况");

async Task Ollama(string question)

{

    Console.WriteLine($"User> {question}");

    var builder = Kernel.CreateBuilder();

    //这里我们需要增加刚才我们定义的实例CustomChatCompletionService,有点类似IOC的设计

    builder.Services.AddKeyedSingleton<IChatCompletionService>("ollamaChat"new CustomChatCompletionService());

    //这里我们需要插入之前定义的插件

    builder.Plugins.AddFromType<FunctionTest>();

    var kernel = builder.Build();

    //定义一个对话历史

    ChatHistory history = [];

    //获取刚才定义的插件函数的元数据,用于后续创建prompt

    var plugins = kernel.Plugins.GetFunctionsMetadata();

    //生成函数调用提示词,引导模型根据用户请求去调用函数

    var functionsPrompt = CreateFunctionsMetaObject(plugins);

    //创建系统提示词,插入刚才生成的提示词

    var prompt = $"""

                      You have access to the following functions. Use them if required:

                      {functionsPrompt}

                      If function calls are used, ensure the output is in JSON format; otherwise, output should be in text format.

                      """;

    //添加系统提示词

    history.AddSystemMessage(prompt);

    //创建一个对话服务实例

    var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();

    //添加用户的提问

    history.AddUserMessage(question);

    //链式执行kernel

    var result = await chatCompletionService.GetChatMessageContentAsync(

        history,

        executionSettings: null,

        kernel: kernel);

    //打印回调内容

    Console.WriteLine($"Assistant> {result}");

}

static JToken? CreateFunctionsMetaObject(IList<KernelFunctionMetadata> plugins)

{

    if (plugins.Count < 1) return null;

    if (plugins.Count == 1) return CreateFunctionMetaObject(plugins[0]);

    JArray promptFunctions = [];

    foreach (var plugin in plugins)

    {

        var pluginFunctionWrapper = CreateFunctionMetaObject(plugin);

        promptFunctions.Add(pluginFunctionWrapper);

    }

    return promptFunctions;

}

static JObject CreateFunctionMetaObject(KernelFunctionMetadata plugin)

{

    var pluginFunctionWrapper = new JObject()

        {

            "type""function" },

        };

    var pluginFunction = new JObject()

        {

            "name", plugin.Name },

            "description", plugin.Description },

        };

    var pluginFunctionParameters = new JObject()

        {

            "type""object" },

        };

    var pluginProperties = new JObject();

    foreach (var parameter in plugin.Parameters)

    {

        var property = new JObject()

            {

                "type", parameter.ParameterType?.ToString() },

                "description", parameter.Description },

            };

        pluginProperties.Add(parameter.Name, property);

    }

    pluginFunctionParameters.Add("properties", pluginProperties);

    pluginFunction.Add("parameters", pluginFunctionParameters);

    pluginFunctionWrapper.Add("function", pluginFunction);

    return pluginFunctionWrapper;

}

public class FunctionTest

{

    [KernelFunction, Description("获取城市的天气状况")]

    public object GetWeather([Description("城市名称")] string CityName, [Description("查询时段,值可以是[白天,夜晚]")] string DayPart)

    {

        return new { CityName, DayPart, CurrentCondition = "多云", LaterCondition = "阴", MinTemperature = 19, MaxTemperature = 23 };

    }

}

CustomChatCompletionService.cs:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

using Microsoft.SemanticKernel;

using Microsoft.SemanticKernel.ChatCompletion;

using Newtonsoft.Json.Linq;

using OllamaSharp;

using System.Diagnostics;

using System.Text;

namespace ConsoleApp4

{

    public class CustomChatCompletionService : IChatCompletionService

    {

        public static Dictionary<string, SearchResult> DicSearchResult = new Dictionary<string, SearchResult>();

        public static void GetDicSearchResult(Kernel kernel)

        {

            DicSearchResult = new Dictionary<string, SearchResult>();

            foreach (var functionMetaData in kernel.Plugins.GetFunctionsMetadata())

            {

                string functionName = functionMetaData.Name;

                if (DicSearchResult.ContainsKey(functionName))

                    continue;

                var searchResult = new SearchResult

                {

                    FunctionName = functionName,

                    KernelFunction = kernel.Plugins.GetFunction(null, functionName)

                };

                functionMetaData.Parameters.ToList().ForEach(x => searchResult.FunctionParams.Add(x.Name, null));

                DicSearchResult.Add(functionName, searchResult);

            }

        }

        public IReadOnlyDictionary<stringobject?> Attributes => throw new NotImplementedException();

        static Stopwatch sw = new Stopwatch();

        public async Task<IReadOnlyList<ChatMessageContent>> GetChatMessageContentsAsync(ChatHistory chatHistory, PromptExecutionSettings? executionSettings = null, Kernel? kernel = null, CancellationToken cancellationToken = default)

        {

            GetDicSearchResult(kernel);

            var prompt = HistoryToText(chatHistory);

            var ollama = new OllamaApiClient("http://127.0.0.1:11434""qwen2:7b");

            var chat = new Chat(ollama, _ => { });

            sw.Start();

            var history = (await chat.Send(prompt, CancellationToken.None)).ToArray();

            sw.Stop();

            Console.WriteLine($"调用耗时:{Math.Round(sw.Elapsed.TotalSeconds,2)}秒");

            var last = history.Last();

            var chatResponse = last.Content;

            try

            {

                JToken jToken = JToken.Parse(chatResponse);

                jToken = ConvertStringToJson(jToken);

                var searchs = DicSearchResult.Values.ToList();

                if (TryFindValues(jToken, ref searchs))

                {

                    var firstFunc = searchs.First();

                    var funcCallResult = await firstFunc.KernelFunction.InvokeAsync(kernel, firstFunc.FunctionParams);

                    chatHistory.AddMessage(AuthorRole.Assistant, chatResponse);

                    chatHistory.AddMessage(AuthorRole.Tool, funcCallResult.ToString());

                    return await GetChatMessageContentsAsync(chatHistory, kernel: kernel);

                }

                else

                {

                }

            }

            catch(Exception e)

            {

            }

            return new List<ChatMessageContent> { new ChatMessageContent(AuthorRole.Assistant, chatResponse) };

        }

        JToken ConvertStringToJson(JToken token)

        {

            if (token.Type == JTokenType.Object)

            {

                // 遍历对象的每个属性

                JObject obj = new JObject();

                foreach (JProperty prop in token.Children<JProperty>())

                {

                    obj.Add(prop.Name, ConvertStringToJson(prop.Value));

                }

                return obj;

            }

            else if (token.Type == JTokenType.Array)

            {

                // 遍历数组的每个元素

                JArray array = new JArray();

                foreach (JToken item in token.Children())

                {

                    array.Add(ConvertStringToJson(item));

                }

                return array;

            }

            else if (token.Type == JTokenType.String)

            {

                // 尝试将字符串解析为 JSON

                string value = token.ToString();

                try

                {

                    return JToken.Parse(value);

                }

                catch (Exception)

                {

                    // 解析失败时返回原始字符串

                    return token;

                }

            }

            else

            {

                // 其他类型直接返回

                return token;

            }

        }

        bool TryFindValues(JToken token, ref List<SearchResult> searches)

        {

            if (token.Type == JTokenType.Object)

            {

                foreach (var child in token.Children<JProperty>())

                {

                    foreach (var search in searches)

                    {

                        if (child.Value.ToString().ToLower().Equals(search.FunctionName.ToLower()) && search.SearchFunctionNameSucc != true)

                            search.SearchFunctionNameSucc = true;

                        foreach (var par in search.FunctionParams)

                        {

                            if (child.Name.ToLower().Equals(par.Key.ToLower()) && par.Value == null)

                                search.FunctionParams[par.Key] = child.Value.ToString().ToLower();

                        }

                    }

                    if (searches.Any(x => x.SearchFunctionNameSucc == false || x.FunctionParams.Any(x => x.Value == null)))

                        TryFindValues(child.Value, ref searches);

                }

            }

            else if (token.Type == JTokenType.Array)

            {

                foreach (var item in token.Children())

                {

                    if (searches.Any(x => x.SearchFunctionNameSucc == false || x.FunctionParams.Any(x => x.Value == null)))

                        TryFindValues(item, ref searches);

                }

            }

            return searches.Any(x => x.SearchFunctionNameSucc && x.FunctionParams.All(x => x.Value != null));

        }

        public virtual string HistoryToText(ChatHistory history)

        {

            StringBuilder sb = new();

            foreach (var message in history)

            {

                if (message.Role == AuthorRole.User)

                {

                    sb.AppendLine($"User: {message.Content}");

                }

                else if (message.Role == AuthorRole.System)

                {

                    sb.AppendLine($"System: {message.Content}");

                }

                else if (message.Role == AuthorRole.Assistant)

                {

                    sb.AppendLine($"Assistant: {message.Content}");

                }

                else if (message.Role == AuthorRole.Tool)

                {

                    sb.AppendLine($"Tool: {message.Content}");

                }

            }

            return sb.ToString();

        }

        public IAsyncEnumerable<StreamingChatMessageContent> GetStreamingChatMessageContentsAsync(ChatHistory chatHistory, PromptExecutionSettings? executionSettings = null, Kernel? kernel = null, CancellationToken cancellationToken = default)

        {

            throw new NotImplementedException();

        }

    }

    public class SearchResult

    {

        public string FunctionName { getset; }

        public bool SearchFunctionNameSucc { getset; }

        public KernelArguments FunctionParams { getset; } = new KernelArguments();

        public KernelFunction KernelFunction { getset; }

    }

}

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐