changed the logic in the service and added some changes to the tests

This commit is contained in:
stasex 2023-10-27 01:16:02 +03:00
parent 51aca2e270
commit 98377dbf9d
4 changed files with 98 additions and 127 deletions

View File

@ -55,127 +55,110 @@ public class ProductService : IProductService
} }
}; };
if (countOfMessage==1)
var messagesForOpenAI = new List<OpenAiMessage>();
foreach (var item in previousMessages.Items)
{ {
yield return new ServerSentEvent messagesForOpenAI
{ .Add(new OpenAiMessage()
Event = SearchEventType.Message,
Data = previousMessages.Items.FirstOrDefault()?.Text
};
}
if(countOfMessage>1)
{
var messagesForOpenAI = new List<OpenAiMessage>();
messagesForOpenAI.Add(new OpenAiMessage()
{
Role = OpenAiRoleExtensions.RequestConvert(OpenAiRole.System),
Content = promptForGpt
});
foreach (var item in previousMessages.Items)
{
messagesForOpenAI.Add(
new OpenAiMessage()
{ {
Role = item.Role.ToLower(), Role = item.Role.ToLower(),
Content = item.Text Content = item.Text
}); });
}
messagesForOpenAI.Add(new OpenAiMessage()
{
Role = OpenAiRoleExtensions.RequestConvert(OpenAiRole.User),
Content = message.Text
});
chatRequest.Messages.AddRange(messagesForOpenAI);
var suggestionBuffer = new Suggestion();
var messageBuffer = new MessagePart();
var productBuffer = new ProductName();
var currentDataType = SearchEventType.Wishlist;
var dataTypeHolder = string.Empty;
await foreach (var data in _openAiService.GetChatCompletionStream(chatRequest, cancellationToken))
{
if (data.Contains("["))
{
if (dataTypeHolder=="[Message]" && messageBuffer.Text!=null)
{
_wishlistsService.AddMessageToPersonalWishlistAsync(wishlistId, new MessageCreateDto()
{
Text = messageBuffer.Text,
}, cancellationToken);
}
dataTypeHolder = string.Empty;
dataTypeHolder += data;
} }
messagesForOpenAI.Add(new OpenAiMessage()
{
Role = OpenAiRoleExtensions.RequestConvert(OpenAiRole.User),
Content = message.Text
});
chatRequest.Messages.AddRange(messagesForOpenAI);
var suggestionBuffer = new Suggestion();
var messageBuffer = new MessagePart();
var productBuffer = new ProductName();
var currentDataType = SearchEventType.Wishlist;
var dataTypeHolder = string.Empty;
await foreach (var data in _openAiService.GetChatCompletionStream(chatRequest, cancellationToken)) else if (data.Contains("]"))
{ {
if (data.Contains("[")) dataTypeHolder += data;
currentDataType = DetermineDataType(dataTypeHolder);
}
else if (dataTypeHolder=="[" && !data.Contains("["))
{
dataTypeHolder += data;
}
else
{
switch (currentDataType)
{ {
if (dataTypeHolder=="[Message]" && messageBuffer.Text!=null) case SearchEventType.Message:
{ yield return new ServerSentEvent
_wishlistsService.AddMessageToPersonalWishlistAsync(wishlistId, new MessageCreateDto()
{ {
Text = messageBuffer.Text, Event = SearchEventType.Message,
}, cancellationToken); Data = data
} };
dataTypeHolder = string.Empty; messageBuffer.Text += data;
dataTypeHolder += data; break;
}
else if (data.Contains("]")) case SearchEventType.Suggestion:
{ if (data.Contains(";"))
dataTypeHolder += data; {
currentDataType = DetermineDataType(dataTypeHolder);
}
else if (dataTypeHolder=="[" && !data.Contains("["))
{
dataTypeHolder += data;
}
else
{
switch (currentDataType)
{
case SearchEventType.Message:
yield return new ServerSentEvent yield return new ServerSentEvent
{ {
Event = SearchEventType.Message, Event = SearchEventType.Suggestion,
Data = data Data = suggestionBuffer.Text
}; };
messageBuffer.Text += data; suggestionBuffer.Text = string.Empty;
break;
case SearchEventType.Suggestion:
if (data.Contains(";"))
{
yield return new ServerSentEvent
{
Event = SearchEventType.Suggestion,
Data = suggestionBuffer.Text
};
suggestionBuffer.Text = string.Empty;
break;
}
suggestionBuffer.Text += data;
break; break;
}
suggestionBuffer.Text += data;
break;
case SearchEventType.Product: case SearchEventType.Product:
if (data.Contains(";")) if (data.Contains(";"))
{
yield return new ServerSentEvent
{ {
yield return new ServerSentEvent Event = SearchEventType.Product,
{ Data = productBuffer.Name
Event = SearchEventType.Product, };
Data = productBuffer.Name productBuffer.Name = string.Empty;
};
productBuffer.Name = string.Empty;
//a complete description of the entity when the Amazon API is connected //a complete description of the entity when the Amazon API is connected
await _wishlistsService.AddProductToPersonalWishlistAsync(wishlistId, new ProductCreateDto() await _wishlistsService.AddProductToPersonalWishlistAsync(wishlistId, new ProductCreateDto()
{ {
Url = "", Url = "",
Name = productBuffer.Name, Name = productBuffer.Name,
Rating = 0, Rating = 0,
Description = "", Description = "",
ImagesUrls = new []{"", ""}, ImagesUrls = new []{"", ""},
WasOpened = false WasOpened = false
}, cancellationToken); }, cancellationToken);
break;
break; }
} productBuffer.Name += data;
productBuffer.Name += data; break;
break;
}
} }
} }
} }

