├── .gitattributes
├── .gitignore
├── DeepSeek.NET.sln
├── DeepSeek.NET
├── .vscode
│ └── settings.json
├── Classes
│ ├── ChatRequest
│ │ └── ChatRequest.cs
│ ├── ChatResponse
│ │ ├── ChatResponse.cs
│ │ ├── Choice.cs
│ │ ├── Content.cs
│ │ ├── Logprobs.cs
│ │ ├── TopLogprobs.cs
│ │ └── Usage.cs
│ ├── Message.cs
│ └── ModelResponse
│ │ ├── Model.cs
│ │ └── ModelResponse.cs
├── Constant.cs
├── DeepSeek.NET.csproj
└── DeepSeekClient.cs
├── DeepSeek.NETTests
├── DeepSeek.NETTests.csproj
└── DeepSeekClientTests.cs
├── LICENSE.txt
└── README.md
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Oo]ut/
33 | [Ll]og/
34 | [Ll]ogs/
35 |
36 | # Visual Studio 2015/2017 cache/options directory
37 | .vs/
38 | # Uncomment if you have tasks that create the project's static files in wwwroot
39 | #wwwroot/
40 |
41 | # Visual Studio 2017 auto generated files
42 | Generated\ Files/
43 |
44 | # MSTest test Results
45 | [Tt]est[Rr]esult*/
46 | [Bb]uild[Ll]og.*
47 |
48 | # NUnit
49 | *.VisualState.xml
50 | TestResult.xml
51 | nunit-*.xml
52 |
53 | # Build Results of an ATL Project
54 | [Dd]ebugPS/
55 | [Rr]eleasePS/
56 | dlldata.c
57 |
58 | # Benchmark Results
59 | BenchmarkDotNet.Artifacts/
60 |
61 | # .NET Core
62 | project.lock.json
63 | project.fragment.lock.json
64 | artifacts/
65 |
66 | # ASP.NET Scaffolding
67 | ScaffoldingReadMe.txt
68 |
69 | # StyleCop
70 | StyleCopReport.xml
71 |
72 | # Files built by Visual Studio
73 | *_i.c
74 | *_p.c
75 | *_h.h
76 | *.ilk
77 | *.meta
78 | *.obj
79 | *.iobj
80 | *.pch
81 | *.pdb
82 | *.ipdb
83 | *.pgc
84 | *.pgd
85 | *.rsp
86 | *.sbr
87 | *.tlb
88 | *.tli
89 | *.tlh
90 | *.tmp
91 | *.tmp_proj
92 | *_wpftmp.csproj
93 | *.log
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Coverlet is a free, cross platform Code Coverage Tool
146 | coverage*.json
147 | coverage*.xml
148 | coverage*.info
149 |
150 | # Visual Studio code coverage results
151 | *.coverage
152 | *.coveragexml
153 |
154 | # NCrunch
155 | _NCrunch_*
156 | .*crunch*.local.xml
157 | nCrunchTemp_*
158 |
159 | # MightyMoose
160 | *.mm.*
161 | AutoTest.Net/
162 |
163 | # Web workbench (sass)
164 | .sass-cache/
165 |
166 | # Installshield output folder
167 | [Ee]xpress/
168 |
169 | # DocProject is a documentation generator add-in
170 | DocProject/buildhelp/
171 | DocProject/Help/*.HxT
172 | DocProject/Help/*.HxC
173 | DocProject/Help/*.hhc
174 | DocProject/Help/*.hhk
175 | DocProject/Help/*.hhp
176 | DocProject/Help/Html2
177 | DocProject/Help/html
178 |
179 | # Click-Once directory
180 | publish/
181 |
182 | # Publish Web Output
183 | *.[Pp]ublish.xml
184 | *.azurePubxml
185 | # Note: Comment the next line if you want to checkin your web deploy settings,
186 | # but database connection strings (with potential passwords) will be unencrypted
187 | *.pubxml
188 | *.publishproj
189 |
190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
191 | # checkin your Azure Web App publish settings, but sensitive information contained
192 | # in these scripts will be unencrypted
193 | PublishScripts/
194 |
195 | # NuGet Packages
196 | *.nupkg
197 | # NuGet Symbol Packages
198 | *.snupkg
199 | # The packages folder can be ignored because of Package Restore
200 | **/[Pp]ackages/*
201 | # except build/, which is used as an MSBuild target.
202 | !**/[Pp]ackages/build/
203 | # Uncomment if necessary however generally it will be regenerated when needed
204 | #!**/[Pp]ackages/repositories.config
205 | # NuGet v3's project.json files produces more ignorable files
206 | *.nuget.props
207 | *.nuget.targets
208 |
209 | # Microsoft Azure Build Output
210 | csx/
211 | *.build.csdef
212 |
213 | # Microsoft Azure Emulator
214 | ecf/
215 | rcf/
216 |
217 | # Windows Store app package directories and files
218 | AppPackages/
219 | BundleArtifacts/
220 | Package.StoreAssociation.xml
221 | _pkginfo.txt
222 | *.appx
223 | *.appxbundle
224 | *.appxupload
225 |
226 | # Visual Studio cache files
227 | # files ending in .cache can be ignored
228 | *.[Cc]ache
229 | # but keep track of directories ending in .cache
230 | !?*.[Cc]ache/
231 |
232 | # Others
233 | ClientBin/
234 | ~$*
235 | *~
236 | *.dbmdl
237 | *.dbproj.schemaview
238 | *.jfm
239 | *.pfx
240 | *.publishsettings
241 | orleans.codegen.cs
242 |
243 | # Including strong name files can present a security risk
244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
245 | #*.snk
246 |
247 | # Since there are multiple workflows, uncomment next line to ignore bower_components
248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
249 | #bower_components/
250 |
251 | # RIA/Silverlight projects
252 | Generated_Code/
253 |
254 | # Backup & report files from converting an old project file
255 | # to a newer Visual Studio version. Backup files are not needed,
256 | # because we have git ;-)
257 | _UpgradeReport_Files/
258 | Backup*/
259 | UpgradeLog*.XML
260 | UpgradeLog*.htm
261 | ServiceFabricBackup/
262 | *.rptproj.bak
263 |
264 | # SQL Server files
265 | *.mdf
266 | *.ldf
267 | *.ndf
268 |
269 | # Business Intelligence projects
270 | *.rdl.data
271 | *.bim.layout
272 | *.bim_*.settings
273 | *.rptproj.rsuser
274 | *- [Bb]ackup.rdl
275 | *- [Bb]ackup ([0-9]).rdl
276 | *- [Bb]ackup ([0-9][0-9]).rdl
277 |
278 | # Microsoft Fakes
279 | FakesAssemblies/
280 |
281 | # GhostDoc plugin setting file
282 | *.GhostDoc.xml
283 |
284 | # Node.js Tools for Visual Studio
285 | .ntvs_analysis.dat
286 | node_modules/
287 |
288 | # Visual Studio 6 build log
289 | *.plg
290 |
291 | # Visual Studio 6 workspace options file
292 | *.opt
293 |
294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
295 | *.vbw
296 |
297 | # Visual Studio LightSwitch build output
298 | **/*.HTMLClient/GeneratedArtifacts
299 | **/*.DesktopClient/GeneratedArtifacts
300 | **/*.DesktopClient/ModelManifest.xml
301 | **/*.Server/GeneratedArtifacts
302 | **/*.Server/ModelManifest.xml
303 | _Pvt_Extensions
304 |
305 | # Paket dependency manager
306 | .paket/paket.exe
307 | paket-files/
308 |
309 | # FAKE - F# Make
310 | .fake/
311 |
312 | # CodeRush personal settings
313 | .cr/personal
314 |
315 | # Python Tools for Visual Studio (PTVS)
316 | __pycache__/
317 | *.pyc
318 |
319 | # Cake - Uncomment if you are using it
320 | # tools/**
321 | # !tools/packages.config
322 |
323 | # Tabs Studio
324 | *.tss
325 |
326 | # Telerik's JustMock configuration file
327 | *.jmconfig
328 |
329 | # BizTalk build output
330 | *.btp.cs
331 | *.btm.cs
332 | *.odx.cs
333 | *.xsd.cs
334 |
335 | # OpenCover UI analysis results
336 | OpenCover/
337 |
338 | # Azure Stream Analytics local run output
339 | ASALocalRun/
340 |
341 | # MSBuild Binary and Structured Log
342 | *.binlog
343 |
344 | # NVidia Nsight GPU debugger configuration file
345 | *.nvuser
346 |
347 | # MFractors (Xamarin productivity tool) working folder
348 | .mfractor/
349 |
350 | # Local History for Visual Studio
351 | .localhistory/
352 |
353 | # BeatPulse healthcheck temp database
354 | healthchecksdb
355 |
356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
357 | MigrationBackup/
358 |
359 | # Ionide (cross platform F# VS Code tools) working folder
360 | .ionide/
361 |
362 | # Fody - auto-generated XML schema
363 | FodyWeavers.xsd
--------------------------------------------------------------------------------
/DeepSeek.NET.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.13.35507.96 d17.13
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DeepSeek.NET", "DeepSeek.NET\DeepSeek.NET.csproj", "{8DCDFADF-8F54-4816-9D9B-F47A5EC0A9AC}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DeepSeek.NETTests", "DeepSeek.NETTests\DeepSeek.NETTests.csproj", "{637EACA7-E58E-407C-83A1-55B4AF597874}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|Any CPU = Debug|Any CPU
13 | Release|Any CPU = Release|Any CPU
14 | EndGlobalSection
15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
16 | {8DCDFADF-8F54-4816-9D9B-F47A5EC0A9AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
17 | {8DCDFADF-8F54-4816-9D9B-F47A5EC0A9AC}.Debug|Any CPU.Build.0 = Debug|Any CPU
18 | {8DCDFADF-8F54-4816-9D9B-F47A5EC0A9AC}.Release|Any CPU.ActiveCfg = Release|Any CPU
19 | {8DCDFADF-8F54-4816-9D9B-F47A5EC0A9AC}.Release|Any CPU.Build.0 = Release|Any CPU
20 | {637EACA7-E58E-407C-83A1-55B4AF597874}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {637EACA7-E58E-407C-83A1-55B4AF597874}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {637EACA7-E58E-407C-83A1-55B4AF597874}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {637EACA7-E58E-407C-83A1-55B4AF597874}.Release|Any CPU.Build.0 = Release|Any CPU
24 | EndGlobalSection
25 | GlobalSection(SolutionProperties) = preSolution
26 | HideSolutionNode = FALSE
27 | EndGlobalSection
28 | GlobalSection(ExtensibilityGlobals) = postSolution
29 | SolutionGuid = {6F74EA4B-150E-4F4C-8B45-1915E23698B1}
30 | EndGlobalSection
31 | EndGlobal
32 |
--------------------------------------------------------------------------------
/DeepSeek.NET/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "MicroPython.executeButton": [
3 | {
4 | "text": "▶",
5 | "tooltip": "Run",
6 | "alignment": "left",
7 | "command": "extension.executeFile",
8 | "priority": 3.5
9 | }
10 | ],
11 | "MicroPython.syncButton": [
12 | {
13 | "text": "$(sync)",
14 | "tooltip": "sync",
15 | "alignment": "left",
16 | "command": "extension.execute",
17 | "priority": 4
18 | }
19 | ]
20 | }
--------------------------------------------------------------------------------
/DeepSeek.NET/Classes/ChatRequest/ChatRequest.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json.Serialization;
2 |
3 | namespace DeepSeek.Classes;
4 |
5 | ///
6 | /// Chat request
7 | ///
8 | public class ChatRequest
9 | {
10 | ///
11 | /// List of messages
12 | ///
13 | public Message[] Messages { get; set; } = Array.Empty();
14 |
15 | ///
16 | /// The ID of the model to use. You can use deepseek-chat or deepseek-coder.
17 | ///
18 | public string? Model { get; set; }
19 |
20 | ///
21 | /// A number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, reducing the model's likelihood to repeat the same content.
22 | ///
23 | [JsonPropertyName("frequency_penalty")]
24 | public double FrequencyPenalty { get; set; } = 0;
25 |
26 | ///
27 | /// The maximum number of tokens allowed for the generated completion in a single request. The total length of input tokens and output tokens is limited by the model's context length.
28 | /// default: 4096
29 | ///
30 | [JsonPropertyName("max_tokens")]
31 | public long MaxTokens { get; set; } = 4096;
32 |
33 | ///
34 | /// A number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.
35 | ///
36 | [JsonPropertyName("presence_penalty")]
37 | public double PresencePenalty { get; set; } = 0;
38 |
39 | ///
40 | /// A list of up to 4 strings. The API will stop generating further tokens upon encountering any of these strings.
41 | ///
42 | public List Stop { get; set; } = [];
43 |
44 | ///
45 | /// If set to true, messages will be sent incrementally in a stream using SSE (server-sent events). The message stream ends with data: [DONE].
46 | ///
47 | [JsonInclude]
48 | internal bool Stream { get; set; }
49 |
50 | ///
51 | /// Sampling temperature, between 0 and 2. Higher values like 0.8 make the output more random, while lower values like 0.2 make it more focused and deterministic. We generally recommend adjusting this or top_p, but not both.
52 | ///
53 | public double Temperature { get; set; } = 1;
54 |
55 | ///
56 | /// An alternative to sampling with temperature, the model considers the results of the top_p probability tokens. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend adjusting this or temperature, but not both.
57 | ///
58 | [JsonPropertyName("top_p")]
59 | public double TopP { get; set; } = 1;
60 |
61 | ///
62 | /// Whether to return the log probabilities of the output tokens. If true, the log probabilities of each output token are returned in the content of the message.
63 | ///
64 | public bool Logprobs { get; set; }
65 |
66 | ///
67 | /// An integer N between 0 and 20, specifying the top N tokens with the highest probabilities to return for each output position, along with their log probabilities. If this parameter is specified, logprobs must be true.
68 | ///
69 | [JsonPropertyName("top_logprobs")]
70 | public int? TopLogprobs { get; set; }
71 | }
--------------------------------------------------------------------------------
/DeepSeek.NET/Classes/ChatResponse/ChatResponse.cs:
--------------------------------------------------------------------------------
1 | namespace DeepSeek.Classes;
2 |
3 | ///
4 | /// Chat response
5 | ///
6 | public class ChatResponse
7 | {
8 | ///
9 | /// The unique identifier for the conversation.
10 | ///
11 | public string? Id { get; set; }
12 |
13 | ///
14 | /// A list of choices generated by the model for the completion.
15 | ///
16 | public List Choices { get; set; } = [];
17 |
18 | ///
19 | /// The name of the model used to generate the completion.
20 | ///
21 | public string? Model { get; set; }
22 |
23 | ///
24 | /// The Unix timestamp (in seconds) when the chat completion was created.
25 | ///
26 | public long Created { get; set; }
27 |
28 | ///
29 | /// The type of object, which is "chat.completion".
30 | ///
31 | public string Object { get; set; } = "chat.completion";
32 |
33 | ///
34 | /// Usage information for the chat completion request.
35 | ///
36 | public Usage? Usage { get; set; }
37 | }
--------------------------------------------------------------------------------
/DeepSeek.NET/Classes/ChatResponse/Choice.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json.Serialization;
2 |
3 | namespace DeepSeek.Classes;
4 |
5 | ///
6 | /// A choice generated by the model.
7 | ///
8 | public class Choice
9 | {
10 | [JsonPropertyName("finish_reason")]
11 | public string? FinishReason { get; set; }
12 |
13 | public long Index { get; set; }
14 |
15 | public Message? Message { get; set; }
16 |
17 | ///
18 | /// Log probability information for this choice.
19 | ///
20 | public Logprobs? Logprobs { get; set; }
21 |
22 | ///
23 | /// Incremental content returned in streaming mode.
24 | ///
25 | public Message? Delta { get; set; }
26 | }
27 |
--------------------------------------------------------------------------------
/DeepSeek.NET/Classes/ChatResponse/Content.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json.Serialization;
2 |
3 | namespace DeepSeek.Classes;
4 |
5 | ///
6 | /// Log probability information for a specific token.
7 | ///
8 | public class Content
9 | {
10 | public string? Token { get; set; }
11 |
12 | public long Logprob { get; set; }
13 |
14 | public byte[] Bytes { get; set; } = [];
15 |
16 | [JsonPropertyName("top_logprobs")]
17 | public List TopLogprobs { get; set; } = [];
18 | }
19 |
--------------------------------------------------------------------------------
/DeepSeek.NET/Classes/ChatResponse/Logprobs.cs:
--------------------------------------------------------------------------------
1 | namespace DeepSeek.Classes;
2 |
3 | ///
4 | /// Log probability information.
5 | ///
6 | public class Logprobs
7 | {
8 | ///
9 | /// A list containing log probability information for the output tokens.
10 | ///
11 | public List Content { get; set; } = [];
12 | }
13 |
--------------------------------------------------------------------------------
/DeepSeek.NET/Classes/ChatResponse/TopLogprobs.cs:
--------------------------------------------------------------------------------
1 | namespace DeepSeek.Classes;
2 |
3 | ///
4 | /// Top log probability information for a specific token.
5 | ///
6 | public class TopLogprobs
7 | {
8 | public string? Token { get; set; }
9 |
10 | public long Logprob { get; set; }
11 |
12 | public byte[] Bytes { get; set; } = [];
13 | }
14 |
--------------------------------------------------------------------------------
/DeepSeek.NET/Classes/ChatResponse/Usage.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json.Serialization;
2 |
3 | namespace DeepSeek.Classes;
4 |
5 | ///
6 | /// Usage information for the request.
7 | ///
8 | public class Usage
9 | {
10 | [JsonPropertyName("completion_tokens")]
11 | public long CompletionTokens { get; set; }
12 |
13 | [JsonPropertyName("prompt_tokens")]
14 | public long PromptTokens { get; set; }
15 |
16 | [JsonPropertyName("total_tokens")]
17 | public long TotalTokens { get; set; }
18 |
19 | [JsonPropertyName("prompt_cache_hit_tokens")]
20 | public long PromptCacheHitTokens { get; set; }
21 |
22 | [JsonPropertyName("prompt_cache_miss_tokens")]
23 | public long PromptCacheMissTokens { get; set; }
24 | }
25 |
--------------------------------------------------------------------------------
/DeepSeek.NET/Classes/Message.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json.Serialization;
2 |
3 | namespace DeepSeek.Classes;
4 |
5 | public class Message
6 | {
7 | public string Content { get; set; } = string.Empty;
8 |
9 | [JsonPropertyName("reasoning_content")]
10 | public string ReasoningContent { get; set; } = string.Empty;
11 | public string Role { get; set; } = string.Empty;
12 |
13 |
14 | public static Message NewUserMessage(string content)
15 | {
16 | return new Message
17 | {
18 | Content = content,
19 | Role = "user"
20 | };
21 | }
22 |
23 | public static Message NewSystemMessage(string content)
24 | {
25 | return new Message
26 | {
27 | Content = content,
28 | Role = "system"
29 | };
30 | }
31 |
32 | public static Message NewAssistantMessage(string content)
33 | {
34 | return new Message
35 | {
36 | Content = content,
37 | Role = "assistant"
38 | };
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/DeepSeek.NET/Classes/ModelResponse/Model.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json.Serialization;
2 |
3 | namespace DeepSeek.Classes;
4 |
5 | public class Model
6 | {
7 | public string? Id { get; set; }
8 | public string? Object { get; set; }
9 |
10 |
11 | [JsonPropertyName("owned_by")]
12 | public string? OwnedBy { get; set; }
13 | }
14 |
15 |
--------------------------------------------------------------------------------
/DeepSeek.NET/Classes/ModelResponse/ModelResponse.cs:
--------------------------------------------------------------------------------
1 | namespace DeepSeek.Classes;
2 |
3 | public class ModelResponse
4 | {
5 | public string? Object { get; set; }
6 | public List Data { get; set; } = [];
7 | }
--------------------------------------------------------------------------------
/DeepSeek.NET/Constant.cs:
--------------------------------------------------------------------------------
1 | namespace DeepSeek;
2 |
3 | public static class Constants
4 | {
5 |
6 | ///
7 | /// Base domain for API requests
8 | ///
9 | public const string BaseAddress = "https://api.deepseek.com";
10 |
11 | ///
12 | /// Chat completions endpoint
13 | ///
14 | public const string CompletionEndpoint = "/chat/completions";
15 |
16 | ///
17 | /// Models list endpoint
18 | ///
19 | public const string ModelsEndpoint = "/models";
20 |
21 | ///
22 | /// Stream completion indicator
23 | ///
24 | public const string StreamDoneSign = "[DONE]";
25 | }
26 |
27 |
28 | public static class Models
29 | {
30 | public const string ModelChat = "deepseek-chat";
31 |
32 | public const string ModelReasoner = "deepseek-reasoner";
33 | }
34 |
--------------------------------------------------------------------------------
/DeepSeek.NET/DeepSeek.NET.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net8.0
5 | enable
6 | enable
7 | True
8 | Added ReasoningContent
9 | A modern .NET wrapper for the DeepSeek AI API
10 | LuisLlamas
11 | A modern .NET wrapper for the DeepSeek AI API – integrate conversational AI into your applications with ease.
12 | README.md
13 | https://github.com/luisllamasbinaburo/deepseeknet
14 | git
15 | LICENSE.txt
16 | $(NoWarn);NU5104
17 | 1.2.0
18 |
19 |
20 |
21 |
22 | True
23 | \
24 |
25 |
26 | True
27 | \
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/DeepSeek.NET/DeepSeekClient.cs:
--------------------------------------------------------------------------------
1 | using DeepSeek.Classes;
2 | using Microsoft.Extensions.AI;
3 | using System.Diagnostics.CodeAnalysis;
4 | using System.Net.Http.Json;
5 | using System.Runtime.CompilerServices;
6 | using System.Text;
7 | using System.Text.Encodings.Web;
8 | using System.Text.Json;
9 | using System.Text.Json.Serialization;
10 | using System.Text.Unicode;
11 | using System.Threading.Channels;
12 |
13 | namespace DeepSeek;
14 |
15 | public class DeepSeekClient : IChatClient, IDisposable
16 | {
17 | private readonly HttpClient _httpClient;
18 | private bool _disposed;
19 | private readonly ChatClientMetadata _metadata = new("deepseek", new Uri(Constants.BaseAddress));
20 |
21 | public JsonSerializerOptions JsonSerializerOptions { get; } = new()
22 | {
23 | ReferenceHandler = ReferenceHandler.IgnoreCycles,
24 | PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
25 | Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
26 | DefaultBufferSize = 1024
27 | };
28 |
29 | public string? ErrorMessage { get; private set; }
30 |
31 | public DeepSeekClient(HttpClient httpClient, string apiKey)
32 | {
33 | _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
34 | ConfigureHttpClient(apiKey);
35 | }
36 |
37 | public DeepSeekClient(string apiKey) : this(new HttpClient(), apiKey)
38 | {
39 | _httpClient.Timeout = TimeSpan.FromSeconds(60);
40 | }
41 |
42 | private void ConfigureHttpClient(string apiKey)
43 | {
44 | _httpClient.BaseAddress = new Uri(Constants.BaseAddress);
45 | _httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Bearer {apiKey}");
46 | }
47 |
48 | public void SetTimeout(int seconds)
49 | {
50 | if (seconds <= 0) throw new ArgumentOutOfRangeException(nameof(seconds));
51 | _httpClient.Timeout = TimeSpan.FromSeconds(seconds);
52 | }
53 |
54 | public async Task ListModelsAsync(CancellationToken cancellationToken = default)
55 | {
56 | using var response = await _httpClient.GetAsync(Constants.ModelsEndpoint, cancellationToken);
57 |
58 | if (!response.IsSuccessStatusCode)
59 | {
60 | await HandleErrorResponse(response);
61 | return null;
62 | }
63 |
64 | return await response.Content.ReadFromJsonAsync(JsonSerializerOptions, cancellationToken);
65 | }
66 |
67 | ///
68 | /// Creates a chat completion
69 | ///
70 | /// Chat request parameters
71 | /// Chat response or null if failed
72 | public async Task ChatAsync(ChatRequest request, CancellationToken cancellationToken = default)
73 | {
74 | request.Stream = false;
75 | using var content = JsonContent.Create(request, options: JsonSerializerOptions);
76 |
77 | using var response = await _httpClient.PostAsync(Constants.CompletionEndpoint, content, cancellationToken);
78 |
79 | if (!response.IsSuccessStatusCode)
80 | {
81 | await HandleErrorResponse(response);
82 | return null;
83 | }
84 |
85 | return await response.Content.ReadFromJsonAsync(JsonSerializerOptions, cancellationToken);
86 | }
87 |
88 | ///
89 | /// Creates a streaming chat completion
90 | ///
91 | /// Async enumerable of choices
92 | public async Task?> ChatStreamAsync(ChatRequest request, CancellationToken cancellationToken)
93 | {
94 | request.Stream = true;
95 | var content = new StringContent(JsonSerializer.Serialize(request, JsonSerializerOptions), Encoding.UTF8, "application/json");
96 |
97 | var requestMessage = new HttpRequestMessage(HttpMethod.Post, Constants.CompletionEndpoint)
98 | {
99 | Content = content,
100 | };
101 | var response = await _httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
102 |
103 | if (response.IsSuccessStatusCode)
104 | {
105 | var stream = await response.Content.ReadAsStreamAsync();
106 | return ProcessStream(stream);
107 | }
108 | else
109 | {
110 | var res = await response.Content.ReadAsStringAsync();
111 | ErrorMessage = res;
112 | return null;
113 | }
114 | }
115 |
116 | private IAsyncEnumerable ProcessStream(Stream stream)
117 | {
118 | var reader = new StreamReader(stream);
119 |
120 | var channel = Channel.CreateUnbounded();
121 | _ = Task.Run(async () =>
122 | {
123 | while (true)
124 | {
125 | var line = await reader.ReadLineAsync();
126 | if (line is null)
127 | {
128 | break;
129 | }
130 |
131 | line = line?.Replace("data:", "").Trim();
132 |
133 | if (line == Constants.StreamDoneSign) break;
134 | if (string.IsNullOrWhiteSpace(line)) continue;
135 |
136 | var chatResponse = JsonSerializer.Deserialize(line, JsonSerializerOptions);
137 |
138 | var choice = chatResponse?.Choices.FirstOrDefault();
139 | if (choice is null) continue;
140 |
141 | await channel.Writer.WriteAsync(choice);
142 | }
143 | channel.Writer.Complete();
144 | });
145 |
146 | return channel.Reader.ReadAllAsync();
147 | }
148 |
149 | private async Task HandleErrorResponse(HttpResponseMessage response)
150 | {
151 | ErrorMessage = $"HTTP {response.StatusCode}: {await response.Content.ReadAsStringAsync()}";
152 | }
153 |
154 | public void Dispose()
155 | {
156 | if (_disposed) return;
157 | _httpClient.Dispose();
158 | _disposed = true;
159 | GC.SuppressFinalize(this);
160 | }
161 |
162 | #region IChatClient
163 | async Task IChatClient.GetResponseAsync(IEnumerable messages, ChatOptions? options, CancellationToken cancellationToken)
164 | {
165 | ChatRequest request = CreateChatRequest(messages, options);
166 |
167 | DeepSeek.Classes.ChatResponse? response = await ChatAsync(request, cancellationToken);
168 | ThrowIfRequestFailed(response);
169 |
170 | return CreateMeaiChatResponse(response);
171 | }
172 |
173 | async IAsyncEnumerable IChatClient.GetStreamingResponseAsync(IEnumerable messages, ChatOptions? options, [EnumeratorCancellation] CancellationToken cancellationToken)
174 | {
175 | IAsyncEnumerable? choices = await ChatStreamAsync(CreateChatRequest(messages, options), cancellationToken);
176 | ThrowIfRequestFailed(choices);
177 |
178 | string responseId = Guid.NewGuid().ToString("N");
179 | await foreach (var choice in choices)
180 | {
181 | yield return CreateChatResponseUpdate(choice, responseId);
182 | }
183 | }
184 |
185 | object? IChatClient.GetService(Type serviceType, object? serviceKey) =>
186 | serviceKey is not null ? null :
187 | serviceType == typeof(ChatClientMetadata) ? _metadata :
188 | serviceType?.IsInstanceOfType(this) is true ? this :
189 | null;
190 |
191 | private void ThrowIfRequestFailed([NotNull] object? response)
192 | {
193 | if (response is null)
194 | {
195 | throw new InvalidOperationException(string.IsNullOrWhiteSpace(ErrorMessage) ?
196 | $"Failed to get response" :
197 | $"Failed to get response: {ErrorMessage}");
198 | }
199 | }
200 |
201 | private static Microsoft.Extensions.AI.ChatResponse CreateMeaiChatResponse(DeepSeek.Classes.ChatResponse response)
202 | {
203 | Microsoft.Extensions.AI.ChatResponse completion = new([])
204 | {
205 | ResponseId = response.Id,
206 | ModelId = response.Model,
207 | CreatedAt = DateTimeOffset.FromUnixTimeSeconds(response.Created)
208 | };
209 |
210 | if (response.Choices is { Count: > 0 })
211 | {
212 | completion.FinishReason ??= CreateFinishReason(response.Choices[0]);
213 | completion.Messages.Add(CreateChatMessage(response, response.Choices[0]));
214 | }
215 |
216 | if (response.Usage is Usage usage)
217 | {
218 | completion.Usage = new()
219 | {
220 | InputTokenCount = (int)usage.PromptTokens,
221 | TotalTokenCount = (int)usage.TotalTokens,
222 | OutputTokenCount = (int)usage.CompletionTokens,
223 | AdditionalCounts = new()
224 | {
225 | [nameof(usage.PromptCacheHitTokens)] = (int)usage.PromptCacheHitTokens,
226 | [nameof(usage.PromptCacheMissTokens)] = (int)usage.PromptCacheMissTokens,
227 | },
228 | };
229 | }
230 |
231 | return completion;
232 | }
233 |
234 | private static ChatFinishReason? CreateFinishReason(Choice choice) =>
235 | choice.FinishReason switch
236 | {
237 | "stop" => ChatFinishReason.Stop,
238 | "length" => ChatFinishReason.Length,
239 | "content_filter" => ChatFinishReason.ContentFilter,
240 | "tool_calls" => ChatFinishReason.ToolCalls,
241 | _ => null,
242 | };
243 |
244 | private static ChatMessage CreateChatMessage(DeepSeek.Classes.ChatResponse response, Choice choice)
245 | {
246 | Message? choiceMessage = choice.Delta ?? choice.Message;
247 |
248 | ChatMessage m = new(CreateChatRole(choiceMessage), choiceMessage?.Content)
249 | {
250 | MessageId = response.Id,
251 | RawRepresentation = choice,
252 | };
253 |
254 | if (choice.Logprobs is not null)
255 | {
256 | (m.AdditionalProperties ??= []).Add(nameof(choice.Logprobs), choice.Logprobs);
257 | }
258 |
259 | return m;
260 | }
261 |
262 | private static ChatResponseUpdate CreateChatResponseUpdate(Choice choice, string responseId)
263 | {
264 | Message? choiceMessage = choice.Delta ?? choice.Message;
265 |
266 | ChatResponseUpdate update = new(CreateChatRole(choiceMessage), choiceMessage?.Content)
267 | {
268 | FinishReason = CreateFinishReason(choice),
269 | RawRepresentation = choice,
270 | ResponseId = responseId,
271 | };
272 |
273 | if (choice.Logprobs is not null)
274 | {
275 | (update.AdditionalProperties ??= []).Add(nameof(choice.Logprobs), choice.Logprobs);
276 | }
277 |
278 | return update;
279 | }
280 |
281 | private static ChatRole CreateChatRole(Message? m) =>
282 | m?.Role switch
283 | {
284 | "user" => ChatRole.User,
285 | "system" => ChatRole.System,
286 | _ => ChatRole.Assistant,
287 | };
288 |
289 | private ChatRequest CreateChatRequest(IEnumerable chatMessages, ChatOptions? options)
290 | {
291 | ChatRequest request = options?.RawRepresentationFactory?.Invoke(this) as ChatRequest ?? new();
292 |
293 | if (options is not null)
294 | {
295 | if (options.ModelId is not null) request.Model = options.ModelId;
296 | if (options.FrequencyPenalty is not null) request.FrequencyPenalty = options.FrequencyPenalty.Value;
297 | if (options.MaxOutputTokens is not null) request.MaxTokens = options.MaxOutputTokens.Value;
298 | if (options.PresencePenalty is not null) request.PresencePenalty = options.PresencePenalty.Value;
299 | if (options.StopSequences is not null) request.Stop = [.. options.StopSequences];
300 | if (options.Temperature is not null) request.Temperature = options.Temperature.Value;
301 | if (options.TopP is not null) request.TopP = options.TopP.Value;
302 | }
303 |
304 | List messages = [];
305 | if (request.Messages is not null)
306 | {
307 | messages.AddRange(request.Messages);
308 | }
309 |
310 | foreach (var message in chatMessages)
311 | {
312 | string role;
313 | if (message.Role == ChatRole.User) role = "user";
314 | else if (message.Role == ChatRole.Assistant) role = "assistant";
315 | else if (message.Role == ChatRole.System) role = "system";
316 | else continue;
317 |
318 | string text = string.Concat(message.Contents.OfType());
319 |
320 | if (!string.IsNullOrWhiteSpace(text))
321 | {
322 | messages.Add(new() { Content = text, Role = role });
323 | }
324 | }
325 |
326 | request.Messages = messages.ToArray();
327 | return request;
328 | }
329 | #endregion
330 | }
--------------------------------------------------------------------------------
/DeepSeek.NETTests/DeepSeek.NETTests.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net8.0
5 | latest
6 | enable
7 | enable
8 |
12 | true
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/DeepSeek.NETTests/DeepSeekClientTests.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.VisualStudio.TestTools.UnitTesting;
2 | using DeepSeek;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Linq;
6 | using System.Threading.Tasks;
7 | using System.IO;
8 | using DeepSeek.Classes;
9 |
10 | namespace DeepSeek.Tests
11 | {
12 | [TestClass]
13 | public class DeepSeekTests
14 | {
15 | private DeepSeekClient? _client;
16 | private bool _disposed;
17 |
18 | private static readonly string? ApiKey = Environment.GetEnvironmentVariable("DEEPSEEK_API_KEY")
19 | ?? "DEEPSEEK_API_KEY";
20 |
21 | [TestInitialize]
22 | public void Initialize()
23 | {
24 | if (ApiKey == "DEEPSEEK_API_KEY" || string.IsNullOrEmpty(ApiKey))
25 | {
26 | Assert.Inconclusive("API key not set");
27 | }
28 |
29 | _client = new DeepSeekClient(ApiKey);
30 | }
31 |
32 | [TestMethod]
33 | public async Task ListModelsAsyncTest_ValidKey_ReturnsModels()
34 | {
35 | // Act
36 | var result = await _client!.ListModelsAsync();
37 |
38 | // Assert
39 | Assert.IsNotNull(result);
40 | Assert.IsTrue(result!.Data!.Count > 0);
41 | Assert.IsNull(_client.ErrorMessage);
42 | }
43 |
44 | [TestMethod]
45 | public async Task ChatAsyncTest_ValidRequest_ReturnsResponse()
46 | {
47 | // Arrange
48 | var request = new ChatRequest
49 | {
50 | Messages = [Message.NewUserMessage("Hello! Tell me an interesting fact about space.")],
51 | Model = Models.ModelChat
52 | };
53 |
54 | // Act
55 | var result = await _client!.ChatAsync(request);
56 |
57 | // Assert
58 | Assert.IsNotNull(result);
59 | Assert.IsFalse(string.IsNullOrEmpty(result!.Choices!.First().Message!.Content));
60 | }
61 |
62 | [TestMethod]
63 | public async Task ChatAsyncTest_ValidReasonerRequest_ReturnsReasonerResponse()
64 | {
65 | // Arrange
66 | var request = new ChatRequest
67 | {
68 | Messages = [Message.NewUserMessage("Hello! Tell me an interesting fact about space.")],
69 | Model = Models.ModelReasoner
70 | };
71 |
72 | // Act
73 | var result = await _client!.ChatAsync(request);
74 |
75 | // Assert
76 | Assert.IsNotNull(result);
77 | Assert.IsFalse(string.IsNullOrEmpty(result!.Choices!.First().Message!.ReasoningContent));
78 | }
79 |
80 | [TestMethod]
81 | public async Task ChatStreamAsyncTest_ValidRequest_StreamsResponses()
82 | {
83 | // Arrange
84 | var request = new ChatRequest
85 | {
86 | Messages = [Message.NewUserMessage("Explain the theory of relativity in 3 sentences.")],
87 | Model = Models.ModelChat
88 | };
89 |
90 | // Act
91 | var responses = new List();
92 |
93 | var choices = await _client!.ChatStreamAsync(request, new CancellationToken());
94 | if (choices is not null)
95 | {
96 | await foreach (var choice in choices)
97 | {
98 | responses.Add(choice.Delta?.Content ?? "");
99 | }
100 | }
101 |
102 | // Assert
103 | Assert.IsTrue(responses.Count > 0);
104 | Assert.IsFalse(string.IsNullOrEmpty(string.Join("", responses)));
105 | }
106 |
107 | [TestMethod]
108 | [ExpectedException(typeof(ArgumentOutOfRangeException))]
109 | public void SetTimeoutTest_InvalidValue_ThrowsException()
110 | {
111 | // Act
112 | _client!.SetTimeout(-1);
113 | }
114 |
115 |
116 | [TestMethod]
117 | public async Task ErrorHandlingTest_InvalidKey_ReturnsError()
118 | {
119 | // Arrange
120 | var invalidClient = new DeepSeekClient("invalid_key");
121 |
122 | // Act
123 | var result = await invalidClient.ListModelsAsync();
124 |
125 | // Assert
126 | Assert.IsNull(result);
127 | Assert.IsNotNull(invalidClient.ErrorMessage);
128 | }
129 | }
130 | }
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) [year] [fullname]
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # DeepSeek.NET
2 |
3 | 
4 | A modern .NET (C#) wrapper for the DeepSeek AI API – integrate conversational AI into your applications with ease.
5 |
6 | - **Model Discovery**: Retrieve available AI models effortlessly.
7 | - **Smart Conversations**: Execute both single-turn and streaming multi-turn dialogues.
8 | - **Streaming Support**: Real-time response handling for dynamic interactions.
9 | - **Modern .NET (C#) Integration**: Built with .NET 8 and `HttpClient` best practices.
10 |
11 | ## 📋 Prerequisites
12 |
13 | - **DeepSeek API Key**: Obtain from [DeepSeek Platform](https://platform.deepseek.com/)
14 | - **.NET 8+**: Target framework requirement
15 |
16 | ## 📦 Installation
17 |
18 | ```bash
19 | dotnet add package DeepSeek.NET
20 | ```
21 |
22 | ## 🛠️ Quick Start
23 |
24 | ### Initialize Client
25 |
26 | ```csharp
27 | // Simple initialization
28 | var client = new DeepSeekClient("your_api_key_here");
29 |
30 | // Or with custom HttpClient
31 | var httpClient = new HttpClient();
32 | var factoryClient = new DeepSeekClient(httpClient, "your_api_key_here");
33 | ```
34 |
35 | (You can change the HttpClient Timeout with `client.setTimeout(int seconds)`)
36 |
37 | ### Discover Available Models
38 |
39 | DeepSeek offers two AI models for different use cases:
40 |
41 | - **`Models.ModelChat`**: Standard conversational AI model, ideal for chat interactions.
42 | - **`Models.ModelReasoner`**: Includes an additional reasoning phase, useful for deeper analytical responses.
43 |
44 | ```csharp
45 | var models = await client.ListModelsAsync();
46 | if (models?.Data is null)
47 | {
48 | Console.WriteLine($"Error: {client.ErrorMsg}");
49 | return;
50 | }
51 |
52 | foreach (var model in models.Data)
53 | {
54 | Console.WriteLine($"- {model.Id}: {model.Capabilities}");
55 | }
56 | ```
57 |
58 | ### Basic Chat Interaction
59 |
60 | When constructing a conversation, you can use different types of messages to define roles:
61 |
62 | - **`Message.NewSystemMessage(content)`**: Used for system instructions or context setting.
63 | - **`Message.NewAssistantMessage(content)`**: Represents a response from the AI assistant.
64 | - **`Message.NewUserMessage(content)`**: Represents a message from the user.
65 |
66 | ```csharp
67 | var chatRequest = new ChatRequest
68 | {
69 | Messages = [
70 | Message.NewUserMessage("Explain quantum computing in 3 sentences"),
71 | Message.NewAssistantMessage("..."),
72 | Message.NewUserMessage("Now simplify it for a 5th grader")
73 | ],
74 | Model = Models.ModelChat
75 | };
76 |
77 | var response = await client.ChatAsync(chatRequest);
78 | var responseContent = response?.Choices.First().Message.Content ?? "No response";
79 |
80 | Console.WriteLine(responseContent);
81 | ```
82 |
83 | ### Real-Time Streaming
84 |
85 | ```csharp
86 | var streamRequest = new ChatRequest
87 | {
88 | Messages = [
89 | Message.NewUserMessage("Tell a 100-word sci-fi story") }
90 | ],
91 | Model = Models.ModelChat
92 | };
93 |
94 | var stream = await client.ChatStreamAsync(streamRequest);
95 | if (stream is null) return;
96 |
97 | await foreach (var chunk in stream)
98 | {
99 | Console.Write(chunk.Delta?.Content);
100 | }
101 | ```
102 |
103 | ### Read Reasoning Content
104 |
105 | Only in case of `Models.Reasoner`, you will have available also the Reasoning Content
106 |
107 | ```csharp
108 | var chatRequest = new ChatRequest
109 | {
110 | Messages = [
111 | Message.NewUserMessage("Hello! Tell me an interesting fact about space.")
112 | ],
113 | Model = Models.ModelReasoner
114 | };
115 |
116 | var response = await client.ChatAsync(chatRequest);
117 | var reasoningContent = response?.Choices.First().Message.ReasoningContent ?? String.Empty;
118 |
119 | Console.WriteLine(reasoningContent);
120 | ```
121 |
122 | ## 🤝 Contributing
123 |
124 | We welcome contributions! Please follow our contribution guidelines when:
125 | - Reporting issues
126 | - Suggesting enhancements
127 | - Submitting pull requests
128 |
129 | ## License
130 |
131 | MIT License – See [LICENSE](LICENSE) for details.
132 |
--------------------------------------------------------------------------------