具体代码:
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using OpenAI;
using OpenAI.Responses;
using System;
using System.ClientModel;
using System.ComponentModel;
using System.Text.Json;
[Description("获取天气")]
static string GetWeather([Description("要获取天气的城市")] string location)
=> $"你成功的调用获取天气工具,城市:{location},空气温度36,下着暴雨";
var options = new OpenAIClientOptions
{
Endpoint = new Uri("http://localhost:11434/v1"), // DeepSeek 的 OpenAI 兼容端点
};
OpenAIClient client = new(new ApiKeyCredential("1222"), options);
// 文件存储的历史提供器,用固定 key 作为文件名,重启后能自动恢复对话
var historyProvider = new FileChatHistoryProvider("default-session");
#pragma warning disable OPENAI001 // GetResponsesClient 是评估用 API,可能在未来变更
ChatClientAgent agent = client.GetResponsesClient().AsAIAgent(
options: new ChatClientAgentOptions
{
Name = "MyFristAgent",
ChatOptions = new ChatOptions
{
Instructions = "你是一个叫猫猫的AI助手",
Tools = [AIFunctionFactory.Create(GetWeather)],
},
ChatHistoryProvider = historyProvider,
},
model: "gemma4:cloud"
);
#pragma warning restore OPENAI001
AgentSession session = await agent.CreateSessionAsync();
Console.WriteLine(historyProvider.HasHistory
? "已从文件恢复历史记录,继续对话(输入 exit 退出):"
: "开始新的对话(输入 exit 退出):");
while (true)
{
Console.Write("你:");
string? input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input))
{
continue;
}
if (input.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
break;
}
Console.Write("猫猫:");
await foreach (var update in agent.RunStreamingAsync(input, session))
{
if (!string.IsNullOrEmpty(update.Text))
{
Console.Write(update.Text);
}
}
Console.WriteLine();
}
// 基于 JSON 文件的聊天历史提供器,文件名 = 传入的 key
class FileChatHistoryProvider : ChatHistoryProvider
{
private readonly string _filePath;
private readonly List<ChatMessage> _messages = [];
public FileChatHistoryProvider(string key)
{
_filePath = Path.Combine(AppContext.BaseDirectory, $"chat-{key}.json");
if (File.Exists(_filePath))
{
var json = File.ReadAllText(_filePath);
var saved = JsonSerializer.Deserialize<List<ChatMessage>>(json);
if (saved is not null)
{
_messages.AddRange(saved);
}
}
}
public bool HasHistory => _messages.Count > 0;
// 每次运行前:把文件里的历史提供给 agent
protected override ValueTask<IEnumerable<ChatMessage>> ProvideChatHistoryAsync(
ChatHistoryProvider.InvokingContext context,
CancellationToken cancellationToken = default)
=> new(_messages.ToList());
// 每次运行后:把新的请求/响应消息追加到文件
protected override async ValueTask StoreChatHistoryAsync(
ChatHistoryProvider.InvokedContext context,
CancellationToken cancellationToken = default)
{
foreach (var msg in context.RequestMessages.Concat(context.ResponseMessages))
{
_messages.Add(msg);
}
var json = JsonSerializer.Serialize(_messages);
await File.WriteAllTextAsync(_filePath, json, cancellationToken);
}
}