Semantic Kernel:OpenAPI的Plugin

news/2025/3/4 3:32:30/文章来源:https://www.cnblogs.com/axzxs2001/p/18746201

  SK的插件,能让AI功能如虎添翼。Plugin能让AI与本地功能和数据互动,使AI与应用的结合,并起到了很好的粘合剂作用。

  怎么能让Plugin本身和功能分离呢?调用API是一个很好的办法,比如下面是一个查询订单的功能,是一个mini API项目。

using System.Text.Json.Serialization;var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi();
var app = builder.Build();
app.MapOpenApi();
app.MapGet("/orders", () =>
{app.Logger.LogInformation("查询orders");var orders = Enumerable.Range(1, 5).Select(index =>new Order(Guid.NewGuid().ToString(),$"Product {index}",index,index * 10)).ToArray();return orders;
})
.WithName("orders").WithDescription("获取订单列表");
app.Run();class Order
{public Order(string id, string product, int quantity, decimal price){Id = id;Product = product;Quantity = quantity;Price = price;}[JsonPropertyName("编号")]public string Id { get; set; }[JsonPropertyName("产品名称")]public string Product { get; set; }[JsonPropertyName("订单数量")]public int Quantity { get; set; }[JsonPropertyName("订单金额")]public decimal Price { get; set; }
}

这个API的OpenAPI的框架是这样的:http://localhost:5000/openapi/v1.json

{"openapi": "3.0.1","info": {"title": "OpenAPIDemoForAI | v1","version": "1.0.0"},"servers": [{"url": "http://localhost:5000"}],"paths": {"/orders": {"get": {"tags": ["OpenAPIDemoForAI"],"description": "获取订单列表","operationId": "orders","responses": {"200": {"description": "OK","content": {"application/json": {"schema": {"type": "array","items": {"$ref": "#/components/schemas/Order"}}}}}}}}},"components": {"schemas": {"Order": {"required": ["编号","产品名称","订单数量","订单金额"],"type": "object","properties": {"编号": {"type": "string"},"产品名称": {"type": "string"},"订单数量": {"type": "integer","format": "int32"},"订单金额": {"type": "number","format": "double"}}}}},"tags": [{"name": "OpenAPIDemoForAI"}]
}

现在调用一下接口,查询一下订单:http://localhost:5000/orders

[{"编号": "c82bd2f1-25d1-4a17-bb40-7cfe9fd35f71","产品名称": "Product 1","订单数量": 1,"订单金额": 10},{"编号": "bc6f1eef-4ea9-426c-a446-1cff12d963ac","产品名称": "Product 2","订单数量": 2,"订单金额": 20},{"编号": "b7b27a33-db1f-4c7c-99c6-064d330d8893","产品名称": "Product 3","订单数量": 3,"订单金额": 30},{"编号": "c58f6e36-4363-441d-b54f-50c99970d07a","产品名称": "Product 4","订单数量": 4,"订单金额": 40},{"编号": "2789ac41-0d90-4da8-8041-b2e3cd3f7859","产品名称": "Product 5","订单数量": 5,"订单金额": 50}
]

  SK本身是支持把符合OpenAPI(这里不是OpenAI)规范的API导入成为SK的插件的,主要借助OpenApiKernelPluginFactory来完成,具体实现如下:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using Microsoft.SemanticKernel.Plugins.OpenApi;
using System.IO;
using System.Text.Json;
#pragma warning disable 
var apikey = File.ReadAllText("c:/gpt/key.txt");
using HttpClient httpClient = new();var kernelBuilder = Kernel.CreateBuilder();
kernelBuilder.AddOpenAIChatCompletion("gpt-4o", apiKey: apikey);
var kernel = kernelBuilder.Build();var pluginArr = new List<PluginSetting>
{new PluginSetting{PluginName="OrderService",UriString="http://localhost:5000/openapi/v1.json"}
};
foreach (var pluginItem in pluginArr)
{var plugin = await OpenApiKernelPluginFactory.CreateFromOpenApiAsync(pluginName: pluginItem.PluginName,uri: new Uri(pluginItem.UriString),executionParameters: new OpenApiFunctionExecutionParameters(httpClient){IgnoreNonCompliantErrors = true,EnableDynamicPayload = true,});kernel.Plugins.Add(plugin);
}
var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();
var openAIPromptExecutionSettings = new OpenAIPromptExecutionSettings()
{ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions
};
ChatHistory history = [];
while (true)
{Console.WriteLine("回车开始");Console.ReadLine();Console.WriteLine("用户 > 查询一下订单,然后总汇订单的总金额 ");history.AddUserMessage("总汇一下订单的总金额");var result = await chatCompletionService.GetChatMessageContentAsync(history,executionSettings: openAIPromptExecutionSettings,kernel: kernel);Console.WriteLine("助理 > " + result);history.AddMessage(result.Role, result.Content!);
}
public class PluginSetting
{public string PluginName { get; set; }public string UriString { get; set; }
}

