openai/openai-dotnet

Public

mirrored from https://github.com/openai/openai-dotnetAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
mailinhphan/clientOptions

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

OpenAI/src/Generated/Models/Chat/ChatCompletion.Serialization.cs

334lines · modecode

1// <auto-generated/>
2
3#nullable disable
4
5using System;
6using System.ClientModel;
7using System.ClientModel.Primitives;
8using System.Collections.Generic;
9using System.Diagnostics.CodeAnalysis;
10using System.Text;
11using System.Text.Json;
12using OpenAI;
13
14namespace OpenAI.Chat
15{
16 public partial class ChatCompletion : IJsonModel<ChatCompletion>
17 {
18 internal ChatCompletion() : this(null, null, default, null, default, null, null, null, default)
19 {
20 }
21
22 [Experimental("OPENAI001")]
23 protected virtual ChatCompletion PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options)
24 {
25 string format = options.Format == "W" ? ((IPersistableModel<ChatCompletion>)this).GetFormatFromOptions(options) : options.Format;
26 switch (format)
27 {
28 case "J":
29 using (JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions))
30 {
31 return DeserializeChatCompletion(document.RootElement, data, options);
32 }
33 default:
34 throw new FormatException($"The model {nameof(ChatCompletion)} does not support reading '{options.Format}' format.");
35 }
36 }
37
38 [Experimental("OPENAI001")]
39 protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options)
40 {
41 string format = options.Format == "W" ? ((IPersistableModel<ChatCompletion>)this).GetFormatFromOptions(options) : options.Format;
42 switch (format)
43 {
44 case "J":
45 return ModelReaderWriter.Write(this, options, OpenAIContext.Default);
46 default:
47 throw new FormatException($"The model {nameof(ChatCompletion)} does not support writing '{options.Format}' format.");
48 }
49 }
50
51 BinaryData IPersistableModel<ChatCompletion>.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options);
52
53 ChatCompletion IPersistableModel<ChatCompletion>.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options);
54
55 string IPersistableModel<ChatCompletion>.GetFormatFromOptions(ModelReaderWriterOptions options) => "J";
56
57 [Experimental("OPENAI001")]
58 public static explicit operator ChatCompletion(ClientResult result)
59 {
60 PipelineResponse response = result.GetRawResponse();
61 BinaryData data = response.Content;
62 using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions);
63 return DeserializeChatCompletion(document.RootElement, data, ModelSerializationExtensions.WireOptions);
64 }
65
66 void IJsonModel<ChatCompletion>.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options)
67 {
68#pragma warning disable SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
69 if (Patch.Contains("$"u8))
70 {
71 writer.WriteRawValue(Patch.GetJson("$"u8));
72 return;
73 }
74#pragma warning restore SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
75
76 writer.WriteStartObject();
77 JsonModelWriteCore(writer, options);
78 writer.WriteEndObject();
79 }
80
81 [Experimental("OPENAI001")]
82 protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options)
83 {
84 string format = options.Format == "W" ? ((IPersistableModel<ChatCompletion>)this).GetFormatFromOptions(options) : options.Format;
85 if (format != "J")
86 {
87 throw new FormatException($"The model {nameof(ChatCompletion)} does not support writing '{format}' format.");
88 }
89#pragma warning disable SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
90 if (!Patch.Contains("$.id"u8))
91 {
92 writer.WritePropertyName("id"u8);
93 writer.WriteStringValue(Id);
94 }
95 if (Patch.Contains("$.choices"u8))
96 {
97 if (!Patch.IsRemoved("$.choices"u8))
98 {
99 writer.WritePropertyName("choices"u8);
100 writer.WriteRawValue(Patch.GetJson("$.choices"u8));
101 }
102 }
103 else
104 {
105 writer.WritePropertyName("choices"u8);
106 writer.WriteStartArray();
107 for (int i = 0; i < Choices.Count; i++)
108 {
109 if (Choices[i].Patch.IsRemoved("$"u8))
110 {
111 continue;
112 }
113 writer.WriteObjectValue(Choices[i], options);
114 }
115 Patch.WriteTo(writer, "$.choices"u8);
116 writer.WriteEndArray();
117 }
118 if (!Patch.Contains("$.created"u8))
119 {
120 writer.WritePropertyName("created"u8);
121 writer.WriteNumberValue(CreatedAt, "U");
122 }
123 if (!Patch.Contains("$.model"u8))
124 {
125 writer.WritePropertyName("model"u8);
126 writer.WriteStringValue(Model);
127 }
128 if (Optional.IsDefined(ServiceTier) && !Patch.Contains("$.service_tier"u8))
129 {
130 writer.WritePropertyName("service_tier"u8);
131 writer.WriteStringValue(ServiceTier.Value.ToString());
132 }
133 if (Optional.IsDefined(SystemFingerprint) && !Patch.Contains("$.system_fingerprint"u8))
134 {
135 writer.WritePropertyName("system_fingerprint"u8);
136 writer.WriteStringValue(SystemFingerprint);
137 }
138 if (!Patch.Contains("$.object"u8))
139 {
140 writer.WritePropertyName("object"u8);
141 writer.WriteStringValue(Object);
142 }
143 if (Optional.IsDefined(Usage) && !Patch.Contains("$.usage"u8))
144 {
145 writer.WritePropertyName("usage"u8);
146 writer.WriteObjectValue(Usage, options);
147 }
148
149 Patch.WriteTo(writer);
150#pragma warning restore SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
151 }
152
153 ChatCompletion IJsonModel<ChatCompletion>.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options);
154
155 [Experimental("OPENAI001")]
156 protected virtual ChatCompletion JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options)
157 {
158 string format = options.Format == "W" ? ((IPersistableModel<ChatCompletion>)this).GetFormatFromOptions(options) : options.Format;
159 if (format != "J")
160 {
161 throw new FormatException($"The model {nameof(ChatCompletion)} does not support reading '{format}' format.");
162 }
163 using JsonDocument document = JsonDocument.ParseValue(ref reader);
164 return DeserializeChatCompletion(document.RootElement, null, options);
165 }
166
167 internal static ChatCompletion DeserializeChatCompletion(JsonElement element, BinaryData data, ModelReaderWriterOptions options)
168 {
169 if (element.ValueKind == JsonValueKind.Null)
170 {
171 return null;
172 }
173 string id = default;
174 IReadOnlyList<InternalCreateChatCompletionResponseChoice> choices = default;
175 DateTimeOffset createdAt = default;
176 string model = default;
177 ChatServiceTier? serviceTier = default;
178 string systemFingerprint = default;
179 string @object = default;
180 ChatTokenUsage usage = default;
181#pragma warning disable SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
182 JsonPatch patch = new JsonPatch(data is null ? ReadOnlyMemory<byte>.Empty : data.ToMemory());
183#pragma warning restore SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
184 foreach (var prop in element.EnumerateObject())
185 {
186 if (prop.NameEquals("id"u8))
187 {
188 id = prop.Value.GetString();
189 continue;
190 }
191 if (prop.NameEquals("choices"u8))
192 {
193 List<InternalCreateChatCompletionResponseChoice> array = new List<InternalCreateChatCompletionResponseChoice>();
194 foreach (var item in prop.Value.EnumerateArray())
195 {
196 array.Add(InternalCreateChatCompletionResponseChoice.DeserializeInternalCreateChatCompletionResponseChoice(item, item.GetUtf8Bytes(), options));
197 }
198 choices = array;
199 continue;
200 }
201 if (prop.NameEquals("created"u8))
202 {
203 createdAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64());
204 continue;
205 }
206 if (prop.NameEquals("model"u8))
207 {
208 model = prop.Value.GetString();
209 continue;
210 }
211 if (prop.NameEquals("service_tier"u8))
212 {
213 if (prop.Value.ValueKind == JsonValueKind.Null)
214 {
215 continue;
216 }
217 serviceTier = new ChatServiceTier(prop.Value.GetString());
218 continue;
219 }
220 if (prop.NameEquals("system_fingerprint"u8))
221 {
222 systemFingerprint = prop.Value.GetString();
223 continue;
224 }
225 if (prop.NameEquals("object"u8))
226 {
227 @object = prop.Value.GetString();
228 continue;
229 }
230 if (prop.NameEquals("usage"u8))
231 {
232 if (prop.Value.ValueKind == JsonValueKind.Null)
233 {
234 continue;
235 }
236 usage = ChatTokenUsage.DeserializeChatTokenUsage(prop.Value, prop.Value.GetUtf8Bytes(), options);
237 continue;
238 }
239 patch.Set([.. "$."u8, .. Encoding.UTF8.GetBytes(prop.Name)], prop.Value.GetUtf8Bytes());
240 }
241 return new ChatCompletion(
242 id,
243 choices,
244 createdAt,
245 model,
246 serviceTier,
247 systemFingerprint,
248 @object,
249 usage,
250 patch);
251 }
252
253#pragma warning disable SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
254 private bool PropagateGet(ReadOnlySpan<byte> jsonPath, out JsonPatch.EncodedValue value)
255 {
256 ReadOnlySpan<byte> local = jsonPath.SliceToStartOfPropertyName();
257 value = default;
258
259 if (local.StartsWith("usage"u8))
260 {
261 return Usage.Patch.TryGetEncodedValue([.. "$"u8, .. local.Slice("usage"u8.Length)], out value);
262 }
263 if (local.StartsWith("choices"u8))
264 {
265 int propertyLength = "choices"u8.Length;
266 ReadOnlySpan<byte> currentSlice = local.Slice(propertyLength);
267 if (currentSlice.IsEmpty)
268 {
269 return TryResolveChoicesArray(out value);
270 }
271 if (!currentSlice.TryGetIndex(out int index, out int bytesConsumed))
272 {
273 return false;
274 }
275 return Choices[index].Patch.TryGetEncodedValue([.. "$"u8, .. currentSlice.Slice(bytesConsumed)], out value);
276 }
277 return false;
278 }
279#pragma warning restore SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
280
281#pragma warning disable SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
282 private bool PropagateSet(ReadOnlySpan<byte> jsonPath, JsonPatch.EncodedValue value)
283 {
284 ReadOnlySpan<byte> local = jsonPath.SliceToStartOfPropertyName();
285
286 if (local.StartsWith("usage"u8))
287 {
288 Usage.Patch.Set([.. "$"u8, .. local.Slice("usage"u8.Length)], value);
289 return true;
290 }
291 if (local.StartsWith("choices"u8))
292 {
293 int propertyLength = "choices"u8.Length;
294 ReadOnlySpan<byte> currentSlice = local.Slice(propertyLength);
295 if (!currentSlice.TryGetIndex(out int index, out int bytesConsumed))
296 {
297 return false;
298 }
299 Choices[index].Patch.Set([.. "$"u8, .. currentSlice.Slice(bytesConsumed)], value);
300 return true;
301 }
302 return false;
303 }
304#pragma warning restore SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
305
306#pragma warning disable SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
307 private bool TryResolveChoicesArray(out JsonPatch.EncodedValue value)
308 {
309 value = default;
310 BinaryData data = ModelReaderWriter.Write(ActiveChoices(), ModelReaderWriterOptions.Json, OpenAIContext.Default);
311 JsonPatch tempPatch = new JsonPatch();
312 tempPatch.Set("$"u8, data.ToMemory().Span);
313 return tempPatch.TryGetEncodedValue("$"u8, out value);
314 }
315#pragma warning restore SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
316
317#pragma warning disable SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
318 private IEnumerable<InternalCreateChatCompletionResponseChoice> ActiveChoices()
319 {
320 if (!Optional.IsCollectionDefined(Choices))
321 {
322 yield break;
323 }
324 for (int i = 0; i < Choices.Count; i++)
325 {
326 if (!Choices[i].Patch.IsRemoved("$"u8))
327 {
328 yield return Choices[i];
329 }
330 }
331 }
332#pragma warning restore SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
333 }
334}
335