using System.Net.Http.Json;using System.Text.Json;namespace Agent.Core.Ollama;public static class HttpExtensions{ public static HttpRequestMessage JsonRequest<T>(string url, T body) => new(HttpMethod.Post, url) { Content = JsonContent.Create(body) }; public static T? Deserialize<T>(this string json) => JsonSerializer.Deserialize<T>(json); public static async Task<bool> IsReachableAsync(this HttpClient http, string url) { try { HttpResponseMessage response = await http.GetAsync(url); return response.IsSuccessStatusCode; } catch { return false; } } public static async IAsyncEnumerable<string> ReadStreamLinesAsync(this HttpClient http, HttpRequestMessage request) { using HttpResponseMessage response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); response.EnsureSuccessStatusCode(); using Stream stream = await response.Content.ReadAsStreamAsync(); using StreamReader reader = new(stream); while (!reader.EndOfStream) { string? line = await reader.ReadLineAsync(); if (!string.IsNullOrWhiteSpace(line)) { yield return line; } } }}
Documentation
HttpExtensions
HTTP helpers for Ollama REST calls.
HttpExtensions.cs
- Extension methods for posting JSON and reading streaming responses from Ollama.