从上一篇文章可以看出使用Microsoft.Extensions.AI来跟大模型对话是多么简单,微软为我们封装了很多东西,我们作为调包侠,无脑调用即可。
本着只要你想吃苦,就有吃不完的苦,只要你想摆烂,就有停不下的爽的原则,给聊天增加日志,比聊天本身更简单。
首先,回顾上一节中的代码,有个OpenAIClientOptions,对就是这个Option,它可以直接设置一个ClientLoggingOptions,对,就这么简单。
1 2 3 4
| OpenAIClientOptions clientOptions = new OpenAIClientOptions(); clientOptions.Endpoint = new Uri("https:...."); OpenAIClient aiClient = new OpenAIClient(new System.ClientModel.ApiKeyCredential("...."),clientOptions);
|
完整演示
一切简化,我们用简单的NLog
- 你要用
Nlog,那一定要先配置下Nlog啦,自己安装相关的Nuget包NLog.Extensions.Logging
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| var config = new LoggingConfiguration();
ColoredConsoleTarget target = new ColoredConsoleTarget("console") { Layout = "${longdate} | ${level:uppercase=true:padding=-5} | ${logger} | ${message} ${exception:format=tostring}" };
FileTarget fileTarget = new FileTarget() { FileName = @"C:\Users\aaa\Desktop\aaaaa.log", AutoFlush = true, DeleteOldFileOnStartup = true };
config.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Error, fileTarget); LogManager.Configuration = config;
|
- 让 .NET 的日志系统使用 NLog 作为日志输出后端
ILoggerFactory logFactory = LoggerFactory.Create(builder => builder.AddNLog());
- 新建一个
ClientLoggingOptions,然后配置一下
1 2 3 4 5 6
| ClientLoggingOptions clientLogOpt = new ClientLoggingOptions(); clientLogOpt.LoggerFactory = logFactory; clientLogOpt.EnableLogging = true; clientLogOpt.EnableMessageLogging = true; clientLogOpt.EnableMessageContentLogging = true;
|
- 完事
1 2
| OpenAIClientOptions clientOptions = new OpenAIClientOptions(); clientOptions.ClientLoggingOptions = clientLogOpt;
|