From 3b47ed3fb4e8b30a73a8297e6485985fee7c129a Mon Sep 17 00:00:00 2001 From: Stevan Freeborn <65925598+StevanFreeborn@users.noreply.github.com> Date: Fri, 19 Jul 2024 21:15:59 -0500 Subject: [PATCH] fix: yield error when initial stream response is not successful --- src/AnthropicClient/AnthropicApiClient.cs | 8 ++++ .../Integration/AnthropicApiClientTests.cs | 38 +++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/src/AnthropicClient/AnthropicApiClient.cs b/src/AnthropicClient/AnthropicApiClient.cs index a9c120c..ad5d0c8 100644 --- a/src/AnthropicClient/AnthropicApiClient.cs +++ b/src/AnthropicClient/AnthropicApiClient.cs @@ -95,6 +95,14 @@ public class AnthropicApiClient : IAnthropicApiClient public async IAsyncEnumerable CreateMessageAsync(StreamMessageRequest request) { var response = await SendRequestAsync(request); + + if (response.IsSuccessStatusCode is false) + { + var error = Deserialize(await response.Content.ReadAsStringAsync()) ?? new AnthropicError(); + yield return new AnthropicEvent(EventType.Error, new ErrorEventData(error.Error)); + yield break; + } + var anthropicHeaders = new AnthropicHeaders(response.Headers); using var responseContent = await response.Content.ReadAsStreamAsync(); diff --git a/tests/AnthropicClient.Tests/Integration/AnthropicApiClientTests.cs b/tests/AnthropicClient.Tests/Integration/AnthropicApiClientTests.cs index 0e3a353..5272be0 100644 --- a/tests/AnthropicClient.Tests/Integration/AnthropicApiClientTests.cs +++ b/tests/AnthropicClient.Tests/Integration/AnthropicApiClientTests.cs @@ -321,4 +321,42 @@ public class AnthropicApiClientTests : IntegrationTest toolCallResult.IsSuccess.Should().BeTrue(); toolCallResult.Value.Should().Be(getWeather("San Francisco, CA", "fahrenheit")); } + + [Fact] + public async Task CreateMessageAsync_WhenCalledMessageIsStreamAndRequestFails_ItShouldReturnErrorEvent() + { + _mockHttpMessageHandler + .WhenCreateStreamMessageRequest() + .Respond( + HttpStatusCode.BadRequest, + "application/json", + @"{ + ""type"": ""error"", + ""error"": { + ""type"": ""invalid_request_error"", + ""message"": ""messages: roles must alternate between user and assistant, but found multiple user roles in a row"" + } + }" + ); + + var request = new StreamMessageRequest( + model: AnthropicModels.Claude35Sonnet, + messages: [ + new(MessageRole.User, [new TextContent("Hello!")]), + new(MessageRole.User, [new TextContent("Hello!")]) + ] + ); + + var result = Client.CreateMessageAsync(request); + var events = await result.ToListAsync(); + + events.Should().HaveCount(1); + events[0].Type.Should().Be(EventType.Error); + events[0].Data.Should().BeOfType(); + events[0].Data.Should().BeEquivalentTo(new ErrorEventData( + new InvalidRequestError( + "messages: roles must alternate between user and assistant, but found multiple user roles in a row" + ) + )); + } } \ No newline at end of file