运行结果如下:

  文章来源微信公众号

  想要更快更方便的了解相关知识,可以关注微信公众号 

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

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

相关文章

Semantic Kernel:Phi-4试用

微软在去年12月12日首次展示了Phi-4模型,该模型拥有140亿参数,但表现极为强大。在多项测试中表现优异:GPQA(研究生水平问答)和MATH数学基准测试中,Phi-4的表现超过了OpenAI的GPT-4o,并超越同类顶级开源模型Qwen 2.5 - 14B和Llama 3.3 - 70B。 在美国数学竞赛AMC测试中,…

2025/3/2 【栈与队列】LeetCode232. 用栈实现队列

232. 用栈实现队列 - 力扣(LeetCode) 代码随想录 (programmercarl.com) 思想:用下面的两个栈模拟队列 from collections import deque class MyQueue:def __init__(self):# in主要负责push,out主要负责popself.stackin = []self.stackout = []def push(self, x: int) -> …

Semantic Kernel:Process

Process(流程)是为实现特定业务目标而设计的步骤集合,通过提供服务或产品,为客户创造价值。每个流程由一系列有序的活动组成,这些活动共同完成一个整体目标,旨在提升效率、优化决策,并促进跨团队协作。 在Microsoft Semantic Kernel框架中,Process Framework是一种强大…

Semantic Kernel:新Agent代理

在之前的SemanticKernel中,有一篇关于Agent的文章,不过现在看来其中使用的包过时,所以这篇来更新一下。原文章如下:Semantic Kernel:Agent代理 桂素伟,公众号:桂迹Semantic Kernel:Agent代理原来项目引有的Nuget包如下,版本停留在了1.18.2,2024年9月4日   最新的Agen…

基于uniCloud开发的管理端部署

参考链接: https://doc.dcloud.net.cn/uniCloud/publish.html https://doc.dcloud.net.cn/uniCloud/hosting.html#使用 上传云函数前端网页托管勾选将编译后的资源部署到前端网页托管选项 配置自定义域名配置域名,根据提示在域名管理处添加解析将得到的cname值在域名解析出添…

UnitsNet 库简介

UnitsNet 是一个功能强大的 .NET 库,专为简化物理单位的处理而设计。它提供了丰富的单位类型及其转换功能,使开发人员能够在代码中方便地进行物理单位间的转换、计算和显示。UnitsNet 支持多种领域的物理单位,例如长度、质量、体积、温度、速度、面积等,极大地提高了开发效…

DeepSeek避坑指南:巧用提示词

前言 DeepSeek是国内AI里面的佼佼者,它开源deepseek r1大模型,不仅把AI的使用成本降了下来,同时还撼动了open AI等国际玩家的市场地位。 由于DeepSeek R1是推理模型,在某些时候输出的内容答非所问、甚至会一本正经的胡说八道。今天我们主要聊聊如何能更好的让大模型回答问题…

.NET9里WinForm更新了什么

下面是几个在.NET9中WinForm的新功能!主题Windows Forms 已初步支持暗模式,目标是在 .NET 10 中实现完整支持。应用程序的颜色模式可以设置为以下几种值:SystemColorMode.Classic—(默认)浅色模式,与之前版本的 Windows Forms 相同。 SystemColorMode.System—遵循 Windo…

2019-PTA模拟赛-L1-3 后天(三目表达式-仅代码)

签到题,无解析Code: #include<iostream> using namespace std; int main(){int d;cin >> d;int res = (d + 2) % 7 == 0 ? 7 : (d + 2) % 7;cout << res;return 0; }

SemanticKernel系列,AI系列,SmartFill介绍视频系列

SemanticKernel系列 Semantic Kernel(SK)是微软开发的开源框架,旨在帮助开发者将大型语言模型(LLM)集成到应用程序中。它提供了丰富的工具和功能,支持多种编程语言,简化了LLM的调用和管理过程。通过SK,开发者可以更高效地构建智能应用,实现自然语言处理、对话生成等功…

Python|Windows 系统安装 triton 的方法

若未安装,则在运行调用了该仓库的 Python 脚本时,会报错如下:ModuleNotFoundError: No module named triton在 Windows 系统中,如果直接使用 pip 安装,会报错如下:pip install triton ERROR: Could not find a version that satisfies the requirement triton (from vers…

linux---常见命令

使用的是linux服务器,在这里整理一些linux常见的命令: 1、查看服务器端口命令sudo netstat -tuln打完收工!