Skip to content

Add Sample Responses for Azure.AI.OpenAI #49799

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 18 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,11 @@
</AssemblyAttribute>
</ItemGroup>

<ItemGroup>
<None Update="Samples\Resources\batman.wav">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<Link>Resources/batman.wav</Link>
</None>
</ItemGroup>

</Project>
72 changes: 72 additions & 0 deletions sdk/openai/Azure.AI.OpenAI/tests/ResponsesTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,37 @@ public async Task FileSearch(string deploymentName)
}
}

[TestCase(Gpt4oMiniDeployment)]
public async Task ResponseImageInput(string deploymentName)
{
OpenAIClient topLevelClient = GetTestTopLevelClient(DefaultResponsesConfig);
OpenAIFileClient fileClient = topLevelClient.GetOpenAIFileClient();
VectorStoreClient vectorStoreClient = topLevelClient.GetVectorStoreClient();
OpenAIResponseClient client = topLevelClient.GetOpenAIResponseClient(deploymentName);

Uri imageUri = new("https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Microsoft_logo.svg/512px-Microsoft_logo.svg.png");
ResponseContentPart imagePart = ResponseContentPart.CreateInputImagePart(imageUri);
ResponseContentPart textPart = ResponseContentPart.CreateInputTextPart("Describe this image");

List<ResponseContentPart> contentParts = [imagePart, textPart];

OpenAIResponse response = client.CreateResponse(
inputItems:
[
ResponseItem.CreateSystemMessageItem("You are a helpful assistant that describes images"),
ResponseItem.CreateUserMessageItem(contentParts)
]);

Assert.That(response.OutputItems?.Count, Is.EqualTo(1));
MessageResponseItem? message = response?.OutputItems?[0] as MessageResponseItem;
Assert.That(message, Is.Not.Null);

await foreach (ResponseItem inputItem in client.GetResponseInputItemsAsync(response?.Id))
{
Console.WriteLine(ModelReaderWriter.Write(inputItem).ToString());
}
}

