microsoft/teams.net

Public

mirrored fromhttps://github.com/microsoft/teams.netAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
release/v2

Branches

Tags

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

Clone

HTTPS

Download ZIP

Libraries/Microsoft.Teams.AI/Messages/UserMessage.cs

104lines · modecode

1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT License.
3
4using System.Text.Json;
5using System.Text.Json.Serialization;
6
7using Microsoft.Teams.Common;
8
9namespace Microsoft.Teams.AI.Messages;
10
11public class UserMessage(object? content) : UserMessage<object?>(content)
12{
13 public static UserMessage<string> Text(string content) => new(content);
14 public static UserMessage<IEnumerable<IContent>> Text(IEnumerable<IContent> content) => new(content);
15 public static UserMessage<Stream> Media(Stream content) => new(content);
16}
17
18public class UserMessage<T> : IMessage
19{
20 [JsonPropertyName("role")]
21 [JsonPropertyOrder(0)]
22 public Role Role => Role.User;
23
24 [JsonPropertyName("content")]
25 [JsonPropertyOrder(1)]
26 public T Content { get; set; }
27
28 [JsonConstructor]
29 public UserMessage(T content)
30 {
31 Content = content;
32 }
33
34 public string GetText()
35 {
36 if (Content is IEnumerable<IContent> asEnum)
37 {
38 return string.Join("\n", asEnum.Select(v => v.ToString()));
39 }
40
41 if (Content is string asString)
42 {
43 return asString;
44 }
45
46 return Content?.ToString() ?? throw new InvalidCastException();
47 }
48
49 public override string ToString()
50 {
51 return JsonSerializer.Serialize(this, new JsonSerializerOptions()
52 {
53 WriteIndented = true,
54 DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
55 });
56 }
57}
58
59[JsonConverter(typeof(JsonConverter<ContentType>))]
60public class ContentType(string value) : StringEnum(value)
61{
62 public static readonly ContentType Text = new("text");
63 public bool IsText => Text.Equals(Value);
64
65 public static readonly ContentType ImageUrl = new("image_url");
66 public bool IsImageUrl => ImageUrl.Equals(Value);
67}
68
69/// <summary>
70/// represents some message content
71/// </summary>
72public interface IContent
73{
74 /// <summary>
75 /// the type of content
76 /// </summary>
77 public ContentType Type { get; }
78}
79
80public class TextContent : IContent
81{
82 [JsonPropertyName("type")]
83 [JsonPropertyOrder(0)]
84 public ContentType Type => ContentType.Text;
85
86 [JsonPropertyName("text")]
87 [JsonPropertyOrder(1)]
88 public required string Text { get; set; }
89
90 public override string ToString() => Text;
91}
92
93public class ImageContent : IContent
94{
95 [JsonPropertyName("type")]
96 [JsonPropertyOrder(0)]
97 public ContentType Type => ContentType.ImageUrl;
98
99 [JsonPropertyName("image_url")]
100 [JsonPropertyOrder(1)]
101 public required string ImageUrl { get; set; }
102
103 public override string ToString() => ImageUrl;
104}