using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json.Serialization; using System.Text; using System.Text.Json; namespace OllamaStudy.CApp { class Program { private static readonly HttpClient httpClient = new HttpClient(); static async Task Main() { string model = "llama3.2:1b"; string prompt = "What is the weather in Toronto?"; var functionDefinition = new { name = "get_current_weather", description = "Get the current weather for a city.", parameters = new { type = "object", properties = new { city = new { type = "string", description = "The name of the city" } }, required = new[] { "city" } } }; var requestBody = new { model = model, messages = new[] { new { role = "user", content = prompt } }, tools = new[] { new { type = "function", function = functionDefinition } }, stream = false }; string jsonRequest = JsonSerializer.Serialize(requestBody); var request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri("http://localhost:11434/api/chat"), Content = new StringContent(jsonRequest, Encoding.UTF8, "application/json") }; try { HttpResponseMessage response = await httpClient.SendAsync(request); string responseContent = await response.Content.ReadAsStringAsync(); Console.WriteLine("🔹 Response from model:"); Console.WriteLine(responseContent); var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; var jsonResponse = JsonSerializer.Deserialize(responseContent, options); if (jsonResponse?.Message?.ToolCalls != null && jsonResponse.Message.ToolCalls.Length > 0) { foreach (var toolCall in jsonResponse.Message.ToolCalls) { if (toolCall.Function?.Name == "get_current_weather") { string city = toolCall.Function.Arguments?.City ?? "unknown"; Console.WriteLine($"🌦️ Calling get_current_weather with city: {city}"); string weatherInfo = GetCurrentWeather(city); Console.WriteLine($"✅ Weather in {city}: {weatherInfo}"); } } } else { Console.WriteLine("⚠️ No tool calls detected."); } } catch (Exception ex) { Console.WriteLine($"❌ Error connecting to Ollama: {ex.Message}"); } } static string GetCurrentWeather(string city) { return $"The weather in {city} is sunny with 25°C."; } } class OllamaResponse { [JsonPropertyName("message")] public MessageContent? Message { get; set; } } class MessageContent { [JsonPropertyName("tool_calls")] public ToolCall[]? ToolCalls { get; set; } } class ToolCall { [JsonPropertyName("function")] public FunctionData? Function { get; set; } } class FunctionData { [JsonPropertyName("name")] public string? Name { get; set; } [JsonPropertyName("arguments")] public ToolArguments? Arguments { get; set; } } class ToolArguments { [JsonPropertyName("city")] public string? City { get; set; } } }