本文是Ollama系列教程的第6篇,主要介绍如何通过SDK将ollama集成到c#程序中。
Ollama 提供了HTTP API的访问,如果需要使用SDK集成到项目中,需要引用第三方库OllamaSharp
,直接使用nuget进行安装即可。
初始化client
// set up the client
var uri = new Uri("http://localhost:11434");
var ollama = new OllamaApiClient(uri);
获取模型列表
// list models
var models = await ollama.ListLocalModelsAsync();
if (models != null && models.Any())
{
Console.WriteLine("Models: ");
foreach (var model in models)
{
Console.WriteLine(" " + model.Name);
}
}
创建对话
// chat with ollama
var chat = new Chat(ollama);
Console.WriteLine();
Console.WriteLine($"Chat with {ollama.SelectedModel}");
while (true)
{
var currentMessageCount = chat.Messages.Count;
Console.Write(">>");
var message = Console.ReadLine();
await foreach (var answerToken in chat.SendAsync(message, Tools))
Console.Write(answerToken);
Console.WriteLine();
// find the latest message from the assistant and possible tools
var newMessages = chat.Messages.Skip(currentMessageCount - 1);
foreach (var newMessage in newMessages)
{
if (newMessage.ToolCalls?.Any() ?? false)
{
Console.WriteLine("\nTools used:");
foreach (var function in newMessage.ToolCalls.Where(t => t.Function != null).Select(t => t.Function))
{
Console.WriteLine($" - {function!.Name}");
Console.WriteLine($" - parameters");
if (function?.Arguments is not null)
{
foreach (var argument in function.Arguments)
Console.WriteLine($" - {argument.Key}: {argument.Value}");
}
}
}
if (newMessage.Role.GetValueOrDefault() == OllamaSharp.Models.Chat.ChatRole.Tool)
Console.WriteLine($" - results: \"{newMessage.Content}\"");
}
}
Tools
如果是LLM是大脑,那么工具就是四肢,通过工具我们能具备LLM与外界交互的能力。
定义工具:
/// <summary>
/// Gets the current datetime
/// </summary>
/// <returns>The current datetime</returns>
[OllamaTool]
public static string GetDateTime() => $"{DateTime.Now: yyyy-MM-dd HH:mm:ss ddd}";
使用工具:
public static List<object> Tools { get; } = [
new GetDateTimeTool(),
];
await chat.SendAsync(message, Tools)