[RecordedTest]
public async Task ComputerToolWithScreenshotRoundTrip()
{
Expand Down Expand Up @@ -953,4 +984,45 @@ private static void AssertSerializationRoundTrip<T>(
}
"""),
false);

[TestCase(Gpt4oMiniDeployment)]
public void ChatbotTellsJokes(string deploymentName)
{
OpenAIResponseClient client = GetResponseTestClientForDeployment(deploymentName);

OpenAIResponse response = client.CreateResponse(
inputItems: [
ResponseItem.CreateSystemMessageItem("You are a humorous assistant who tells jokes"),
ResponseItem.CreateUserMessageItem("Please tell me 3 jokes about trains")
]);

string output = ((MessageResponseItem)response.OutputItems[0]).Content[0].Text;

Assert.That(output, Is.Not.Null.And.Not.Empty);
}

[TestCase(Gpt4oMiniDeployment)]
public void ChatbotSummarizeTextTest(string deploymentName)
{
OpenAIResponseClient client = GetResponseTestClientForDeployment(deploymentName);

OpenAIResponse response = client.CreateResponse(
inputItems: [
ResponseItem.CreateSystemMessageItem("You are a helpful assistant that summarizes texts"),
ResponseItem.CreateAssistantMessageItem("Please summarize the following text in one sentence"),
ResponseItem.CreateUserMessageItem(GetSummarizationPromt())
]);

string output = ((MessageResponseItem)response.OutputItems[0]).Content[0].Text;
Assert.That(output, Is.Not.Null.And.Not.Empty);
}
private static string GetSummarizationPromt()
{
String textToSummarize = "On July 20, 1969, Apollo 11 successfully landed the first humans on the Moon. "
+ "Astronauts Neil Armstrong and Buzz Aldrin spent over two hours collecting samples and conducting experiments, "
+ "while Michael Collins remained in orbit aboard the command module. "
+ "The mission marked a significant achievement in space exploration, fulfilling President John F. Kennedy's goal of landing a man on the Moon and returning him safely to Earth. "
+ "The lunar samples brought back provided invaluable insights into the Moon's composition and history.";
return "Summarize the following text.%n" + "Text:%n" + textToSummarize + "%n Summary:%n";
}
}
165 changes: 165 additions & 0 deletions sdk/openai/Azure.AI.OpenAI/tests/Samples/01_Chat.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using System.Diagnostics;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Azure.AI.OpenAI.Samples;

Expand Down Expand Up @@ -40,6 +41,80 @@ public void BasicChat()
#endregion
}

public void ConversationChat()
{
#region Snippet:ConversationResponse
AzureOpenAIClient azureClient = new(
new Uri("https://your-azure-openai-resource.com"),
new DefaultAzureCredential());
ChatClient chatClient = azureClient.GetChatClient("my-gpt-35-turbo-deployment");

var messages = new List<ChatMessage>
{
new UserChatMessage("Tell me a story about building the best SDK!")
};

for (int i = 0; i < 4; i++)
{
ChatCompletion completion = chatClient.CompleteChat(messages, new()
{
MaxOutputTokenCount = 2048
});

Console.WriteLine($"\n--- Response {i + 1} ---\n");

foreach (var choice in completion.Content)
{
Console.WriteLine(choice.Text);
messages.Add(new AssistantChatMessage(choice.Text));
}

string exclamations = new('!', i);
string questions = new('?', i);

messages.Add(new SystemChatMessage($"Be as snarky as possible when replying!{exclamations}"));
messages.Add(new UserChatMessage($"But why?{questions}"));
}
#endregion
}

public async Task ConversationChatAsync()
{
#region Snippet:ConversationChatAsync
AzureOpenAIClient azureClient = new(
new Uri("https://your-azure-openai-resource.com"),
new DefaultAzureCredential());
ChatClient chatClient = azureClient.GetChatClient("my-gpt-35-turbo-deployment");

var messages = new List<ChatMessage>
{
new UserChatMessage("Tell me a story about building the best SDK!")
};

for (int i = 0; i < 4; i++)
{
ChatCompletion completion = await chatClient.CompleteChatAsync(messages, new()
{
MaxOutputTokenCount = 2048
});

Console.WriteLine($"\n--- Response {i + 1} ---\n");

foreach (var choice in completion.Content)
{
Console.WriteLine(choice.Text);
messages.Add(new AssistantChatMessage(choice.Text));
}

string exclamations = new('!', i);
string questions = new('?', i);

messages.Add(new SystemChatMessage($"Be as snarky as possible when replying!{exclamations}"));
messages.Add(new UserChatMessage($"But why?{questions}"));
}
#endregion
}

public void StreamingChat()
{
#region Snippet:StreamChatMessages
Expand All @@ -66,6 +141,96 @@ public void StreamingChat()
#endregion
}

public void StructuredOutputs()
{
#region Snippet:StructuredOutputs
AzureOpenAIClient azureClient = new(
new Uri("https://your-azure-openai-resource.com"),
new DefaultAzureCredential());
ChatClient client = azureClient.GetChatClient("my-gpt-35-turbo-deployment");

IEnumerable<ChatMessage> messages =
[
new UserChatMessage("What's heavier, a pound of feathers or sixteen ounces of steel?")
];
ChatCompletionOptions options = new ChatCompletionOptions()
{
ResponseFormat = ChatResponseFormat.CreateJsonSchemaFormat(
"test_schema",
BinaryData.FromString("""
{
"type": "object",
"properties": {
"answer": {
"type": "string"
},
"steps": {
"type": "array",
"items": {
"type": "string"
}
}
},
"required": [
"answer",
"steps"
],
"additionalProperties": false
}
"""),
"a single final answer with a supporting collection of steps",
jsonSchemaIsStrict: true)
};
ChatCompletion completion = client.CompleteChat(messages, options)!;
Console.WriteLine(completion!.Content![0].Text);
#endregion
}

public async Task StructuredOutputsAsync()
{
#region Snippet:StructuredOutputsAsync
AzureOpenAIClient azureClient = new(
new Uri("https://your-azure-openai-resource.com"),
new DefaultAzureCredential());
ChatClient client = azureClient.GetChatClient("my-gpt-35-turbo-deployment");

IEnumerable<ChatMessage> messages =
[
new UserChatMessage("What's heavier, a pound of feathers or sixteen ounces of steel?")
];
ChatCompletionOptions options = new ChatCompletionOptions()
{
ResponseFormat = ChatResponseFormat.CreateJsonSchemaFormat(
"test_schema",
BinaryData.FromString("""
{
"type": "object",
"properties": {
"answer": {
"type": "string"
},
"steps": {
"type": "array",
"items": {
"type": "string"
}
}
},
"required": [
"answer",
"steps"
],
"additionalProperties": false
}
"""),
"a single final answer with a supporting collection of steps",
jsonSchemaIsStrict: true)
};
ChatCompletion completion = await client.CompleteChatAsync(messages, options)!;
Console.WriteLine(completion!.Content![0].Text);
#endregion
}

public void ChatWithTools()
{
#region Snippet:ChatTools:DefineTool
Expand Down
Loading
Loading