如何拿到接口返回的消耗token
SemanticKernel
以下引用自官方案例
- Text模型
- 使用Kernel
FunctionResult functionResult = await kernel.InvokePromptAsync(promptTestDataGeneration);
CompletionsUsage? usage = FunctionResult.Metadata?["Usage"] as CompletionsUsage;
//回答消耗的Token
Console.WriteLine(usage.CompletionTokens);
//提示词消耗的Token
Console.WriteLine(usage.PromptTokens);
//一共消耗的Token
Console.WriteLine(usage.TotalTokens);
```
- 直接使用AzureOpenAIChatCompletionService
var service = new AzureOpenAIChatCompletionService("deployment", "https://endpoint", "api-key", "model-id", this._httpClient);
var result = await service.GetChatMessageContentsAsync([], settings, kernel);
var usage = result[0].Metadata?["Usage"] as CompletionsUsage;
//回答消耗的Token
Console.WriteLine(usage.CompletionTokens);
//提示词消耗的Token
Console.WriteLine(usage.PromptTokens);
//一共消耗的Token
Console.WriteLine(usage.TotalTokens);
```
- 使用Kernel
- 暂不支持Embedding模型
客制方法
- 当前SK仅支持OpenAI和AzureOpenAI的模型调用,如何需要其他模型供应商目前有两种办法解决
- 使用OneAPI做一个中转成AzureOpenAI然后使用上述SK的方法使用。
- 自定义方法发送请求,使用AddKeyedSingleton注入。
定义IAzureTextEmbeddingCompletionService接口,引用ITextEmbeddingGenerationService
public interface IAzureTextEmbeddingCompletionService : ITextEmbeddingGenerationService
{
Task<(List<float>, TextEmbeddingUsage)> GenerateEmbeddingsByUsageAsync(IList<string> data, Kernel kernel = null, CancellationToken cancellationToken = default);
}
定义AzureTextEmbeddingCompletionService实现IAzureTextEmbeddingCompletionService接口
public class AzureTextEmbeddingCompletionService : IAzureTextEmbeddingCompletionService
{
private readonly SemanticAzureOpenAIConfig config;
private readonly Dictionary<string, object?> _attributes = new();
private readonly ModelClient client;
public IReadOnlyDictionary<string, object> Attributes => _attributes; public AzureTextEmbeddingCompletionService(ModelOptions options)
{
config = new SemanticAzureOpenAIConfig()
{
ApiKey = options.ApiKey,
Endpoint = options.Endpoint,
DeploymentName = "text-embedding-ada-002",
ApiVersion = options.ModelVersion
};
client = new(config.ApiKey, ModelType.AzureOpenAI, config.Endpoint);
} public async Task<IList<ReadOnlyMemory<float>>> GenerateEmbeddingsAsync(IList<string> data, Kernel kernel = null, CancellationToken cancellationToken = default)
{
var result = await client.AzureOpenAI.GenerateEmbeddingsAsync(config.DeploymentName, data.First());
var list = result.Data[0].Embedding.ToList();
IList<ReadOnlyMemory<float>> readOnlyMemoryList = list.Select(f => new ReadOnlyMemory<float>(new[] { f })).ToList();
return readOnlyMemoryList;
} public async Task<(List<float>, TextEmbeddingUsage)> GenerateEmbeddingsByUsageAsync(IList<string> data, Kernel kernel = null, CancellationToken cancellationToken = default)
{
var result = await client.AzureOpenAI.GenerateEmbeddingsAsync(config.DeploymentName, data.First());
var list = result.Data[0].Embedding.ToList();
IList<ReadOnlyMemory<float>> readOnlyMemoryList = list.Select(f => new ReadOnlyMemory<float>(new[] { f })).ToList();
return (list, result.Usage);
}
}
//定义入参类
public class ModelOptions
{
public string AppId { get; set; } public string ApiKey { get; set; } public string ApiSecret { get; set; }
public string Endpoint { get; set; }
public string DeploymentName { get; set; }
public ChatHistory ChatHistory { get; set; } = new ChatHistory(); public string ModelVersion { get; set; }
}
ModelClient的实现参考对话模型的对接方式实现,原理是一致的这里不详述。(.Net接入AzureOpenAI、OpenAI、通义千问、智谱AI、讯飞星火、文心一言大语言模型。 | FaceMan)
创建Kernel实例,注入IAzureTextEmbeddingCompletionService服务
var builder = Kernel.CreateBuilder();
var options = new ModelOptions()
{
Endpoint = "YourEndpoint",
ApiKey = "YourApiKey",
DeploymentName = "YourDeploymentName",,
ChatHistory = "YourChatHistory",//Embedding可不填
};
builder.Services.AddKeyedSingleton<IAzureTextEmbeddingCompletionService>("AzureOpenAIEmbedding", new AzureTextEmbeddingCompletionService(options));
获取Embedding服务,获取Token
var service = _kernel.GetRequiredService<IAzureTextEmbeddingCompletionService>();
var res = await service.GenerateEmbeddingsByUsageAsync
(new List<string> { partitionContent }, cancellationToken: cancellationToken)
.ConfigureAwait(false);
// item1 向量,item2消耗的token
float[] result = res.Item1.ToArray<float>();
totalToken += res.Item2.TotalTokens;
Embedding embedding = new Embedding(result);
如何拿到接口返回的消耗token的更多相关文章
- httprunner学习3-extract提取token值参数关联(上个接口返回的token,传给下个接口请求参数)
前言 如何将上个接口的返回token,传给下个接口当做请求参数?这是最常见的一个问题了. 解决这个问题其实很简单,我们只需取出token值,设置为一个中间变量a,下个接口传这个变量a就可以了.那么接下 ...
- Postman----登录接口返回的reponse中token值传递给其他接口的一个简单接口测试示例
注: 在进行接口测试时,我们都需要使用登录,并且其他的接口都要在登录后进行,那么必不可少的会使用到将登录接口的reponse返回结果中的某些参数值需要进行返回,并传递给其他接口,这样才可以进行登录后的 ...
- C#进阶系列——WebApi 接口返回值不困惑:返回值类型详解
前言:已经有一个月没写点什么了,感觉心里空落落的.今天再来篇干货,想要学习Webapi的园友们速速动起来,跟着博主一起来学习吧.之前分享过一篇 C#进阶系列——WebApi接口传参不再困惑:传参详解 ...
- WebApi 接口返回值类型详解 ( 转 )
使用过Webapi的园友应该都知道,Webapi的接口返回值主要有四种类型 void无返回值 IHttpActionResult HttpResponseMessage 自定义类型 此篇就围绕这四块分 ...
- WebApi接口返回值不困惑:返回值类型详解
前言:已经有一个月没写点什么了,感觉心里空落落的.今天再来篇干货,想要学习Webapi的园友们速速动起来,跟着博主一起来学习吧.作为程序猿,我们都知道参数和返回值是编程领域不可分割的两大块,此前分享了 ...
- WebApi 接口返回值不困惑:返回值类型详解。IHttpActionResult、void、HttpResponseMessage、自定义类型
首先声明,我还没有这么强大的功底,只是感觉博主写的很好,就做了一个复制,请别因为这个鄙视我,博主网址:http://www.cnblogs.com/landeanfen/p/5501487.html ...
- (转)C# WebApi 接口返回值不困惑:返回值类型详解
原文地址:http://www.cnblogs.com/landeanfen/p/5501487.html 正文 前言:已经有一个月没写点什么了,感觉心里空落落的.今天再来篇干货,想要学习Webapi ...
- [转]C#进阶系列——WebApi 接口返回值不困惑:返回值类型详解
本文转自:http://www.cnblogs.com/landeanfen/p/5501487.html 阅读目录 一.void无返回值 二.IHttpActionResult 1.Json(T c ...
- C#进阶系列——WebApi接口返回值类型详解
阅读目录 一.void无返回值 二.IHttpActionResult 1.Json(T content) 2.Ok(). Ok(T content) 3.NotFound() 4.其他 5.自定义I ...
- WebService如何封装XML请求 以及解析接口返回的XML
原 WebService如何封装XML请求 以及解析接口返回的XML 置顶 2019年08月16日 15:00:47 童子泛舟 阅读数 28 标签: XML解析WebService第三方API 更多 ...
随机推荐
- 【libGDX】使用Mesh绘制三角形
1 Mesh 和 ShaderProgram 简介 1.1 创建 Mesh 1)Mesh 的构造方法 public Mesh(boolean isStatic, int maxVertices, ...
- 深入理解Go语言(03):scheduler调度器 - 基本介绍
一:什么是调度 平常我们在生活中会有哪些调度的例子呢?比如十字路口的红绿灯,它就是一种调度系统.在交通十字路口,每个路口上多多少少有一些车辆,为了限制这些车辆不随意行驶,就建起了红绿灯调度系统.红绿灯 ...
- 内置方法,序列化模块pickle和json---day15
1.内置方法 ads 绝对值函数 val = -16 res = abs(val) print(res) #16 round 四舍五入(n.5 n为偶数则舍去,n.5 n为奇数 则进一) 奇进偶不进 ...
- Django关于StreamingHttpResponse与FileResponse响应文件或视频的下载请求
StreamingHttpResponse from django.http import StreamingHttpResponse StreamingHttpResponse(streaming_ ...
- 【LeetCode数组#2双指针法】移除元素、删除有序数组中的重复项、移动0
移除元素 力扣27题目链接(opens new window) 给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度. 不要使用额外的数组 ...
- 06、etcd 写请求执行流程
本篇内容主要来源于自己学习的视频,如有侵权,请联系删除,谢谢. 上一节我们学习了 etcd 读请求执行流程,这一节,我们来学习 etcd 写请求执行流程. 1.etcd写请求概览 etcd 一个写请求 ...
- 【Azure 媒体服务】使用编码预设文件(Preset.json)来自定义编码任务 -- 创建视频缩略图
问题描述 在Azure门户上创建Transform Encoding时候,只能选择 Built-in Preset 编码方式(如:H265ContentAwareEncoding) 在创建编码任务时, ...
- 【Azure 服务总线】有何办法可以把原来老环境的Azure Service Bus 配置快速复制到新环境配置,而且原环境不删除
问题描述 有何办法可以把原来老环境的Azure Service Bus 配置快速复制到新环境配置,而且原环境不删除 问题解答 在通常的做法中,是可以在Service Bus所在的资源组中,通过&quo ...
- C++//vector存放自定义数据类型
1 //vector存放自定义数据类型 2 3 #include <iostream> 4 #include <string> 5 #include<fstream> ...
- vue使用cordova的大坑!!
额,前段时间用 cordova 包了个 vue 项目,跑真机,完美.跑公司安卓系统虚拟机,垮. 原因找了很久,最后发现是路由的问题,使用了 createWebHistory ,去掉了 hash ,虽然 ...