I am developing assistants for use within the Unity Engine using C# so that the assistant can have access to the project’s scripts, etc.
I am able to create an assistant, add retrieval files, activate code interpreter and file retrieval, as well as create a thread with a message, then run the assistant and get an initial response.
The trouble I am having is then posting another message to the existing thread. The payload is exactly the same for creating a new thread and posting a message to an existing thread. From my understanding, the endpoint is different but I am unsure what else needs to be different.
Essentially my function checks if I already have a threadID saved; if not, create a new thread and post the message. If it does, use the thread id to post a new message. But that is where it fails, giving me the error “Missing required parameter: ‘role’.”
public async Task PostToThreadAsync(GPTAssistantConfig _config, string _prompt)
{
var payload = new MessagePayload
{
messages = new Message[]
{
new Message { role = "user", content = _prompt }
}
};
string jsonPayload = JsonConvert.SerializeObject(payload);
var sendcontent = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
_httpClient.DefaultRequestHeaders.Clear();
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _config.apiKey);
_httpClient.DefaultRequestHeaders.Add("OpenAI-Beta", "assistants=v1");
string postUrl;
// Check if a thread already exists
if (!string.IsNullOrEmpty(_config.threadID))
{
// Log the thread ID
Debug.Log($"Posting to existing thread {_config.threadID} with payload: {jsonPayload}");
postUrl = $"v1/threads/{_config.threadID}/messages";
}
else
{
// No thread ID, so create a new thread
Debug.Log($"Posting to new thread with payload: {jsonPayload}");
postUrl = $"v1/threads";
}
HttpResponseMessage response = await _httpClient.PostAsync(postUrl, sendcontent);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Debug.Log("Posted successfully. Response: " + responseBody);
ThreadObject threadObj = JsonConvert.DeserializeObject<ThreadObject>(responseBody);
_config.threadID = threadObj.id;
Debug.Log("Thread ID set to: " + _config.threadID);
}
else
{
string newThreadErrorContent = await response.Content.ReadAsStringAsync();
Debug.LogError("Error while posting message: " + response.StatusCode + "\nError Content: " + newThreadErrorContent);
}
}