View File

@ -220,13 +220,8 @@ public class DbInitializer
}, },
new Message new Message
{ {
Text = "You are a Shopping Assistant that helps people find product recommendations. Ask user additional questions if more context needed." + Text = "What are you looking for?",
"\nYou must return data with one of the prefixes:" + Role = "assistant",
"\n[Question] - return question" +
"\n[Suggestions] - return semicolon separated suggestion how to answer to a question" +
"\n[Message] - return text" +
"\n[Products] - return semicolon separated product names",
Role = "system",
WishlistId = wishlistId4, WishlistId = wishlistId4,
CreatedById = user2.Id, CreatedById = user2.Id,
CreatedDateUtc = DateTime.UtcNow CreatedDateUtc = DateTime.UtcNow
@ -234,15 +229,7 @@ public class DbInitializer
new Message new Message
{ {
Text = "What are you looking for?", Text = "What are you looking for?",
Role = "system", Role = "assistant",
WishlistId = wishlistId4,
CreatedById = user2.Id,
CreatedDateUtc = DateTime.UtcNow
},
new Message
{
Text = "What are you looking for?",
Role = "system",
WishlistId = wishlistId3, WishlistId = wishlistId3,
CreatedById = user2.Id, CreatedById = user2.Id,
CreatedDateUtc = DateTime.UtcNow CreatedDateUtc = DateTime.UtcNow

View File

@ -57,7 +57,7 @@ public class ProductsTests : TestsBase
if (eventName == "event: Message") if (eventName == "event: Message")
{ {
foundMessageEvent = true; foundMessageEvent = true;
Assert.Equal("\"What are you looking for?\"", eventData); Assert.NotNull(eventData);
break; break;
} }
} }

View File

@ -49,7 +49,8 @@ public class ProductTests
" 3070TI", " ;", " GTX", " 4070TI", " ;", " ?" " 3070TI", " ;", " GTX", " 4070TI", " ;", " ?"
}; };
var expectedMessages = new List<string> { "What are you looking for?" }; var expectedMessages = new List<string> { " What", " u", " want", " ?" };
var expectedSuggestion = new List<string> { " USB-C", " Keyboard ultra", " USB-C" };
// Mock the GetChatCompletionStream method to provide the expected SSE data // Mock the GetChatCompletionStream method to provide the expected SSE data
_openAiServiceMock.Setup(x => x.GetChatCompletionStream(It.IsAny<ChatCompletionRequest>(), cancellationToken)) _openAiServiceMock.Setup(x => x.GetChatCompletionStream(It.IsAny<ChatCompletionRequest>(), cancellationToken))
@ -63,10 +64,10 @@ public class ProductTests
_wishListServiceMock _wishListServiceMock
.Setup(m => m.GetMessagesPageFromPersonalWishlistAsync( .Setup(m => m.GetMessagesPageFromPersonalWishlistAsync(
It.IsAny<string>(), // Очікуваний параметр wishlistId It.IsAny<string>(),
It.IsAny<int>(), // Очікуваний параметр pageNumber It.IsAny<int>(),
It.IsAny<int>(), // Очікуваний параметр pageSize It.IsAny<int>(),
It.IsAny<CancellationToken>()) // Очікуваний параметр cancellationToken It.IsAny<CancellationToken>())
) )
.ReturnsAsync(new PagedList<MessageDto>( .ReturnsAsync(new PagedList<MessageDto>(
new List<MessageDto> new List<MessageDto>
@ -78,7 +79,6 @@ public class ProductTests
CreatedById = "User2", CreatedById = "User2",
Role = "User" Role = "User"
}, },
}, },
1, 1,
1, 1,
@ -105,6 +105,7 @@ public class ProductTests
// Check if the actual SSE events match the expected SSE events // Check if the actual SSE events match the expected SSE events
Assert.NotNull(actualSseEvents); Assert.NotNull(actualSseEvents);
Assert.Equal(expectedMessages, receivedMessages); Assert.Equal(expectedMessages, receivedMessages);
Assert.Equal(expectedSuggestion, receivedSuggestions);
} }