diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/Azure.AI.ChatProtocol.sln b/sdk/machinelearning/Azure.AI.ChatProtocol/Azure.AI.ChatProtocol.sln new file mode 100644 index 000000000000..24a7e22f8cce --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/Azure.AI.ChatProtocol.sln @@ -0,0 +1,56 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29709.97 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Core.TestFramework", "..\..\core\Azure.Core.TestFramework\src\Azure.Core.TestFramework.csproj", "{ECC730C1-4AEA-420C-916A-66B19B79E4DC}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azure.AI.ChatProtocol", "src\Azure.AI.ChatProtocol.csproj", "{28FF4005-4467-4E36-92E7-DEA27DEB1519}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azure.AI.ChatProtocol.Tests", "tests\Azure.AI.ChatProtocol.Tests.csproj", "{1F1CD1D4-9932-4B73-99D8-C252A67D4B46}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Release|Any CPU.Build.0 = Release|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Release|Any CPU.Build.0 = Release|Any CPU + {ECC730C1-4AEA-420C-916A-66B19B79E4DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {ECC730C1-4AEA-420C-916A-66B19B79E4DC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {ECC730C1-4AEA-420C-916A-66B19B79E4DC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {ECC730C1-4AEA-420C-916A-66B19B79E4DC}.Release|Any CPU.Build.0 = Release|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Release|Any CPU.Build.0 = Release|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Release|Any CPU.Build.0 = Release|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Release|Any CPU.Build.0 = Release|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Debug|Any CPU.Build.0 = Debug|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Release|Any CPU.ActiveCfg = Release|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Release|Any CPU.Build.0 = Release|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A97F4B90-2591-4689-B1F8-5F21FE6D6CAE} + EndGlobalSection +EndGlobal diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/CHANGELOG.md b/sdk/machinelearning/Azure.AI.ChatProtocol/CHANGELOG.md new file mode 100644 index 000000000000..13dd08af78ab --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/CHANGELOG.md @@ -0,0 +1,11 @@ +# Release History + +## 1.0.0-beta.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/Directory.Build.props b/sdk/machinelearning/Azure.AI.ChatProtocol/Directory.Build.props new file mode 100644 index 000000000000..63bd836ad44b --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/Directory.Build.props @@ -0,0 +1,6 @@ + + + + diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/README.md b/sdk/machinelearning/Azure.AI.ChatProtocol/README.md new file mode 100644 index 000000000000..189533ce758b --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/README.md @@ -0,0 +1,86 @@ +# Azure.AI.ChatProtocol client library for .NET + +Azure.AI.ChatProtocol is a managed service that helps developers get secret simply and securely. + +Use the client library for to: + +* [Get secret](https://docs.microsoft.com/azure) + +[Source code][source_root] | [Package (NuGet)][package] | [API reference documentation][reference_docs] | [Product documentation][azconfig_docs] | [Samples][source_samples] + + [Source code](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/machinelearning/Azure.AI.ChatProtocol/src) | [Package (NuGet)](https://www.nuget.org/packages) | [API reference documentation](https://azure.github.io/azure-sdk-for-net) | [Product documentation](https://docs.microsoft.com/azure) + +## Getting started + +This section should include everything a developer needs to do to install and create their first client connection *very quickly*. + +### Install the package + +First, provide instruction for obtaining and installing the package or library. This section might include only a single line of code, like `dotnet add package package-name`, but should enable a developer to successfully install the package from NuGet, npm, or even cloning a GitHub repository. + +Install the client library for .NET with [NuGet](https://www.nuget.org/ ): + +```dotnetcli +dotnet add package Azure.AI.ChatProtocol --prerelease +``` + +### Prerequisites + +Include a section after the install command that details any requirements that must be satisfied before a developer can [authenticate](#authenticate-the-client) and test all of the snippets in the [Examples](#examples) section. For example, for Cosmos DB: + +> You must have an [Azure subscription](https://azure.microsoft.com/free/dotnet/) and [Cosmos DB account](https://docs.microsoft.com/azure/cosmos-db/account-overview) (SQL API). In order to take advantage of the C# 8.0 syntax, it is recommended that you compile using the [.NET Core SDK](https://dotnet.microsoft.com/download) 3.0 or higher with a [language version](https://docs.microsoft.com/dotnet/csharp/language-reference/configure-language-version#override-a-default) of `latest`. It is also possible to compile with the .NET Core SDK 2.1.x using a language version of `preview`. + +### Authenticate the client + +If your library requires authentication for use, such as for Azure services, include instructions and example code needed for initializing and authenticating. + +For example, include details on obtaining an account key and endpoint URI, setting environment variables for each, and initializing the client object. + +## Key concepts + +The *Key concepts* section should describe the functionality of the main classes. Point out the most important and useful classes in the package (with links to their reference pages) and explain how those classes work together. Feel free to use bulleted lists, tables, code blocks, or even diagrams for clarity. + +Include the *Thread safety* and *Additional concepts* sections below at the end of your *Key concepts* section. You may remove or add links depending on what your library makes use of: + +### Thread safety + +We guarantee that all client instance methods are thread-safe and independent of each other ([guideline](https://azure.github.io/azure-sdk/dotnet_introduction.html#dotnet-service-methods-thread-safety)). This ensures that the recommendation of reusing client instances is always safe, even across threads. + +### Additional concepts + +[Client options](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#configuring-service-clients-using-clientoptions) | +[Accessing the response](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#accessing-http-response-details-using-responset) | +[Long-running operations](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#consuming-long-running-operations-using-operationt) | +[Handling failures](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#reporting-errors-requestfailedexception) | +[Diagnostics](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/Diagnostics.md) | +[Mocking](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#mocking) | +[Client lifetime](https://devblogs.microsoft.com/azure-sdk/lifetime-management-and-thread-safety-guarantees-of-azure-sdk-net-clients/) + + +## Examples + +You can familiarize yourself with different APIs using [Samples](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/machinelearning/Azure.AI.ChatProtocol/samples). + +## Troubleshooting + +Describe common errors and exceptions, how to "unpack" them if necessary, and include guidance for graceful handling and recovery. + +Provide information to help developers avoid throttling or other service-enforced errors they might encounter. For example, provide guidance and examples for using retry or connection policies in the API. + +If the package or a related package supports it, include tips for logging or enabling instrumentation to help them debug their code. + +## Next steps + +* Provide a link to additional code examples, ideally to those sitting alongside the README in the package's `/samples` directory. +* If appropriate, point users to other packages that might be useful. +* If you think there's a good chance that developers might stumble across your package in error (because they're searching for specific functionality and mistakenly think the package provides that functionality), point them to the packages they might be looking for. + +## Contributing + +This is a template, but your SDK readme should include details on how to contribute code to the repo/package. + + +[style-guide-msft]: https://docs.microsoft.com/style-guide/capitalization +[style-guide-cloud]: https://aka.ms/azsdk/cloud-style-guide + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-net/sdk/machinelearning/Azure.AI.ChatProtocol/README.png) diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Azure.AI.ChatProtocol.csproj b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Azure.AI.ChatProtocol.csproj new file mode 100644 index 000000000000..9238bad50a03 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Azure.AI.ChatProtocol.csproj @@ -0,0 +1,21 @@ + + + This is the Azure.AI.ChatProtocol client library for developing .NET applications with rich experience. + Azure SDK Code Generation Azure.AI.ChatProtocol for Azure Data Plane + 1.0.0-beta.1 + Azure.AI.ChatProtocol + $(RequiredTargetFrameworks) + true + + + + + + + + + + + + + diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/AIChatProtocolClientBuilderExtensions.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/AIChatProtocolClientBuilderExtensions.cs new file mode 100644 index 000000000000..1297c148c011 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/AIChatProtocolClientBuilderExtensions.cs @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure; +using Azure.AI.ChatProtocol; +using Azure.Core.Extensions; + +namespace Microsoft.Extensions.Azure +{ + /// Extension methods to add to client builder. + public static partial class AIChatProtocolClientBuilderExtensions + { + /// Registers a instance. + /// The builder to register with. + /// The Uri to use. + /// A credential used to authenticate to an Azure Service. + public static IAzureClientBuilder AddChatProtocolClient(this TBuilder builder, Uri endpoint, AzureKeyCredential credential) + where TBuilder : IAzureClientFactoryBuilder + { + return builder.RegisterClientFactory((options) => new ChatProtocolClient(endpoint, credential, options)); + } + + /// Registers a instance. + /// The builder to register with. + /// The Uri to use. + public static IAzureClientBuilder AddChatProtocolClient(this TBuilder builder, Uri endpoint) + where TBuilder : IAzureClientFactoryBuilderWithCredential + { + return builder.RegisterClientFactory((options, cred) => new ChatProtocolClient(endpoint, cred, options)); + } + + /// Registers a instance. + /// The builder to register with. + /// The configuration values. + public static IAzureClientBuilder AddChatProtocolClient(this TBuilder builder, TConfiguration configuration) + where TBuilder : IAzureClientFactoryBuilderWithConfiguration + { + return builder.RegisterClientFactory(configuration); + } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/AIChatProtocolModelFactory.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/AIChatProtocolModelFactory.cs new file mode 100644 index 000000000000..e544c2eb6c57 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/AIChatProtocolModelFactory.cs @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.ChatProtocol +{ + /// Model factory for models. + public static partial class AIChatProtocolModelFactory + { + /// Initializes a new instance of ChatCompletion. + /// The collection of generated completions. + /// A new instance for mocking. + public static ChatCompletion ChatCompletion(IEnumerable choices = null) + { + choices ??= new List(); + + return new ChatCompletion(choices?.ToList()); + } + + /// Initializes a new instance of ChatChoice. + /// The index of the of the chat choice, relative to the other choices in the same completion. + /// The chat message for a given chat completion. + /// + /// Field that allows the chat app to store and retrieve data, the structure of such data is dependant on the backend + /// being used. The client must send back the data in this field unchanged in subsequent requests, until the chat app + /// sends a new one. The data in this field can be used to implement stateful services, such as remembering previous + /// conversations or user preferences. + /// + /// + /// Context allows the chat app to receive extra parameters from the client, such as temperature, functions, or + /// customer_info. These parameters are specific to the chat app and not understood by the generic clients. + /// + /// The reason this chat completion completed its generation. + /// A new instance for mocking. + public static ChatChoice ChatChoice(long index = default, ChatMessage message = null, BinaryData sessionState = null, IReadOnlyDictionary context = null, FinishReason finishReason = default) + { + context ??= new Dictionary(); + + return new ChatChoice(index, message, sessionState, context, finishReason); + } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatChoice.Serialization.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatChoice.Serialization.cs new file mode 100644 index 000000000000..9accde561619 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatChoice.Serialization.cs @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Azure.AI.ChatProtocol +{ + public partial class ChatChoice + { + internal static ChatChoice DeserializeChatChoice(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + long index = default; + ChatMessage message = default; + Optional sessionState = default; + Optional> context = default; + FinishReason finishReason = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt64(); + continue; + } + if (property.NameEquals("message"u8)) + { + message = ChatMessage.DeserializeChatMessage(property.Value); + continue; + } + if (property.NameEquals("sessionState"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + sessionState = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("context"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + if (property0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(property0.Name, null); + } + else + { + dictionary.Add(property0.Name, BinaryData.FromString(property0.Value.GetRawText())); + } + } + context = dictionary; + continue; + } + if (property.NameEquals("finishReason"u8)) + { + finishReason = new FinishReason(property.Value.GetString()); + continue; + } + } + return new ChatChoice(index, message, sessionState.Value, Optional.ToDictionary(context), finishReason); + } + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatChoice FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatChoice(document.RootElement); + } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatChoice.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatChoice.cs new file mode 100644 index 000000000000..96cae3a7715e --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatChoice.cs @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using Azure.Core; + +namespace Azure.AI.ChatProtocol +{ + /// The representation of a single generated completion. + public partial class ChatChoice + { + /// Initializes a new instance of ChatChoice. + /// The index of the of the chat choice, relative to the other choices in the same completion. + /// The chat message for a given chat completion. + /// The reason this chat completion completed its generation. + /// is null. + internal ChatChoice(long index, ChatMessage message, FinishReason finishReason) + { + Argument.AssertNotNull(message, nameof(message)); + + Index = index; + Message = message; + Context = new ChangeTrackingDictionary(); + FinishReason = finishReason; + } + + /// Initializes a new instance of ChatChoice. + /// The index of the of the chat choice, relative to the other choices in the same completion. + /// The chat message for a given chat completion. + /// + /// Field that allows the chat app to store and retrieve data, the structure of such data is dependant on the backend + /// being used. The client must send back the data in this field unchanged in subsequent requests, until the chat app + /// sends a new one. The data in this field can be used to implement stateful services, such as remembering previous + /// conversations or user preferences. + /// + /// + /// Context allows the chat app to receive extra parameters from the client, such as temperature, functions, or + /// customer_info. These parameters are specific to the chat app and not understood by the generic clients. + /// + /// The reason this chat completion completed its generation. + internal ChatChoice(long index, ChatMessage message, BinaryData sessionState, IReadOnlyDictionary context, FinishReason finishReason) + { + Index = index; + Message = message; + SessionState = sessionState; + Context = context; + FinishReason = finishReason; + } + + /// The index of the of the chat choice, relative to the other choices in the same completion. + public long Index { get; } + /// + /// The chat message for a given chat completion. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + public ChatMessage Message { get; } + /// + /// Field that allows the chat app to store and retrieve data, the structure of such data is dependant on the backend + /// being used. The client must send back the data in this field unchanged in subsequent requests, until the chat app + /// sends a new one. The data in this field can be used to implement stateful services, such as remembering previous + /// conversations or user preferences. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData SessionState { get; } + /// + /// Context allows the chat app to receive extra parameters from the client, such as temperature, functions, or + /// customer_info. These parameters are specific to the chat app and not understood by the generic clients. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public IReadOnlyDictionary Context { get; } + /// The reason this chat completion completed its generation. + public FinishReason FinishReason { get; } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatCompletion.Serialization.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatCompletion.Serialization.cs new file mode 100644 index 000000000000..c737de770073 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatCompletion.Serialization.cs @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using System.Text.Json; +using Azure; + +namespace Azure.AI.ChatProtocol +{ + public partial class ChatCompletion + { + internal static ChatCompletion DeserializeChatCompletion(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList choices = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("choices"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ChatChoice.DeserializeChatChoice(item)); + } + choices = array; + continue; + } + } + return new ChatCompletion(choices); + } + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatCompletion FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatCompletion(document.RootElement); + } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatCompletion.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatCompletion.cs new file mode 100644 index 000000000000..cc982645bc10 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatCompletion.cs @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; +using Azure.Core; + +namespace Azure.AI.ChatProtocol +{ + /// Representation of the response to a chat completion request. + public partial class ChatCompletion + { + /// Initializes a new instance of ChatCompletion. + /// The collection of generated completions. + /// is null. + internal ChatCompletion(IEnumerable choices) + { + Argument.AssertNotNull(choices, nameof(choices)); + + Choices = choices.ToList(); + } + + /// Initializes a new instance of ChatCompletion. + /// The collection of generated completions. + internal ChatCompletion(IReadOnlyList choices) + { + Choices = choices; + } + + /// The collection of generated completions. + public IReadOnlyList Choices { get; } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatCompletionChunk.Serialization.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatCompletionChunk.Serialization.cs new file mode 100644 index 000000000000..348cda8976a8 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatCompletionChunk.Serialization.cs @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using System.Text.Json; +using Azure; + +namespace Azure.AI.ChatProtocol +{ + internal partial class ChatCompletionChunk + { + internal static ChatCompletionChunk DeserializeChatCompletionChunk(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList choices = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("choices"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ChoiceDelta.DeserializeChoiceDelta(item)); + } + choices = array; + continue; + } + } + return new ChatCompletionChunk(choices); + } + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatCompletionChunk FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatCompletionChunk(document.RootElement); + } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatCompletionChunk.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatCompletionChunk.cs new file mode 100644 index 000000000000..61f4d3052f4c --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatCompletionChunk.cs @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; +using Azure.Core; + +namespace Azure.AI.ChatProtocol +{ + /// A single response to a streaming completion request. + internal partial class ChatCompletionChunk + { + /// Initializes a new instance of ChatCompletionChunk. + /// The collection of choice deltas received in this chunk. + /// is null. + internal ChatCompletionChunk(IEnumerable choices) + { + Argument.AssertNotNull(choices, nameof(choices)); + + Choices = choices.ToList(); + } + + /// Initializes a new instance of ChatCompletionChunk. + /// The collection of choice deltas received in this chunk. + internal ChatCompletionChunk(IReadOnlyList choices) + { + Choices = choices; + } + + /// The collection of choice deltas received in this chunk. + public IReadOnlyList Choices { get; } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatCompletionOptions.Serialization.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatCompletionOptions.Serialization.cs new file mode 100644 index 000000000000..ced4fa6bf056 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatCompletionOptions.Serialization.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.ChatProtocol +{ + public partial class ChatCompletionOptions : IUtf8JsonSerializable + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + { + writer.WriteStartObject(); + writer.WritePropertyName("messages"u8); + writer.WriteStartArray(); + foreach (var item in Messages) + { + writer.WriteObjectValue(item); + } + writer.WriteEndArray(); + writer.WritePropertyName("stream"u8); + writer.WriteBooleanValue(Stream); + if (Optional.IsDefined(SessionState)) + { + writer.WritePropertyName("sessionState"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(SessionState); +#else + using (JsonDocument document = JsonDocument.Parse(SessionState)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + if (Optional.IsCollectionDefined(Context)) + { + writer.WritePropertyName("context"u8); + writer.WriteStartObject(); + foreach (var item in Context) + { + writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + writer.WriteEndObject(); + } + writer.WriteEndObject(); + } + + /// Convert into a Utf8JsonRequestContent. + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this); + return content; + } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatCompletionOptions.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatCompletionOptions.cs new file mode 100644 index 000000000000..7cb7331d9062 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatCompletionOptions.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; +using Azure.Core; + +namespace Azure.AI.ChatProtocol +{ + /// The configuration for a chat completion request. + public partial class ChatCompletionOptions + { + /// Initializes a new instance of ChatCompletionOptions. + /// The collection of context messages associated with this completion request. + /// is null. + public ChatCompletionOptions(IEnumerable messages) + { + Argument.AssertNotNull(messages, nameof(messages)); + + Messages = messages.ToList(); + Context = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of ChatCompletionOptions. + /// The collection of context messages associated with this completion request. + /// Indicates whether the completion is a streaming or non-streaming completion. + /// + /// Field that allows the chat app to store and retrieve data, the structure of such data is dependant on the backend + /// being used. The client must send back the data in this field unchanged in subsequent requests, until the chat app + /// sends a new one. The data in this field can be used to implement stateful services, such as remembering previous + /// conversations or user preferences. + /// + /// + /// Context allows the chat app to receive extra parameters from the client, such as temperature, functions, or + /// customer_info. These parameters are specific to the chat app and not understood by the generic clients. + /// + internal ChatCompletionOptions(IList messages, bool stream, BinaryData sessionState, IDictionary context) + { + Messages = messages; + Stream = stream; + SessionState = sessionState; + Context = context; + } + + /// + /// The collection of context messages associated with this completion request. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + public IList Messages { get; } + /// Indicates whether the completion is a streaming or non-streaming completion. + public bool Stream { get; } = false; + + /// + /// Field that allows the chat app to store and retrieve data, the structure of such data is dependant on the backend + /// being used. The client must send back the data in this field unchanged in subsequent requests, until the chat app + /// sends a new one. The data in this field can be used to implement stateful services, such as remembering previous + /// conversations or user preferences. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData SessionState { get; set; } + /// + /// Context allows the chat app to receive extra parameters from the client, such as temperature, functions, or + /// customer_info. These parameters are specific to the chat app and not understood by the generic clients. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public IDictionary Context { get; } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatMessage.Serialization.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatMessage.Serialization.cs new file mode 100644 index 000000000000..558edbc3a4b5 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatMessage.Serialization.cs @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Azure.AI.ChatProtocol +{ + public partial class ChatMessage : IUtf8JsonSerializable + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + { + writer.WriteStartObject(); + writer.WritePropertyName("kind"u8); + writer.WriteStringValue(Kind.ToString()); + writer.WritePropertyName("role"u8); + writer.WriteStringValue(Role.ToString()); + if (Optional.IsDefined(SessionState)) + { + writer.WritePropertyName("sessionState"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(SessionState); +#else + using (JsonDocument document = JsonDocument.Parse(SessionState)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + writer.WriteEndObject(); + } + + internal static ChatMessage DeserializeChatMessage(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("kind", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "text": return TextChatMessage.DeserializeTextChatMessage(element); + } + } + return UnknownChatMessage.DeserializeUnknownChatMessage(element); + } + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatMessage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatMessage(document.RootElement); + } + + /// Convert into a Utf8JsonRequestContent. + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this); + return content; + } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatMessage.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatMessage.cs new file mode 100644 index 000000000000..246975d7b2b6 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatMessage.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; + +namespace Azure.AI.ChatProtocol +{ + /// + /// A single, role-attributed message within a chat completion interaction. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + public abstract partial class ChatMessage + { + /// Initializes a new instance of ChatMessage. + /// The role associated with the message. + protected ChatMessage(ChatRole role) + { + Role = role; + } + + /// Initializes a new instance of ChatMessage. + /// The type of the message. If not specified, the message is assumed to be text. + /// The role associated with the message. + /// + /// Field that allows the chat app to store and retrieve data, the structure of such data is dependant on the backend + /// being used. The client must send back the data in this field unchanged in subsequent requests, until the chat app + /// sends a new one. The data in this field can be used to implement stateful services, such as remembering previous + /// conversations or user preferences. + /// + internal ChatMessage(MessageKind kind, ChatRole role, BinaryData sessionState) + { + Kind = kind; + Role = role; + SessionState = sessionState; + } + + /// The type of the message. If not specified, the message is assumed to be text. + internal MessageKind Kind { get; set; } + /// The role associated with the message. + public ChatRole Role { get; set; } + /// + /// Field that allows the chat app to store and retrieve data, the structure of such data is dependant on the backend + /// being used. The client must send back the data in this field unchanged in subsequent requests, until the chat app + /// sends a new one. The data in this field can be used to implement stateful services, such as remembering previous + /// conversations or user preferences. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData SessionState { get; set; } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatMessageDelta.Serialization.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatMessageDelta.Serialization.cs new file mode 100644 index 000000000000..a2eaf8bf074a --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatMessageDelta.Serialization.cs @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Text.Json; +using Azure; + +namespace Azure.AI.ChatProtocol +{ + internal partial class ChatMessageDelta + { + internal static ChatMessageDelta DeserializeChatMessageDelta(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("kind", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "text": return TextChatMessageDelta.DeserializeTextChatMessageDelta(element); + } + } + return UnknownChatMessageDelta.DeserializeUnknownChatMessageDelta(element); + } + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatMessageDelta FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatMessageDelta(document.RootElement); + } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatMessageDelta.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatMessageDelta.cs new file mode 100644 index 000000000000..d1c36b46ea85 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatMessageDelta.cs @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; + +namespace Azure.AI.ChatProtocol +{ + /// + /// The representation of a delta message received in a streaming completion. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + internal abstract partial class ChatMessageDelta + { + /// Initializes a new instance of ChatMessageDelta. + protected ChatMessageDelta() + { + } + + /// Initializes a new instance of ChatMessageDelta. + /// The type of the message. If not specified, the message is assumed to be text. + /// The role associated with the message. + /// + /// Field that allows the chat app to store and retrieve data, the structure of such data is dependant on the backend + /// being used. The client must send back the data in this field unchanged in subsequent requests, until the chat app + /// sends a new one. The data in this field can be used to implement stateful services, such as remembering previous + /// conversations or user preferences. + /// + internal ChatMessageDelta(MessageKind kind, ChatRole? role, BinaryData sessionState) + { + Kind = kind; + Role = role; + SessionState = sessionState; + } + + /// The type of the message. If not specified, the message is assumed to be text. + internal MessageKind Kind { get; set; } + /// The role associated with the message. + public ChatRole? Role { get; } + /// + /// Field that allows the chat app to store and retrieve data, the structure of such data is dependant on the backend + /// being used. The client must send back the data in this field unchanged in subsequent requests, until the chat app + /// sends a new one. The data in this field can be used to implement stateful services, such as remembering previous + /// conversations or user preferences. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData SessionState { get; } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatProtocolClient.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatProtocolClient.cs new file mode 100644 index 000000000000..85688dc65e97 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatProtocolClient.cs @@ -0,0 +1,376 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using System.Threading.Tasks; +using Azure; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.AI.ChatProtocol +{ + // Data plane generated client. + /// The ChatProtocol service client. + public partial class ChatProtocolClient + { + private const string AuthorizationHeader = "api-key"; + private readonly AzureKeyCredential _keyCredential; + private static readonly string[] AuthorizationScopes = new string[] { }; + private readonly TokenCredential _tokenCredential; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + private readonly string _apiVersion; + + /// The ClientDiagnostics is used to provide tracing support for the client library. + internal ClientDiagnostics ClientDiagnostics { get; } + + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline => _pipeline; + + /// Initializes a new instance of ChatProtocolClient for mocking. + protected ChatProtocolClient() + { + } + + /// Initializes a new instance of ChatProtocolClient. + /// The Uri to use. + /// A credential used to authenticate to an Azure Service. + /// or is null. + public ChatProtocolClient(Uri endpoint, AzureKeyCredential credential) : this(endpoint, credential, new ChatProtocolClientOptions()) + { + } + + /// Initializes a new instance of ChatProtocolClient. + /// The Uri to use. + /// A credential used to authenticate to an Azure Service. + /// or is null. + public ChatProtocolClient(Uri endpoint, TokenCredential credential) : this(endpoint, credential, new ChatProtocolClientOptions()) + { + } + + /// Initializes a new instance of ChatProtocolClient. + /// The Uri to use. + /// A credential used to authenticate to an Azure Service. + /// The options for configuring the client. + /// or is null. + public ChatProtocolClient(Uri endpoint, AzureKeyCredential credential, ChatProtocolClientOptions options) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(credential, nameof(credential)); + options ??= new ChatProtocolClientOptions(); + + ClientDiagnostics = new ClientDiagnostics(options, true); + _keyCredential = credential; + _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), new HttpPipelinePolicy[] { new AzureKeyCredentialPolicy(_keyCredential, AuthorizationHeader) }, new ResponseClassifier()); + _endpoint = endpoint; + _apiVersion = options.Version; + } + + /// Initializes a new instance of ChatProtocolClient. + /// The Uri to use. + /// A credential used to authenticate to an Azure Service. + /// The options for configuring the client. + /// or is null. + public ChatProtocolClient(Uri endpoint, TokenCredential credential, ChatProtocolClientOptions options) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(credential, nameof(credential)); + options ??= new ChatProtocolClientOptions(); + + ClientDiagnostics = new ClientDiagnostics(options, true); + _tokenCredential = credential; + _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), new HttpPipelinePolicy[] { new BearerTokenAuthenticationPolicy(_tokenCredential, AuthorizationScopes) }, new ResponseClassifier()); + _endpoint = endpoint; + _apiVersion = options.Version; + } + + /// Creates a new streaming chat completion. + /// The route where the endpoint exposes the chat operations. + /// The configuration for a streaming chat completion request. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + internal virtual async Task> CreateStreamingAsync(string operationRoute, StreamingChatCompletionOptions streamingChatCompletionOptions, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(operationRoute, nameof(operationRoute)); + Argument.AssertNotNull(streamingChatCompletionOptions, nameof(streamingChatCompletionOptions)); + + RequestContext context = FromCancellationToken(cancellationToken); + using RequestContent content = streamingChatCompletionOptions.ToRequestContent(); + Response response = await CreateStreamingAsync(operationRoute, content, context).ConfigureAwait(false); + return Response.FromValue(ChatCompletionChunk.FromResponse(response), response); + } + + /// Creates a new streaming chat completion. + /// The route where the endpoint exposes the chat operations. + /// The configuration for a streaming chat completion request. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + internal virtual Response CreateStreaming(string operationRoute, StreamingChatCompletionOptions streamingChatCompletionOptions, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(operationRoute, nameof(operationRoute)); + Argument.AssertNotNull(streamingChatCompletionOptions, nameof(streamingChatCompletionOptions)); + + RequestContext context = FromCancellationToken(cancellationToken); + using RequestContent content = streamingChatCompletionOptions.ToRequestContent(); + Response response = CreateStreaming(operationRoute, content, context); + return Response.FromValue(ChatCompletionChunk.FromResponse(response), response); + } + + /// + /// [Protocol Method] Creates a new streaming chat completion. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The route where the endpoint exposes the chat operations. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task CreateStreamingAsync(string operationRoute, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(operationRoute, nameof(operationRoute)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("ChatProtocolClient.CreateStreaming"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateStreamingRequest(operationRoute, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates a new streaming chat completion. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The route where the endpoint exposes the chat operations. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response CreateStreaming(string operationRoute, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(operationRoute, nameof(operationRoute)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("ChatProtocolClient.CreateStreaming"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateStreamingRequest(operationRoute, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Creates a new chat completion. + /// The route where the endpoint exposes the chat operations. + /// The configuration for a chat completion request. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual async Task> CreateAsync(string operationRoute, ChatCompletionOptions chatCompletionOptions, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(operationRoute, nameof(operationRoute)); + Argument.AssertNotNull(chatCompletionOptions, nameof(chatCompletionOptions)); + + RequestContext context = FromCancellationToken(cancellationToken); + using RequestContent content = chatCompletionOptions.ToRequestContent(); + Response response = await CreateAsync(operationRoute, content, context).ConfigureAwait(false); + return Response.FromValue(ChatCompletion.FromResponse(response), response); + } + + /// Creates a new chat completion. + /// The route where the endpoint exposes the chat operations. + /// The configuration for a chat completion request. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual Response Create(string operationRoute, ChatCompletionOptions chatCompletionOptions, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(operationRoute, nameof(operationRoute)); + Argument.AssertNotNull(chatCompletionOptions, nameof(chatCompletionOptions)); + + RequestContext context = FromCancellationToken(cancellationToken); + using RequestContent content = chatCompletionOptions.ToRequestContent(); + Response response = Create(operationRoute, content, context); + return Response.FromValue(ChatCompletion.FromResponse(response), response); + } + + /// + /// [Protocol Method] Creates a new chat completion. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The route where the endpoint exposes the chat operations. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task CreateAsync(string operationRoute, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(operationRoute, nameof(operationRoute)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("ChatProtocolClient.Create"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateRequest(operationRoute, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates a new chat completion. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The route where the endpoint exposes the chat operations. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response Create(string operationRoute, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(operationRoute, nameof(operationRoute)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("ChatProtocolClient.Create"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateRequest(operationRoute, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + internal HttpMessage CreateCreateStreamingRequest(string operationRoute, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/", false); + uri.AppendPath(operationRoute, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateCreateRequest(string operationRoute, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/", false); + uri.AppendPath(operationRoute, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + private static RequestContext DefaultRequestContext = new RequestContext(); + internal static RequestContext FromCancellationToken(CancellationToken cancellationToken = default) + { + if (!cancellationToken.CanBeCanceled) + { + return DefaultRequestContext; + } + + return new RequestContext() { CancellationToken = cancellationToken }; + } + + private static ResponseClassifier _responseClassifier200; + private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatProtocolClientOptions.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatProtocolClientOptions.cs new file mode 100644 index 000000000000..94b8f8a4f4b8 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatProtocolClientOptions.cs @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; + +namespace Azure.AI.ChatProtocol +{ + /// Client options for ChatProtocolClient. + public partial class ChatProtocolClientOptions : ClientOptions + { + private const ServiceVersion LatestVersion = ServiceVersion.V2023_10_01_Preview; + + /// The version of the service to use. + public enum ServiceVersion + { + /// Service version "2023-10-01-preview". + V2023_10_01_Preview = 1, + } + + internal string Version { get; } + + /// Initializes new instance of ChatProtocolClientOptions. + public ChatProtocolClientOptions(ServiceVersion version = LatestVersion) + { + Version = version switch + { + ServiceVersion.V2023_10_01_Preview => "2023-10-01-preview", + _ => throw new NotSupportedException() + }; + } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatRole.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatRole.cs new file mode 100644 index 000000000000..e8dbbf586f53 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChatRole.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.ChatProtocol +{ + /// A representation of the intended purpose of a message. + public readonly partial struct ChatRole : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ChatRole(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string UserValue = "user"; + private const string SystemValue = "system"; + private const string AssistantValue = "assistant"; + + /// The role that provides input to the completion. + public static ChatRole User { get; } = new ChatRole(UserValue); + /// The role that instructs or configures the behavior of the assistant. + public static ChatRole System { get; } = new ChatRole(SystemValue); + /// The role that provides responses to the system-instructed, user-prompted input. + public static ChatRole Assistant { get; } = new ChatRole(AssistantValue); + /// Determines if two values are the same. + public static bool operator ==(ChatRole left, ChatRole right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ChatRole left, ChatRole right) => !left.Equals(right); + /// Converts a string to a . + public static implicit operator ChatRole(string value) => new ChatRole(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ChatRole other && Equals(other); + /// + public bool Equals(ChatRole other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value?.GetHashCode() ?? 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChoiceDelta.Serialization.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChoiceDelta.Serialization.cs new file mode 100644 index 000000000000..e1b278e43c9c --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChoiceDelta.Serialization.cs @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Azure.AI.ChatProtocol +{ + internal partial class ChoiceDelta + { + internal static ChoiceDelta DeserializeChoiceDelta(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + long index = default; + ChatMessageDelta delta = default; + Optional sessionState = default; + Optional> context = default; + Optional finishReason = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt64(); + continue; + } + if (property.NameEquals("delta"u8)) + { + delta = ChatMessageDelta.DeserializeChatMessageDelta(property.Value); + continue; + } + if (property.NameEquals("sessionState"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + sessionState = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("context"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + if (property0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(property0.Name, null); + } + else + { + dictionary.Add(property0.Name, BinaryData.FromString(property0.Value.GetRawText())); + } + } + context = dictionary; + continue; + } + if (property.NameEquals("finishReason"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + finishReason = new FinishReason(property.Value.GetString()); + continue; + } + } + return new ChoiceDelta(index, delta, sessionState.Value, Optional.ToDictionary(context), Optional.ToNullable(finishReason)); + } + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChoiceDelta FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChoiceDelta(document.RootElement); + } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChoiceDelta.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChoiceDelta.cs new file mode 100644 index 000000000000..5c9ad39c648a --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/ChoiceDelta.cs @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using Azure.Core; + +namespace Azure.AI.ChatProtocol +{ + /// The representation of an incremental choice received in a streaming completion. + internal partial class ChoiceDelta + { + /// Initializes a new instance of ChoiceDelta. + /// The index of the of the chat choice, relative to the other choices in the same completion. + /// The partial message received for this choice. + /// is null. + internal ChoiceDelta(long index, ChatMessageDelta delta) + { + Argument.AssertNotNull(delta, nameof(delta)); + + Index = index; + Delta = delta; + Context = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of ChoiceDelta. + /// The index of the of the chat choice, relative to the other choices in the same completion. + /// The partial message received for this choice. + /// + /// Field that allows the chat app to store and retrieve data, the structure of such data is dependant on the backend + /// being used. The client must send back the data in this field unchanged in subsequent requests, until the chat app + /// sends a new one. The data in this field can be used to implement stateful services, such as remembering previous + /// conversations or user preferences. + /// + /// + /// Context allows the chat app to receive extra parameters from the client, such as temperature, functions, or + /// customer_info. These parameters are specific to the chat app and not understood by the generic clients. + /// + /// The reason this chat completion completed its generation. + internal ChoiceDelta(long index, ChatMessageDelta delta, BinaryData sessionState, IReadOnlyDictionary context, FinishReason? finishReason) + { + Index = index; + Delta = delta; + SessionState = sessionState; + Context = context; + FinishReason = finishReason; + } + + /// The index of the of the chat choice, relative to the other choices in the same completion. + public long Index { get; } + /// + /// The partial message received for this choice. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + public ChatMessageDelta Delta { get; } + /// + /// Field that allows the chat app to store and retrieve data, the structure of such data is dependant on the backend + /// being used. The client must send back the data in this field unchanged in subsequent requests, until the chat app + /// sends a new one. The data in this field can be used to implement stateful services, such as remembering previous + /// conversations or user preferences. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData SessionState { get; } + /// + /// Context allows the chat app to receive extra parameters from the client, such as temperature, functions, or + /// customer_info. These parameters are specific to the chat app and not understood by the generic clients. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public IReadOnlyDictionary Context { get; } + /// The reason this chat completion completed its generation. + public FinishReason? FinishReason { get; } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/Docs/ChatProtocolClient.xml b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/Docs/ChatProtocolClient.xml new file mode 100644 index 000000000000..d14f7f5d1399 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/Docs/ChatProtocolClient.xml @@ -0,0 +1,211 @@ + + + + + +This sample shows how to call CreateAsync. +"); +AzureKeyCredential credential = new AzureKeyCredential(""); +ChatProtocolClient client = new ChatProtocolClient(endpoint, credential); + +ChatCompletionOptions chatCompletionOptions = new ChatCompletionOptions(new ChatMessage[] +{ + new TextChatMessage(ChatRole.User, "") +}); +Response response = await client.CreateAsync("", chatCompletionOptions); +]]> +This sample shows how to call CreateAsync with all parameters. +"); +AzureKeyCredential credential = new AzureKeyCredential(""); +ChatProtocolClient client = new ChatProtocolClient(endpoint, credential); + +ChatCompletionOptions chatCompletionOptions = new ChatCompletionOptions(new ChatMessage[] +{ + new TextChatMessage(ChatRole.User, "") + { + SessionState = BinaryData.FromObjectAsJson(new object()), + } +}) +{ + SessionState = BinaryData.FromObjectAsJson(new object()), + Context = + { + ["key"] = BinaryData.FromObjectAsJson(new object()) + }, +}; +Response response = await client.CreateAsync("", chatCompletionOptions); +]]> + + + +This sample shows how to call Create. +"); +AzureKeyCredential credential = new AzureKeyCredential(""); +ChatProtocolClient client = new ChatProtocolClient(endpoint, credential); + +ChatCompletionOptions chatCompletionOptions = new ChatCompletionOptions(new ChatMessage[] +{ + new TextChatMessage(ChatRole.User, "") +}); +Response response = client.Create("", chatCompletionOptions); +]]> +This sample shows how to call Create with all parameters. +"); +AzureKeyCredential credential = new AzureKeyCredential(""); +ChatProtocolClient client = new ChatProtocolClient(endpoint, credential); + +ChatCompletionOptions chatCompletionOptions = new ChatCompletionOptions(new ChatMessage[] +{ + new TextChatMessage(ChatRole.User, "") + { + SessionState = BinaryData.FromObjectAsJson(new object()), + } +}) +{ + SessionState = BinaryData.FromObjectAsJson(new object()), + Context = + { + ["key"] = BinaryData.FromObjectAsJson(new object()) + }, +}; +Response response = client.Create("", chatCompletionOptions); +]]> + + + +This sample shows how to call CreateAsync and parse the result. +"); +AzureKeyCredential credential = new AzureKeyCredential(""); +ChatProtocolClient client = new ChatProtocolClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + messages = new object[] + { + new + { + content = "", + kind = "text", + role = "user", + } + }, + stream = false, +}); +Response response = await client.CreateAsync("", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("choices")[0].GetProperty("index").ToString()); +Console.WriteLine(result.GetProperty("choices")[0].GetProperty("message").GetProperty("kind").ToString()); +Console.WriteLine(result.GetProperty("choices")[0].GetProperty("message").GetProperty("role").ToString()); +Console.WriteLine(result.GetProperty("choices")[0].GetProperty("finishReason").ToString()); +]]> +This sample shows how to call CreateAsync with all parameters and request content and parse the result. +"); +AzureKeyCredential credential = new AzureKeyCredential(""); +ChatProtocolClient client = new ChatProtocolClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + messages = new object[] + { + new + { + content = "", + kind = "text", + role = "user", + sessionState = new object(), + } + }, + stream = false, + sessionState = new object(), + context = new + { + key = new object(), + }, +}); +Response response = await client.CreateAsync("", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("choices")[0].GetProperty("index").ToString()); +Console.WriteLine(result.GetProperty("choices")[0].GetProperty("message").GetProperty("kind").ToString()); +Console.WriteLine(result.GetProperty("choices")[0].GetProperty("message").GetProperty("role").ToString()); +Console.WriteLine(result.GetProperty("choices")[0].GetProperty("message").GetProperty("sessionState").ToString()); +Console.WriteLine(result.GetProperty("choices")[0].GetProperty("sessionState").ToString()); +Console.WriteLine(result.GetProperty("choices")[0].GetProperty("context").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("choices")[0].GetProperty("finishReason").ToString()); +]]> + + + +This sample shows how to call Create and parse the result. +"); +AzureKeyCredential credential = new AzureKeyCredential(""); +ChatProtocolClient client = new ChatProtocolClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + messages = new object[] + { + new + { + content = "", + kind = "text", + role = "user", + } + }, + stream = false, +}); +Response response = client.Create("", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("choices")[0].GetProperty("index").ToString()); +Console.WriteLine(result.GetProperty("choices")[0].GetProperty("message").GetProperty("kind").ToString()); +Console.WriteLine(result.GetProperty("choices")[0].GetProperty("message").GetProperty("role").ToString()); +Console.WriteLine(result.GetProperty("choices")[0].GetProperty("finishReason").ToString()); +]]> +This sample shows how to call Create with all parameters and request content and parse the result. +"); +AzureKeyCredential credential = new AzureKeyCredential(""); +ChatProtocolClient client = new ChatProtocolClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + messages = new object[] + { + new + { + content = "", + kind = "text", + role = "user", + sessionState = new object(), + } + }, + stream = false, + sessionState = new object(), + context = new + { + key = new object(), + }, +}); +Response response = client.Create("", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("choices")[0].GetProperty("index").ToString()); +Console.WriteLine(result.GetProperty("choices")[0].GetProperty("message").GetProperty("kind").ToString()); +Console.WriteLine(result.GetProperty("choices")[0].GetProperty("message").GetProperty("role").ToString()); +Console.WriteLine(result.GetProperty("choices")[0].GetProperty("message").GetProperty("sessionState").ToString()); +Console.WriteLine(result.GetProperty("choices")[0].GetProperty("sessionState").ToString()); +Console.WriteLine(result.GetProperty("choices")[0].GetProperty("context").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("choices")[0].GetProperty("finishReason").ToString()); +]]> + + + \ No newline at end of file diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/FinishReason.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/FinishReason.cs new file mode 100644 index 000000000000..f781d205b777 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/FinishReason.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.ChatProtocol +{ + /// Representation of the reason why a chat session has finished processing. + public readonly partial struct FinishReason : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public FinishReason(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string StoppedValue = "stop"; + private const string TokenLimitReachedValue = "length"; + + /// Completion ended normally. + public static FinishReason Stopped { get; } = new FinishReason(StoppedValue); + /// The completion exhausted available tokens before generation could complete. + public static FinishReason TokenLimitReached { get; } = new FinishReason(TokenLimitReachedValue); + /// Determines if two values are the same. + public static bool operator ==(FinishReason left, FinishReason right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(FinishReason left, FinishReason right) => !left.Equals(right); + /// Converts a string to a . + public static implicit operator FinishReason(string value) => new FinishReason(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is FinishReason other && Equals(other); + /// + public bool Equals(FinishReason other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value?.GetHashCode() ?? 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/MessageKind.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/MessageKind.cs new file mode 100644 index 000000000000..a91a58e4af6a --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/MessageKind.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.ChatProtocol +{ + /// Identifies the type of a message. + internal readonly partial struct MessageKind : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public MessageKind(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string TextValue = "text"; + + /// The message context is text. + public static MessageKind Text { get; } = new MessageKind(TextValue); + /// Determines if two values are the same. + public static bool operator ==(MessageKind left, MessageKind right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(MessageKind left, MessageKind right) => !left.Equals(right); + /// Converts a string to a . + public static implicit operator MessageKind(string value) => new MessageKind(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is MessageKind other && Equals(other); + /// + public bool Equals(MessageKind other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value?.GetHashCode() ?? 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/StreamingChatCompletionOptions.Serialization.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/StreamingChatCompletionOptions.Serialization.cs new file mode 100644 index 000000000000..a8a2b9e5dda9 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/StreamingChatCompletionOptions.Serialization.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.ChatProtocol +{ + internal partial class StreamingChatCompletionOptions : IUtf8JsonSerializable + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + { + writer.WriteStartObject(); + writer.WritePropertyName("messages"u8); + writer.WriteStartArray(); + foreach (var item in Messages) + { + writer.WriteObjectValue(item); + } + writer.WriteEndArray(); + writer.WritePropertyName("stream"u8); + writer.WriteBooleanValue(Stream); + if (Optional.IsDefined(SessionState)) + { + writer.WritePropertyName("sessionState"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(SessionState); +#else + using (JsonDocument document = JsonDocument.Parse(SessionState)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + if (Optional.IsCollectionDefined(Context)) + { + writer.WritePropertyName("context"u8); + writer.WriteStartObject(); + foreach (var item in Context) + { + writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + writer.WriteEndObject(); + } + writer.WriteEndObject(); + } + + /// Convert into a Utf8JsonRequestContent. + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this); + return content; + } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/StreamingChatCompletionOptions.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/StreamingChatCompletionOptions.cs new file mode 100644 index 000000000000..ce3281aefba4 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/StreamingChatCompletionOptions.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; +using Azure.Core; + +namespace Azure.AI.ChatProtocol +{ + /// The configuration for a streaming chat completion request. + internal partial class StreamingChatCompletionOptions + { + /// Initializes a new instance of StreamingChatCompletionOptions. + /// The collection of context messages associated with this completion request. + /// is null. + public StreamingChatCompletionOptions(IEnumerable messages) + { + Argument.AssertNotNull(messages, nameof(messages)); + + Messages = messages.ToList(); + Context = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of StreamingChatCompletionOptions. + /// The collection of context messages associated with this completion request. + /// Indicates whether the completion is a streaming or non-streaming completion. + /// + /// Field that allows the chat app to store and retrieve data, the structure of such data is dependant on the backend + /// being used. The client must send back the data in this field unchanged in subsequent requests, until the chat app + /// sends a new one. The data in this field can be used to implement stateful services, such as remembering previous + /// conversations or user preferences. + /// + /// + /// Context allows the chat app to receive extra parameters from the client, such as temperature, functions, or + /// customer_info. These parameters are specific to the chat app and not understood by the generic clients. + /// + internal StreamingChatCompletionOptions(IList messages, bool stream, BinaryData sessionState, IDictionary context) + { + Messages = messages; + Stream = stream; + SessionState = sessionState; + Context = context; + } + + /// + /// The collection of context messages associated with this completion request. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + public IList Messages { get; } + /// Indicates whether the completion is a streaming or non-streaming completion. + public bool Stream { get; } = true; + + /// + /// Field that allows the chat app to store and retrieve data, the structure of such data is dependant on the backend + /// being used. The client must send back the data in this field unchanged in subsequent requests, until the chat app + /// sends a new one. The data in this field can be used to implement stateful services, such as remembering previous + /// conversations or user preferences. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData SessionState { get; set; } + /// + /// Context allows the chat app to receive extra parameters from the client, such as temperature, functions, or + /// customer_info. These parameters are specific to the chat app and not understood by the generic clients. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public IDictionary Context { get; } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/TextChatMessage.Serialization.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/TextChatMessage.Serialization.cs new file mode 100644 index 000000000000..8f2a33c76ab0 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/TextChatMessage.Serialization.cs @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Azure.AI.ChatProtocol +{ + internal partial class TextChatMessage : IUtf8JsonSerializable + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + { + writer.WriteStartObject(); + writer.WritePropertyName("content"u8); + writer.WriteStringValue(Content); + writer.WritePropertyName("kind"u8); + writer.WriteStringValue(Kind.ToString()); + writer.WritePropertyName("role"u8); + writer.WriteStringValue(Role.ToString()); + if (Optional.IsDefined(SessionState)) + { + writer.WritePropertyName("sessionState"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(SessionState); +#else + using (JsonDocument document = JsonDocument.Parse(SessionState)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + writer.WriteEndObject(); + } + + internal static TextChatMessage DeserializeTextChatMessage(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string content = default; + MessageKind kind = default; + ChatRole role = default; + Optional sessionState = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("content"u8)) + { + content = property.Value.GetString(); + continue; + } + if (property.NameEquals("kind"u8)) + { + kind = new MessageKind(property.Value.GetString()); + continue; + } + if (property.NameEquals("role"u8)) + { + role = new ChatRole(property.Value.GetString()); + continue; + } + if (property.NameEquals("sessionState"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + sessionState = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + } + return new TextChatMessage(kind, role, sessionState.Value, content); + } + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new TextChatMessage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeTextChatMessage(document.RootElement); + } + + /// Convert into a Utf8JsonRequestContent. + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this); + return content; + } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/TextChatMessage.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/TextChatMessage.cs new file mode 100644 index 000000000000..eb402a426c75 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/TextChatMessage.cs @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; + +namespace Azure.AI.ChatProtocol +{ + /// A single, role-attributed text message within a chat completion interaction. + internal partial class TextChatMessage : ChatMessage + { + /// Initializes a new instance of TextChatMessage. + /// The role associated with the message. + /// The text associated with the message. + /// is null. + public TextChatMessage(ChatRole role, string content) : base(role) + { + Argument.AssertNotNull(content, nameof(content)); + + Kind = MessageKind.Text; + Content = content; + } + + /// Initializes a new instance of TextChatMessage. + /// The type of the message. If not specified, the message is assumed to be text. + /// The role associated with the message. + /// + /// Field that allows the chat app to store and retrieve data, the structure of such data is dependant on the backend + /// being used. The client must send back the data in this field unchanged in subsequent requests, until the chat app + /// sends a new one. The data in this field can be used to implement stateful services, such as remembering previous + /// conversations or user preferences. + /// + /// The text associated with the message. + internal TextChatMessage(MessageKind kind, ChatRole role, BinaryData sessionState, string content) : base(kind, role, sessionState) + { + Content = content; + } + + /// The text associated with the message. + public string Content { get; set; } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/TextChatMessageDelta.Serialization.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/TextChatMessageDelta.Serialization.cs new file mode 100644 index 000000000000..b2a2f3522c52 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/TextChatMessageDelta.Serialization.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Azure.AI.ChatProtocol +{ + internal partial class TextChatMessageDelta + { + internal static TextChatMessageDelta DeserializeTextChatMessageDelta(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Optional content = default; + MessageKind kind = default; + Optional role = default; + Optional sessionState = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("content"u8)) + { + content = property.Value.GetString(); + continue; + } + if (property.NameEquals("kind"u8)) + { + kind = new MessageKind(property.Value.GetString()); + continue; + } + if (property.NameEquals("role"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + role = new ChatRole(property.Value.GetString()); + continue; + } + if (property.NameEquals("sessionState"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + sessionState = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + } + return new TextChatMessageDelta(kind, Optional.ToNullable(role), sessionState.Value, content.Value); + } + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new TextChatMessageDelta FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeTextChatMessageDelta(document.RootElement); + } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/TextChatMessageDelta.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/TextChatMessageDelta.cs new file mode 100644 index 000000000000..1cdab990dc3d --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/TextChatMessageDelta.cs @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; + +namespace Azure.AI.ChatProtocol +{ + /// The representation of a delta text message received in a streaming completion. + internal partial class TextChatMessageDelta : ChatMessageDelta + { + /// Initializes a new instance of TextChatMessageDelta. + internal TextChatMessageDelta() + { + Kind = MessageKind.Text; + } + + /// Initializes a new instance of TextChatMessageDelta. + /// The type of the message. If not specified, the message is assumed to be text. + /// The role associated with the message. + /// + /// Field that allows the chat app to store and retrieve data, the structure of such data is dependant on the backend + /// being used. The client must send back the data in this field unchanged in subsequent requests, until the chat app + /// sends a new one. The data in this field can be used to implement stateful services, such as remembering previous + /// conversations or user preferences. + /// + /// An incremental part of the text associated with the message. + internal TextChatMessageDelta(MessageKind kind, ChatRole? role, BinaryData sessionState, string content) : base(kind, role, sessionState) + { + Content = content; + } + + /// An incremental part of the text associated with the message. + public string Content { get; } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/UnknownChatMessage.Serialization.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/UnknownChatMessage.Serialization.cs new file mode 100644 index 000000000000..7aa03410c6ea --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/UnknownChatMessage.Serialization.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Azure.AI.ChatProtocol +{ + internal partial class UnknownChatMessage + { + internal static UnknownChatMessage DeserializeUnknownChatMessage(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + MessageKind kind = "Unknown"; + ChatRole role = default; + Optional sessionState = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("kind"u8)) + { + kind = new MessageKind(property.Value.GetString()); + continue; + } + if (property.NameEquals("role"u8)) + { + role = new ChatRole(property.Value.GetString()); + continue; + } + if (property.NameEquals("sessionState"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + sessionState = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + } + return new UnknownChatMessage(kind, role, sessionState.Value); + } + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownChatMessage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUnknownChatMessage(document.RootElement); + } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/UnknownChatMessage.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/UnknownChatMessage.cs new file mode 100644 index 000000000000..0b14839c0757 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/UnknownChatMessage.cs @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; + +namespace Azure.AI.ChatProtocol +{ + /// Unknown version of ChatMessage. + internal partial class UnknownChatMessage : ChatMessage + { + /// Initializes a new instance of UnknownChatMessage. + /// The role associated with the message. + internal UnknownChatMessage(ChatRole role) : base(role) + { + } + + /// Initializes a new instance of UnknownChatMessage. + /// The type of the message. If not specified, the message is assumed to be text. + /// The role associated with the message. + /// + /// Field that allows the chat app to store and retrieve data, the structure of such data is dependant on the backend + /// being used. The client must send back the data in this field unchanged in subsequent requests, until the chat app + /// sends a new one. The data in this field can be used to implement stateful services, such as remembering previous + /// conversations or user preferences. + /// + internal UnknownChatMessage(MessageKind kind, ChatRole role, BinaryData sessionState) : base(kind, role, sessionState) + { + } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/UnknownChatMessageDelta.Serialization.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/UnknownChatMessageDelta.Serialization.cs new file mode 100644 index 000000000000..eaf6b6c193e2 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/UnknownChatMessageDelta.Serialization.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Azure.AI.ChatProtocol +{ + internal partial class UnknownChatMessageDelta + { + internal static UnknownChatMessageDelta DeserializeUnknownChatMessageDelta(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + MessageKind kind = "Unknown"; + Optional role = default; + Optional sessionState = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("kind"u8)) + { + kind = new MessageKind(property.Value.GetString()); + continue; + } + if (property.NameEquals("role"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + role = new ChatRole(property.Value.GetString()); + continue; + } + if (property.NameEquals("sessionState"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + sessionState = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + } + return new UnknownChatMessageDelta(kind, Optional.ToNullable(role), sessionState.Value); + } + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownChatMessageDelta FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUnknownChatMessageDelta(document.RootElement); + } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/UnknownChatMessageDelta.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/UnknownChatMessageDelta.cs new file mode 100644 index 000000000000..82f7dd784cee --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Generated/UnknownChatMessageDelta.cs @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; + +namespace Azure.AI.ChatProtocol +{ + /// Unknown version of ChatMessageDelta. + internal partial class UnknownChatMessageDelta : ChatMessageDelta + { + /// Initializes a new instance of UnknownChatMessageDelta. + internal UnknownChatMessageDelta() + { + } + + /// Initializes a new instance of UnknownChatMessageDelta. + /// The type of the message. If not specified, the message is assumed to be text. + /// The role associated with the message. + /// + /// Field that allows the chat app to store and retrieve data, the structure of such data is dependant on the backend + /// being used. The client must send back the data in this field unchanged in subsequent requests, until the chat app + /// sends a new one. The data in this field can be used to implement stateful services, such as remembering previous + /// conversations or user preferences. + /// + internal UnknownChatMessageDelta(MessageKind kind, ChatRole? role, BinaryData sessionState) : base(kind, role, sessionState) + { + } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/src/Properties/AssemblyInfo.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Properties/AssemblyInfo.cs new file mode 100644 index 000000000000..38bdd7456bc9 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/src/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Azure.AI.ChatProtocol.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")] + +// Replace Microsoft.Test with the correct resource provider namepace for your service and uncomment. +// See https://docs.microsoft.com/en-us/azure/azure-resource-manager/management/azure-services-resource-providers +// for the list of possible values. +[assembly: Azure.Core.AzureResourceProviderNamespace("Microsoft.Template")] diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/tests/Azure.AI.ChatProtocol.Tests.csproj b/sdk/machinelearning/Azure.AI.ChatProtocol/tests/Azure.AI.ChatProtocol.Tests.csproj new file mode 100644 index 000000000000..252dd1b57bdf --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/tests/Azure.AI.ChatProtocol.Tests.csproj @@ -0,0 +1,29 @@ + + + $(RequiredTargetFrameworks) + + + $(NoWarn);CS1591 + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/tests/Generated/Samples/Samples_ChatProtocolClient.cs b/sdk/machinelearning/Azure.AI.ChatProtocol/tests/Generated/Samples/Samples_ChatProtocolClient.cs new file mode 100644 index 000000000000..ab20ee6bf832 --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/tests/Generated/Samples/Samples_ChatProtocolClient.cs @@ -0,0 +1,239 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using System.Threading.Tasks; +using Azure; +using Azure.AI.ChatProtocol; +using Azure.Core; +using Azure.Identity; +using NUnit.Framework; + +namespace Azure.AI.ChatProtocol.Samples +{ + public partial class Samples_ChatProtocolClient + { + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Create_ShortVersion() + { + Uri endpoint = new Uri(""); + AzureKeyCredential credential = new AzureKeyCredential(""); + ChatProtocolClient client = new ChatProtocolClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + messages = new object[] + { +new +{ +content = "", +kind = "text", +role = "user", +} + }, + stream = false, + }); + Response response = client.Create("", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("choices")[0].GetProperty("index").ToString()); + Console.WriteLine(result.GetProperty("choices")[0].GetProperty("message").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("choices")[0].GetProperty("message").GetProperty("role").ToString()); + Console.WriteLine(result.GetProperty("choices")[0].GetProperty("finishReason").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Create_ShortVersion_Async() + { + Uri endpoint = new Uri(""); + AzureKeyCredential credential = new AzureKeyCredential(""); + ChatProtocolClient client = new ChatProtocolClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + messages = new object[] + { +new +{ +content = "", +kind = "text", +role = "user", +} + }, + stream = false, + }); + Response response = await client.CreateAsync("", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("choices")[0].GetProperty("index").ToString()); + Console.WriteLine(result.GetProperty("choices")[0].GetProperty("message").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("choices")[0].GetProperty("message").GetProperty("role").ToString()); + Console.WriteLine(result.GetProperty("choices")[0].GetProperty("finishReason").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Create_ShortVersion_Convenience() + { + Uri endpoint = new Uri(""); + AzureKeyCredential credential = new AzureKeyCredential(""); + ChatProtocolClient client = new ChatProtocolClient(endpoint, credential); + + ChatCompletionOptions chatCompletionOptions = new ChatCompletionOptions(new ChatMessage[] + { +new TextChatMessage(ChatRole.User, "") + }); + Response response = client.Create("", chatCompletionOptions); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Create_ShortVersion_Convenience_Async() + { + Uri endpoint = new Uri(""); + AzureKeyCredential credential = new AzureKeyCredential(""); + ChatProtocolClient client = new ChatProtocolClient(endpoint, credential); + + ChatCompletionOptions chatCompletionOptions = new ChatCompletionOptions(new ChatMessage[] + { +new TextChatMessage(ChatRole.User, "") + }); + Response response = await client.CreateAsync("", chatCompletionOptions); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Create_AllParameters() + { + Uri endpoint = new Uri(""); + AzureKeyCredential credential = new AzureKeyCredential(""); + ChatProtocolClient client = new ChatProtocolClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + messages = new object[] + { +new +{ +content = "", +kind = "text", +role = "user", +sessionState = new object(), +} + }, + stream = false, + sessionState = new object(), + context = new + { + key = new object(), + }, + }); + Response response = client.Create("", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("choices")[0].GetProperty("index").ToString()); + Console.WriteLine(result.GetProperty("choices")[0].GetProperty("message").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("choices")[0].GetProperty("message").GetProperty("role").ToString()); + Console.WriteLine(result.GetProperty("choices")[0].GetProperty("message").GetProperty("sessionState").ToString()); + Console.WriteLine(result.GetProperty("choices")[0].GetProperty("sessionState").ToString()); + Console.WriteLine(result.GetProperty("choices")[0].GetProperty("context").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("choices")[0].GetProperty("finishReason").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Create_AllParameters_Async() + { + Uri endpoint = new Uri(""); + AzureKeyCredential credential = new AzureKeyCredential(""); + ChatProtocolClient client = new ChatProtocolClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + messages = new object[] + { +new +{ +content = "", +kind = "text", +role = "user", +sessionState = new object(), +} + }, + stream = false, + sessionState = new object(), + context = new + { + key = new object(), + }, + }); + Response response = await client.CreateAsync("", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("choices")[0].GetProperty("index").ToString()); + Console.WriteLine(result.GetProperty("choices")[0].GetProperty("message").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("choices")[0].GetProperty("message").GetProperty("role").ToString()); + Console.WriteLine(result.GetProperty("choices")[0].GetProperty("message").GetProperty("sessionState").ToString()); + Console.WriteLine(result.GetProperty("choices")[0].GetProperty("sessionState").ToString()); + Console.WriteLine(result.GetProperty("choices")[0].GetProperty("context").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("choices")[0].GetProperty("finishReason").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Create_AllParameters_Convenience() + { + Uri endpoint = new Uri(""); + AzureKeyCredential credential = new AzureKeyCredential(""); + ChatProtocolClient client = new ChatProtocolClient(endpoint, credential); + + ChatCompletionOptions chatCompletionOptions = new ChatCompletionOptions(new ChatMessage[] + { +new TextChatMessage(ChatRole.User, "") +{ +SessionState = BinaryData.FromObjectAsJson(new object()), +} + }) + { + SessionState = BinaryData.FromObjectAsJson(new object()), + Context = +{ +["key"] = BinaryData.FromObjectAsJson(new object()) +}, + }; + Response response = client.Create("", chatCompletionOptions); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Create_AllParameters_Convenience_Async() + { + Uri endpoint = new Uri(""); + AzureKeyCredential credential = new AzureKeyCredential(""); + ChatProtocolClient client = new ChatProtocolClient(endpoint, credential); + + ChatCompletionOptions chatCompletionOptions = new ChatCompletionOptions(new ChatMessage[] + { +new TextChatMessage(ChatRole.User, "") +{ +SessionState = BinaryData.FromObjectAsJson(new object()), +} + }) + { + SessionState = BinaryData.FromObjectAsJson(new object()), + Context = +{ +["key"] = BinaryData.FromObjectAsJson(new object()) +}, + }; + Response response = await client.CreateAsync("", chatCompletionOptions); + } + } +} diff --git a/sdk/machinelearning/Azure.AI.ChatProtocol/tsp-location.yaml b/sdk/machinelearning/Azure.AI.ChatProtocol/tsp-location.yaml new file mode 100644 index 000000000000..edd8e9022aaf --- /dev/null +++ b/sdk/machinelearning/Azure.AI.ChatProtocol/tsp-location.yaml @@ -0,0 +1,5 @@ +additionalDirectories: [] +commit: b9fc96cd4464a6c097972f4dbf8c9b5a5b4ef558 +directory: specification/machinelearning/Azure.AI.ChatProtocol +repo: Azure/azure-rest-api-specs + diff --git a/sdk/machinelearning/ci.yml b/sdk/machinelearning/ci.yml new file mode 100644 index 000000000000..01e1cffcc6d3 --- /dev/null +++ b/sdk/machinelearning/ci.yml @@ -0,0 +1,35 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. + +trigger: + branches: + include: + - main + - hotfix/* + - release/* + paths: + include: + - sdk/machinelearning + - sdk/machinelearning/ci.yml + - sdk/machinelearning/Azure.AI.ChatProtocol + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/machinelearning + - sdk/machinelearning/ci.yml + - sdk/machinelearning/Azure.AI.ChatProtocol + +extends: + template: /eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: machinelearning + ArtifactName: packages + Artifacts: + - name: Azure.AI.ChatProtocol + safeName: AzureAIChatProtocol