Create the Conversation Thread
_client.DefaultRequestHeaders.Add("OpenAI-Beta", "assistants=v2");
response = _client.PostAsync("https://api.openai.com/v1/threads", null).Result;
if (!response.IsSuccessStatusCode)
{
var errorResponse = JsonConvert.DeserializeObject<ErrorResponse>(threadIdResponse);
throw new AiClientException(errorResponse?.Error.Message);
}
var threadIdObj = JsonConvert.DeserializeObject<ThreadResponse>(threadIdResponse);
_threadId = threadIdObj?.Id ?? string.Empty;
return _threadId;
{
public string Id { get; set; }
public string Object { get; set; }
public long CreatedAt { get; set; }
public object AssistantId { get; set; }
public string ThreadId { get; set; }
public object RunId { get; set; }
public string Role { get; set; }
public List<AiContent> Content { get; set; }
public List<object> FileIds { get; set; }
public Metadata Metadata { get; set; }
}
Adding Messages
if (string.IsNullOrEmpty(_apiKey)) throw new AiClientException("OpenAI ApiKey is not set");
if (string.IsNullOrEmpty(_threadId)) CreateThread();
if (string.IsNullOrEmpty(message)) throw new AiClientException("Message is empty");
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey);
_client.DefaultRequestHeaders.Add("OpenAI-Beta", "assistants=v2");
var messageRequest = new AiRequestMessage { Role = "user", Content = message };
public class AiRequestMessage
{
[JsonProperty("role")]
public string Role { get; set; }
[JsonProperty("content")]
public string Content { get; set; }
}
var messageRequest = new AiRequestMessage { Role = "user", Content = message };
var messageRequest = new AiRequestMessage { Role = "assistant", Content = message };
Run
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey);
_client.DefaultRequestHeaders.Add("OpenAI-Beta", "assistants=v2");
var custAsst = new Assistant { assistant_id = _assistantId };
var json = JsonConvert.SerializeObject(custAsst);
var content = new StringContent(json, Encoding.UTF8, "application/json");
response = await _client.PostAsync($"https://api.openai.com/v1/threads/{_threadId}/ru ns", content);
var responseContent = await response.Content.ReadAsStringAsync();
var responseObj = JsonConvert.DeserializeObject<RunResponse> (responseContent);
var runId = responseObj?.Id;
var runStatus = responseObj?.Status;
//if not completed, poll again
if (runId != null)
{
while (runStatus != null && !FinalStatuses.Contains(runStatus))
{
await Task.Delay(1000);
response = await _client.GetAsync($"https://api.openai.com/v1/threads/{_threadId}/runs/{runId}");
responseContent = response.Content.ReadAsStringAsync().Result;
responseObj = JsonConvert.DeserializeObject<RunResponse>(responseContent);
runStatus = responseObj?.Status;
}
}
}
await GetResponse();
Get AI Response
HttpResponseMessage response;
using (_client = new HttpClient())
{
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey);
_client.DefaultRequestHeaders.Add("OpenAI-Beta", "assistants=v1");
response = await _client.GetAsync($"https://api.openai.com/v1/threads/{_threadId}/messages");
}
var responseContent = response.Content.ReadAsStringAsync().Result;
try
{
var data = JsonConvert.DeserializeObject<ChatResponse>(responseContent);
_messages.Clear();
_messages = data?.Data.Select(x => new AiContent() { Type = x.Role, Text = x.Content[0].Text }).ToList() ?? new List<AiContent>();
}
catch (Exception ex)
{
throw new AiClientException("Error retrieving messages");
}
public class Data
{
public string Id { get; set; }
public string Object { get; set; }
public long CreatedAt { get; set; }
public string AssistantId { get; set; }
public string ThreadId { get; set; }
public string RunId { get; set; }
public string Role { get; set; }
public List<AiContent> Content { get; set; }
public List<object> FileIds { get; set; }
public Metadata Metadata { get; set; }
}
public class AiContent
{
public string Type { get; set; }
public Text Text { get; set; }
}
public class Text
{
public string Value { get; set; }
public List<object> Annotations { get; set; }
}
Furthering the Project
Full File
using AiClients.Exceptions;
using AiClients.Interfaces;
using AiClients.Models;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Text;
namespace CustomGptClient.Services
{
public class AssitantService : IAiService
{
private string _threadId;
private IConfiguration _config;
private string _apiKey;
private string _assistantId;
private List<AiContent> _messages;
private string _assistantName;
private HttpClient _client;
private List<string> FinalStatuses = new List<string> { "completed", "failed", "cancelled", "expired" };
public AssitantService(IConfiguration configuration)
{
_config = configuration;
_apiKey = _config.GetSection("OpenAI:ApiKey")?.Value ?? string.Empty;
_assistantId = _config.GetSection("OpenAI:AssistantId")?.Value ?? string.Empty;
_messages = new List<AiContent>();
}
private string CreateThread()
{
if (string.IsNullOrEmpty(_apiKey)) throw new AiClientException("OpenAI ApiKey is not set");
HttpResponseMessage response;
using (var _client = new HttpClient())
{
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey);
_client.DefaultRequestHeaders.Add("OpenAI-Beta", "assistants=v2");
response = _client.PostAsync("https://api.openai.com/v1/threads", null).Result;
}
var threadIdResponse = response.Content.ReadAsStringAsync().Result;
if (!response.IsSuccessStatusCode)
{
var errorResponse = JsonConvert.DeserializeObject<ErrorResponse>(threadIdResponse);
throw new AiClientException(errorResponse?.Error.Message);
}
var threadIdObj = JsonConvert.DeserializeObject<ThreadResponse>(threadIdResponse);
_threadId = threadIdObj?.Id ?? string.Empty;
return _threadId;
}
public async Task AddMessage(string message)
{
if (string.IsNullOrEmpty(_apiKey)) throw new AiClientException("OpenAI ApiKey is not set");
if (string.IsNullOrEmpty(_threadId)) CreateThread();
if (string.IsNullOrEmpty(message)) throw new AiClientException("Message is empty");
HttpResponseMessage response;
using (_client = new HttpClient())
{
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey);
_client.DefaultRequestHeaders.Add("OpenAI-Beta", "assistants=v1");
var messageRequest = new AiRequestMessage { Role = "user", Content = message };
var json = JsonConvert.SerializeObject(messageRequest);
var content = new StringContent(json, Encoding.UTF8, "application/json");
response = await _client.PostAsync($"https://api.openai.com/v1/threads/{_threadId}/messages", content);
}
var threadIdResponse = response.Content.ReadAsStringAsync().Result;
if (!response.IsSuccessStatusCode)
{
var errorResponse = JsonConvert.DeserializeObject<ErrorResponse>(threadIdResponse);
throw new AiClientException(errorResponse?.Error.Message);
}
var threadIdObj = JsonConvert.DeserializeObject<ThreadResponse>(threadIdResponse);
await CreateRun();
}
public async Task CreateRun()
{
HttpResponseMessage response;
using (_client = new HttpClient())
{
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey);
_client.DefaultRequestHeaders.Add("OpenAI-Beta", "assistants=v2");
var custAsst = new Assistant { assistant_id = _assistantId };
var json = JsonConvert.SerializeObject(custAsst);
var content = new StringContent(json, Encoding.UTF8, "application/json");
response = await _client.PostAsync($"https://api.openai.com/v1/threads/{_threadId}/runs", content);
var responseContent = await response.Content.ReadAsStringAsync();
var responseObj = JsonConvert.DeserializeObject<RunResponse>(responseContent);
var runId = responseObj?.Id;
var runStatus = responseObj?.Status;
//if not completed, poll again
if (runId != null)
{
while (runStatus != null && !FinalStatuses.Contains(runStatus))
{
await Task.Delay(1000);
response = await _client.GetAsync($"https://api.openai.com/v1/threads/{_threadId}/runs/{runId}");
responseContent = response.Content.ReadAsStringAsync().Result;
responseObj = JsonConvert.DeserializeObject<RunResponse>(responseContent);
runStatus = responseObj?.Status;
}
}
}
await GetResponse();
}
public async Task GetResponse()
{
HttpResponseMessage response;
using (_client = new HttpClient())
{
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey);
_client.DefaultRequestHeaders.Add("OpenAI-Beta", "assistants=v1");
response = await _client.GetAsync($"https://api.openai.com/v1/threads/{_threadId}/messages");
}
var responseContent = response.Content.ReadAsStringAsync().Result;
try
{
var data = JsonConvert.DeserializeObject<ChatResponse>(responseContent);
_messages.Clear();
_messages = data?.Data.Select(x => new AiContent() { Type = x.Role, Text = x.Content[0].Text }).ToList() ?? new List<AiContent>();
}
catch (Exception ex)
{
throw new AiClientException("Error retrieving messages");
}
}
}
Comments
Post a Comment