46 lines
1.3 KiB
C#
46 lines
1.3 KiB
C#
using System.Text;
|
|
using Newtonsoft.Json;
|
|
|
|
public class LocalEmbeddingService
|
|
{
|
|
private readonly HttpClient _httpClient;
|
|
private readonly string _localOllamaUrl = "http://localhost:11434/api/embeddings";
|
|
|
|
public LocalEmbeddingService()
|
|
{
|
|
_httpClient = new HttpClient();
|
|
}
|
|
|
|
public async Task<float[]> GenerateEmbeddingAsync(string text)
|
|
{
|
|
var payload = new
|
|
{
|
|
model = "bge-m3",
|
|
prompt = text
|
|
};
|
|
|
|
var content = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json");
|
|
|
|
var response = await _httpClient.PostAsync(_localOllamaUrl, content);
|
|
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
var responseContent = await response.Content.ReadAsStringAsync();
|
|
var result = JsonConvert.DeserializeObject<OllamaEmbeddingResponse>(responseContent);
|
|
return result.Embedding;
|
|
}
|
|
else
|
|
{
|
|
var errorText = await response.Content.ReadAsStringAsync();
|
|
throw new Exception($"Failed to generate embedding: {response.StatusCode} - {errorText}");
|
|
}
|
|
}
|
|
}
|
|
|
|
public class OllamaEmbeddingResponse
|
|
{
|
|
[JsonProperty("embedding")]
|
|
public float[] Embedding { get; set; }
|
|
}
|
|
|