├── .gitignore
├── .vscode
├── launch.json
├── settings.json
└── tasks.json
├── ChainSemanticFunc
├── ChainSemanticFunc.csproj
├── Plugins
│ └── WriterPlugin
│ │ ├── FacebookPoster
│ │ ├── config.json
│ │ └── skprompt.txt
│ │ └── Translate
│ │ ├── config.json
│ │ └── skprompt.txt
└── Program.cs
├── InlineSemanticFunction
├── InlineSample.cs
├── InlineSemanticFunction.csproj
└── Program.cs
├── IntroSample
├── IntroSample.csproj
├── Plugins
│ └── WriterPlugin
│ │ └── FairyTales
│ │ ├── config.json
│ │ └── skprompt.txt
└── Program.cs
├── KernelChatCompletion
├── KernelChatCompletion.csproj
└── Program.cs
├── KmSearch
├── KmSearch.csproj
├── Plugins
│ └── QASkill
│ │ └── AssistantResults
│ │ ├── config.json
│ │ └── skprompt.txt
└── Program.cs
├── LICENSE
├── MWC-2023
├── MWC2023.sln
├── MixSemanticFunAndNativeFun
│ ├── MixSemanticFunAndNativeFun.csproj
│ ├── Plugins
│ │ ├── CrmPlugin
│ │ │ └── Customer.cs
│ │ └── WriterPlugin
│ │ │ ├── Email
│ │ │ ├── config.json
│ │ │ └── skprompt.txt
│ │ │ └── Email2
│ │ │ ├── config.json
│ │ │ └── skprompt.txt
│ └── Program.cs
├── SequentialPlannerSample
│ ├── Plugins
│ │ └── WriterPlugin
│ │ │ ├── FacebookPoster
│ │ │ ├── config.json
│ │ │ └── skprompt.txt
│ │ │ └── Translate
│ │ │ ├── config.json
│ │ │ └── skprompt.txt
│ ├── Program.cs
│ └── SequentialPlannerSample.csproj
├── TransAndRag
│ ├── Plugins
│ │ └── QAPlugin
│ │ │ ├── AssistantResults
│ │ │ ├── config.json
│ │ │ └── skprompt.txt
│ │ │ └── Translate
│ │ │ ├── config.json
│ │ │ └── skprompt.txt
│ ├── Program.cs
│ └── TransAndRag.csproj
└── WebSearch
│ ├── Plugins
│ └── QAPlugin
│ │ └── AssistantResults
│ │ ├── config.json
│ │ └── skprompt.txt
│ ├── Program.cs
│ └── WebSearch.csproj
├── MixSemanticFunAndNativeFun
├── MixSemanticFunAndNativeFun.csproj
├── Plugins
│ ├── CrmPlugin
│ │ └── Customer.cs
│ └── WriterPlugin
│ │ ├── Email
│ │ ├── config.json
│ │ └── skprompt.txt
│ │ └── Email2
│ │ ├── config.json
│ │ └── skprompt.txt
└── Program.cs
├── MultiChatCompletionSample
├── MultiChatCompletionSample.csproj
└── Program.cs
├── NativeFunctionSample
├── NativeFunctionSample.csproj
├── Plugins
│ ├── CrmPlugin
│ │ └── Customer.cs
│ └── WriterPlugin
│ │ └── Email
│ │ ├── config.json
│ │ └── skprompt.txt
└── Program.cs
├── NatvieFunctions
├── NatvieFunctions.csproj
├── Plugins
│ └── QAPlugin
│ │ └── AssistantResults
│ │ ├── config.json
│ │ └── skprompt.txt
└── Program.cs
├── NetConf2023.zip
├── NetConf2023
├── 01-GetStart
│ ├── 01-GetStart.csproj
│ ├── Plugins
│ │ └── Chat.yaml
│ └── Program.cs
├── 02-NativeFunc
│ ├── 02-NativeFunc.csproj
│ ├── Plugins
│ │ ├── ChatPlugin
│ │ │ └── Chat.yaml
│ │ └── DateTimePlugin
│ │ │ └── DateTimePlugin.cs
│ └── Program.cs
├── 03-MultiSemanticFuncs
│ ├── 03-MultiSemanticFuncs.csproj
│ ├── Plugins
│ │ ├── TranslatePlugin
│ │ │ └── Translate.yaml
│ │ └── WriterPlugin
│ │ │ └── Writer.yaml
│ └── Program.cs
├── 04-TransAndRag
│ ├── Plugins
│ │ └── QAPlugin
│ │ │ ├── AssistantResults
│ │ │ ├── config.json
│ │ │ └── skprompt.txt
│ │ │ └── Translate
│ │ │ ├── config.json
│ │ │ └── skprompt.txt
│ ├── Program.cs
│ └── TransAndRag.csproj
├── 05-EasySummaryClassification
│ ├── 05-EasySummaryClassification.csproj
│ ├── Plugins
│ │ └── SummarizePlugin
│ │ │ └── Summarize
│ │ │ ├── config.json
│ │ │ └── skprompt.txt
│ └── Program.cs
├── DotNetConf-2023-SemanticKernel.pptx
└── netconf2023.sln
├── PromptTemplateEngineSample
├── Program.cs
└── PromptTemplateEngineSample.csproj
├── README.md
├── SequentialPlannerSample
├── Plugins
│ └── WriterPlugin
│ │ ├── FacebookPoster
│ │ ├── config.json
│ │ └── skprompt.txt
│ │ └── Translate
│ │ ├── config.json
│ │ └── skprompt.txt
├── Program.cs
└── SequentialPlannerSample.csproj
├── SerializingSemanticFunction
├── Plugins
│ └── WriterPlugin
│ │ └── FacebookPoster
│ │ ├── config.json
│ │ └── skprompt.txt
├── Program.cs
└── SerializingSemanticFunction.csproj
├── TransAndRag
├── Plugins
│ └── QAPlugin
│ │ ├── AssistantResults
│ │ ├── config.json
│ │ └── skprompt.txt
│ │ └── Translate
│ │ ├── config.json
│ │ └── skprompt.txt
├── Program.cs
└── TransAndRag.csproj
├── TransAndRagUseSemanticFun
├── Plugins
│ └── QAPlugin
│ │ ├── AssistantResults
│ │ ├── config.json
│ │ └── skprompt.txt
│ │ ├── KmSearch.cs
│ │ └── Translate
│ │ ├── config.json
│ │ └── skprompt.txt
├── Program.cs
└── TransAndRagUseSemanticFun.csproj
├── WebSearch
├── Plugins
│ └── QAPlugin
│ │ └── AssistantResults
│ │ ├── config.json
│ │ └── skprompt.txt
├── Program.cs
└── WebSearch.csproj
├── WithoutSkSample
├── WithoutSkSample.sln
└── WithoutSkSample
│ ├── GPT4
│ ├── PromptTemplate.txt
│ ├── RequestModel.cs
│ └── ResponseModel.cs
│ ├── Program.cs
│ └── WithoutSkSample.csproj
├── WriterPlannerSample
├── Program.cs
└── WriterPlannerSample.csproj
├── sklearn.sln
└── skv1_start
├── 01-GetStart
├── 01-GetStart.csproj
├── Plugins
│ └── Chat.yaml
└── Program.cs
├── 02-NativeFunc
├── 02-NativeFunc.csproj
├── Plugins
│ ├── ChatPlugin
│ │ └── Chat.yaml
│ └── DateTimePlugin
│ │ └── DateTimePlugin.cs
└── Program.cs
├── 03-MultiSemanticFuncs
├── 03-MultiSemanticFuncs.csproj
├── Plugins
│ ├── TranslatePlugin
│ │ └── Translate.yaml
│ └── WriterPlugin
│ │ └── Writer.yaml
└── Program.cs
├── 04-TransAndRag
├── Plugins
│ └── QAPlugin
│ │ ├── AssistantResults
│ │ ├── config.json
│ │ └── skprompt.txt
│ │ └── Translate
│ │ ├── config.json
│ │ └── skprompt.txt
├── Program.cs
└── TransAndRag.csproj
├── 05-EasySummaryClassification
├── 05-EasySummaryClassification.csproj
├── Plugins
│ └── SummarizePlugin
│ │ └── Summarize
│ │ ├── config.json
│ │ └── skprompt.txt
└── Program.cs
├── readme.md
└── skv1_start.sln
/.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/main/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 | [Ll]og/
33 | [Ll]ogs/
34 |
35 | # Visual Studio 2015/2017 cache/options directory
36 | .vs/
37 | # Uncomment if you have tasks that create the project's static files in wwwroot
38 | #wwwroot/
39 |
40 | # Visual Studio 2017 auto generated files
41 | Generated\ Files/
42 |
43 | # MSTest test Results
44 | [Tt]est[Rr]esult*/
45 | [Bb]uild[Ll]og.*
46 |
47 | # NUnit
48 | *.VisualState.xml
49 | TestResult.xml
50 | nunit-*.xml
51 |
52 | # Build Results of an ATL Project
53 | [Dd]ebugPS/
54 | [Rr]eleasePS/
55 | dlldata.c
56 |
57 | # Benchmark Results
58 | BenchmarkDotNet.Artifacts/
59 |
60 | # .NET Core
61 | project.lock.json
62 | project.fragment.lock.json
63 | artifacts/
64 |
65 | # ASP.NET Scaffolding
66 | ScaffoldingReadMe.txt
67 |
68 | # StyleCop
69 | StyleCopReport.xml
70 |
71 | # Files built by Visual Studio
72 | *_i.c
73 | *_p.c
74 | *_h.h
75 | *.ilk
76 | *.meta
77 | *.obj
78 | *.iobj
79 | *.pch
80 | *.pdb
81 | *.ipdb
82 | *.pgc
83 | *.pgd
84 | *.rsp
85 | *.sbr
86 | *.tlb
87 | *.tli
88 | *.tlh
89 | *.tmp
90 | *.tmp_proj
91 | *_wpftmp.csproj
92 | *.log
93 | *.tlog
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 6 auto-generated project file (contains which files were open etc.)
298 | *.vbp
299 |
300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project)
301 | *.dsw
302 | *.dsp
303 |
304 | # Visual Studio 6 technical files
305 | *.ncb
306 | *.aps
307 |
308 | # Visual Studio LightSwitch build output
309 | **/*.HTMLClient/GeneratedArtifacts
310 | **/*.DesktopClient/GeneratedArtifacts
311 | **/*.DesktopClient/ModelManifest.xml
312 | **/*.Server/GeneratedArtifacts
313 | **/*.Server/ModelManifest.xml
314 | _Pvt_Extensions
315 |
316 | # Paket dependency manager
317 | .paket/paket.exe
318 | paket-files/
319 |
320 | # FAKE - F# Make
321 | .fake/
322 |
323 | # CodeRush personal settings
324 | .cr/personal
325 |
326 | # Python Tools for Visual Studio (PTVS)
327 | __pycache__/
328 | *.pyc
329 |
330 | # Cake - Uncomment if you are using it
331 | # tools/**
332 | # !tools/packages.config
333 |
334 | # Tabs Studio
335 | *.tss
336 |
337 | # Telerik's JustMock configuration file
338 | *.jmconfig
339 |
340 | # BizTalk build output
341 | *.btp.cs
342 | *.btm.cs
343 | *.odx.cs
344 | *.xsd.cs
345 |
346 | # OpenCover UI analysis results
347 | OpenCover/
348 |
349 | # Azure Stream Analytics local run output
350 | ASALocalRun/
351 |
352 | # MSBuild Binary and Structured Log
353 | *.binlog
354 |
355 | # NVidia Nsight GPU debugger configuration file
356 | *.nvuser
357 |
358 | # MFractors (Xamarin productivity tool) working folder
359 | .mfractor/
360 |
361 | # Local History for Visual Studio
362 | .localhistory/
363 |
364 | # Visual Studio History (VSHistory) files
365 | .vshistory/
366 |
367 | # BeatPulse healthcheck temp database
368 | healthchecksdb
369 |
370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
371 | MigrationBackup/
372 |
373 | # Ionide (cross platform F# VS Code tools) working folder
374 | .ionide/
375 |
376 | # Fody - auto-generated XML schema
377 | FodyWeavers.xsd
378 |
379 | # VS Code files for those working on multiple tools
380 | .vscode/*
381 | !.vscode/settings.json
382 | !.vscode/tasks.json
383 | !.vscode/launch.json
384 | !.vscode/extensions.json
385 | *.code-workspace
386 |
387 | # Local History for Visual Studio Code
388 | .history/
389 |
390 | # Windows Installer files from build outputs
391 | *.cab
392 | *.msi
393 | *.msix
394 | *.msm
395 | *.msp
396 |
397 | # JetBrains Rider
398 | *.sln.iml
399 |
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | // 使用 IntelliSense 找出 C# 偵錯具有哪些屬性
6 | // 針對現有屬性的描述使用暫留
7 | // 如需詳細資訊,請造訪 https://github.com/dotnet/vscode-csharp/blob/main/debugger-launchjson.md
8 | "name": ".NET Core Launch (console)",
9 | "type": "coreclr",
10 | "request": "launch",
11 | "preLaunchTask": "build",
12 | // 如果您已變更目標 Framework,請務必更新程式路徑。
13 | "program": "${workspaceFolder}/WithoutSkSample/WithoutSkSample/bin/Debug/net6.0/WithoutSkSample.dll",
14 | "args": [],
15 | "cwd": "${workspaceFolder}/WithoutSkSample/WithoutSkSample",
16 | // 如需 [主控台] 欄位的詳細資訊,請參閱 https://aka.ms/VSCode-CS-LaunchJson-Console
17 | "console": "internalConsole",
18 | "stopAtEntry": false
19 | },
20 | {
21 | "name": ".NET Core Attach",
22 | "type": "coreclr",
23 | "request": "attach"
24 | }
25 | ]
26 | }
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "dotnet.defaultSolution": "GetStart.sln"
3 | }
--------------------------------------------------------------------------------
/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0.0",
3 | "tasks": [
4 | {
5 | "label": "build",
6 | "command": "dotnet",
7 | "type": "process",
8 | "args": [
9 | "build",
10 | "${workspaceFolder}/WithoutSkSample/WithoutSkSample.sln",
11 | "/property:GenerateFullPaths=true",
12 | "/consoleloggerparameters:NoSummary"
13 | ],
14 | "problemMatcher": "$msCompile"
15 | },
16 | {
17 | "label": "publish",
18 | "command": "dotnet",
19 | "type": "process",
20 | "args": [
21 | "publish",
22 | "${workspaceFolder}/WithoutSkSample/WithoutSkSample.sln",
23 | "/property:GenerateFullPaths=true",
24 | "/consoleloggerparameters:NoSummary"
25 | ],
26 | "problemMatcher": "$msCompile"
27 | },
28 | {
29 | "label": "watch",
30 | "command": "dotnet",
31 | "type": "process",
32 | "args": [
33 | "watch",
34 | "run",
35 | "--project",
36 | "${workspaceFolder}/WithoutSkSample/WithoutSkSample.sln"
37 | ],
38 | "problemMatcher": "$msCompile"
39 | }
40 | ]
41 | }
--------------------------------------------------------------------------------
/ChainSemanticFunc/ChainSemanticFunc.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net7.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | Always
17 |
18 |
19 | Always
20 |
21 |
22 | Always
23 |
24 |
25 | Always
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/ChainSemanticFunc/Plugins/WriterPlugin/FacebookPoster/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "type": "completion",
4 | "description": "產生facebook貼文",
5 | "completion": {
6 | "max_tokens": 2000,
7 | "temperature": 0.2,
8 | "top_p": 0.0,
9 | "presence_penalty": 0.0,
10 | "frequency_penalty": 0.0
11 | },
12 | "input": {
13 | "parameters": [
14 | {
15 | "name": "input",
16 | "description": "貼文主題",
17 | "defaultValue": ""
18 | }
19 | ]
20 | }
21 | }
--------------------------------------------------------------------------------
/ChainSemanticFunc/Plugins/WriterPlugin/FacebookPoster/skprompt.txt:
--------------------------------------------------------------------------------
1 | 你是一位facebook小編,撰寫下列主題的貼文,內容200個字以內,#zh-tw
2 |
3 | {{$input}}
4 |
--------------------------------------------------------------------------------
/ChainSemanticFunc/Plugins/WriterPlugin/Translate/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "type": "completion",
4 | "description": "翻譯",
5 | "completion": {
6 | "max_tokens": 2000,
7 | "temperature": 0.2,
8 | "top_p": 0.0,
9 | "presence_penalty": 0.0,
10 | "frequency_penalty": 0.0
11 | },
12 | "input": {
13 | "parameters": [
14 | {
15 | "name": "input",
16 | "description": "要翻譯的內容",
17 | "defaultValue": ""
18 | }
19 | ]
20 | }
21 | }
--------------------------------------------------------------------------------
/ChainSemanticFunc/Plugins/WriterPlugin/Translate/skprompt.txt:
--------------------------------------------------------------------------------
1 | 翻譯下列內容成為英文,並輸出原始中文資料及翻譯後的英文資料都要顯示出來,中英文內容分隔2行
2 |
3 | {{$input}}
4 |
5 |
--------------------------------------------------------------------------------
/ChainSemanticFunc/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel.Orchestration;
2 | using Microsoft.SemanticKernel;
3 |
4 | namespace ChainSemanticFunc
5 | {
6 | internal class Program
7 | {
8 | private const string deploy_model = "xxx";
9 | private const string aoai_Endpoint = "https://xxx.openai.azure.com";
10 | private const string api_Key = "xxx";
11 |
12 | static async Task Main(string[] args)
13 | {
14 | var kernel = new KernelBuilder()
15 | .WithAzureChatCompletionService(
16 | deploy_model, // Azure OpenAI Deployment Name
17 | aoai_Endpoint, // Azure OpenAI Endpoint
18 | api_Key // Azure OpenAI Key
19 | ).Build();
20 |
21 | // Import the Plugin from the plugins directory.
22 | var pluginsDirectory = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Plugins");
23 | var plugin = kernel.ImportSemanticSkillFromDirectory(pluginsDirectory, "WriterPlugin");
24 |
25 | //叫用GPT模型等得生成結果
26 | var result = await kernel.RunAsync(new ContextVariables("ChatGPT對校園教育的衝擊")
27 | , plugin["FacebookPoster"]
28 | , plugin["Translate"]);
29 |
30 | Console.WriteLine(result);
31 |
32 | }
33 | }
34 | }
--------------------------------------------------------------------------------
/InlineSemanticFunction/InlineSample.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 | using Microsoft.SemanticKernel.Orchestration;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Linq;
6 | using System.Text;
7 | using System.Threading.Tasks;
8 |
9 | namespace InlineSemanticFunction
10 | {
11 | internal static class InlineSample
12 | {
13 | public static async Task NormalParameterAsync(IKernel kernel)
14 | {
15 | const string funcDefinition = @"
16 | 你是一位facebook小編,請使用輕鬆灰諧的語氣,撰寫下列主題的貼文,內容500個字以內,#zh-tw
17 | ###
18 | {{$input}}
19 | ###
20 | ";
21 |
22 | var excuseFunction = kernel.CreateSemanticFunction(funcDefinition,
23 | skillName: "FacebookAgent", functionName: "Post",
24 | maxTokens: 2000, temperature: 0.2,
25 | description: "產生facebook貼文");
26 |
27 | var result = await kernel.RunAsync(@"ChatGPT對校園教育的衝擊", excuseFunction);
28 | Console.WriteLine(result);
29 |
30 | }
31 |
32 | public static async Task CustomizeParameterAsync(IKernel kernel)
33 | {
34 | const string funcDefinition = @"
35 | 你是一位facebook小編,請使用輕鬆灰諧的語氣,撰寫下列主題的貼文,內容500個字以內,#zh-tw
36 | ###
37 | {{$post_subject}}
38 | ###
39 | ";
40 |
41 | var excuseFunction = kernel.CreateSemanticFunction(funcDefinition,
42 | skillName: "FacebookAgent", functionName: "Post",
43 | maxTokens: 2000, temperature: 0.2,
44 | description: "產生facebook貼文");
45 |
46 | var contextVars = new ContextVariables()
47 | {
48 | ["post_subject"] = "ChatGPT對校園教育的衝擊"
49 | };
50 |
51 | var result = await kernel.RunAsync(excuseFunction, contextVars);
52 | Console.WriteLine(result);
53 | }
54 |
55 | public static async Task FewShotSampleAsync(IKernel kernel)
56 | {
57 | const string funcDefinition = @"
58 | 你是一位facebook小編,請先思考一下下列提供的範例寫作風格
59 | ###
60 | {{$fewshot_sample}}
61 | ###
62 |
63 | 接著撰寫下列主題的貼文,內容500個字以內,#zh-tw
64 | ###
65 | {{$post_subject}}
66 | ###
67 |
68 | ";
69 | //few-shot,帶入方文山詞創作範例
70 | string fewshot_sample = @"
71 | 竹籬上 停留著 蜻蜓
72 | 玻璃瓶裡插滿 小小 森林
73 | 青春 嫩綠的很 鮮明
74 |
75 | 百葉窗 折射的 光影
76 | 像有著心事的 一張 表情
77 | 而你 低頭拆信 想知道關於我的事情
78 |
79 | 月色搖晃樹影 穿梭在熱帶雨林
80 | 你離去的原因從來不說明
81 | 你的謊像陷阱我最後才清醒
82 | 幸福只是水中的倒影
83 |
84 | 月色搖晃樹影穿梭在熱帶雨林
85 | 悲傷的雨不停全身血淋淋
86 | 那深陷在沼澤我不堪的愛情
87 | 是我無能為力的傷心
88 |
89 | 蘆葦花開歲已寒 若霜又降路遙漫長
90 | 牆外是誰在吟唱 鳳求凰
91 | 梨園台上 西皮二黃
92 | 卻少了妳 無人問暖
93 | 誰在彼岸 天涯一方
94 |
95 | 在夢裡我醞釀著情緒
96 | 等回憶等那一種熟悉
97 | 人世間最溫柔的消息
98 | 是曾經被你擁入懷裡
99 | ";
100 |
101 | var excuseFunction = kernel.CreateSemanticFunction(funcDefinition,
102 | skillName: "FacebookAgent", functionName: "Post",
103 | maxTokens: 2000, temperature: 0.2,
104 | description: "產生facebook貼文");
105 | var contextVars = new ContextVariables()
106 | {
107 | ["fewshot_sample"] = fewshot_sample,
108 | ["post_subject"] = "ChatGPT對校園教育的衝擊"
109 | };
110 |
111 | var result = await kernel.RunAsync(excuseFunction, contextVars);
112 | Console.WriteLine(result);
113 |
114 | }
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/InlineSemanticFunction/InlineSemanticFunction.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net7.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/InlineSemanticFunction/Program.cs:
--------------------------------------------------------------------------------
1 | using Azure.AI.OpenAI;
2 | using Microsoft.SemanticKernel;
3 | using Microsoft.SemanticKernel.Orchestration;
4 |
5 | namespace InlineSemanticFunction
6 | {
7 | internal class Program
8 | {
9 | private const string deploy_model = "xxx";
10 | private const string aoai_Endpoint = "https://xxx.openai.azure.com";
11 | private const string api_Key = "xxxx";
12 |
13 | static async Task Main(string[] args)
14 | {
15 | var kernel = new KernelBuilder()
16 | .WithAzureChatCompletionService(
17 | deploy_model, // Azure OpenAI Deployment Name
18 | aoai_Endpoint, // Azure OpenAI Endpoint
19 | api_Key // Azure OpenAI Key
20 | ).Build();
21 |
22 | //Inline Semantic Function Intro
23 | await InlineSample.NormalParameterAsync(kernel);
24 |
25 | //Customize Parameter
26 | //await InlineSample.CustomizeParameterAsync(kernel);
27 |
28 | //Few-shot
29 | //await InlineSample.FewShotSampleAsync(kernel);
30 |
31 | }
32 | }
33 | }
--------------------------------------------------------------------------------
/IntroSample/IntroSample.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net7.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | Always
17 |
18 |
19 | Always
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/IntroSample/Plugins/WriterPlugin/FairyTales/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "type": "completion",
4 | "description": "根據主題及角色創造童話故事給小朋友聽",
5 | "completion": {
6 | "max_tokens": 2000,
7 | "temperature": 0.8,
8 | "top_p": 0.0,
9 | "presence_penalty": 0.0,
10 | "frequency_penalty": 0.0
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/IntroSample/Plugins/WriterPlugin/FairyTales/skprompt.txt:
--------------------------------------------------------------------------------
1 | 現在你是一位童話故事創作高手,請根據下列主題
2 | """
3 | {{$story_subject}}
4 | """
5 |
6 | 使用以下角色人物,創造故事給3到7歲小朋友聽,使用繁體中文
7 | """
8 | {{$story_role}}
9 | """
--------------------------------------------------------------------------------
/IntroSample/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 | using Microsoft.SemanticKernel.Orchestration;
3 |
4 | namespace IntroSample
5 | {
6 | internal class Program
7 | {
8 | private const string deploy_model = "xxxx";
9 | private const string aoai_Endpoint = "https://xxxx.openai.azure.com";
10 | private const string api_Key = "xxxxx";
11 |
12 | static async Task Main(string[] args)
13 | {
14 | Console.WriteLine("bot: 你想聽什麼主題的故事呢? \n");
15 | Console.Write("you: ");
16 | string storySubject = Console.ReadLine();
17 | Console.Write("\n");
18 | Console.WriteLine("bot: 故事的角色是什麼呢? \n");
19 | Console.Write("you: ");
20 | string storyRole = Console.ReadLine();
21 | Console.Write("\n");
22 |
23 | var kernel = new KernelBuilder()
24 | .WithAzureChatCompletionService(
25 | deploy_model, // Azure OpenAI Deployment Name
26 | aoai_Endpoint, // Azure OpenAI Endpoint
27 | api_Key // Azure OpenAI Key
28 | ).Build();
29 |
30 |
31 | //Use OpenAI Service
32 | //var kernel = new KernelBuilder()
33 | //.WithOpenAIChatCompletionService(
34 | // OpenAIModelId, // The name of your deployment (e.g., "gpt-3.5-turbo")
35 | // OpenAIApiKey, // The API key of your Azure OpenAI service
36 | // OpenAIOrgId // The endpoint of your Azure OpenAI service
37 | //)
38 | //.Build();
39 |
40 | //接上Plugins
41 | var pluginsDirectory = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Plugins");
42 | var writerPlugin = kernel.ImportSemanticSkillFromDirectory(pluginsDirectory, "WriterPlugin");
43 |
44 | //Prompt Template 參數
45 | var variables = new ContextVariables
46 | {
47 | ["story_subject"] = storySubject,
48 | ["story_role"] = storySubject
49 | };
50 |
51 | //叫用GPT模型等得生成結果
52 | var result = (await kernel.RunAsync(variables, writerPlugin["FairyTales"])).Result;
53 |
54 | Console.WriteLine(result);
55 |
56 | Console.ReadLine();
57 | }
58 | }
59 | }
--------------------------------------------------------------------------------
/KernelChatCompletion/KernelChatCompletion.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net7.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/KernelChatCompletion/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel.Plugins.Memory;
2 | using Microsoft.SemanticKernel;
3 | using Microsoft.SemanticKernel.AI.ChatCompletion;
4 | using Microsoft.SemanticKernel.Connectors.AI.OpenAI;
5 |
6 | namespace KernelChatCompletion
7 | {
8 | internal class Program
9 | {
10 | private const string deploy_Model = "xxx";
11 | private const string aoai_Endpoint = "https://xxx.openai.azure.com";
12 | private const string api_Key = "xxxx";
13 |
14 | static async Task Main(string[] args)
15 | {
16 | var kernel = new KernelBuilder()
17 | .WithAzureChatCompletionService(
18 | deploy_Model, // Azure OpenAI Deployment Name
19 | aoai_Endpoint, // Azure OpenAI Endpoint
20 | api_Key // Azure OpenAI Key
21 | ).Build();
22 |
23 | var requestSettings = new OpenAIRequestSettings()
24 | {
25 | MaxTokens = 1024,
26 | FrequencyPenalty = 0,
27 | PresencePenalty = 0,
28 | Temperature = 0.2,
29 | TopP = 0.5
30 | };
31 |
32 | var chatCompletion = kernel.GetService();
33 | Console.WriteLine($"chatCompletion Object:{chatCompletion.GetType()}");
34 | Console.WriteLine();
35 | Console.WriteLine();
36 | Console.WriteLine("---------------------------");
37 | var chatHistory = chatCompletion.CreateNewChat("你是一位自然語言人工智慧研究專家");
38 | chatHistory.AddUserMessage("ChatGPT與過去的自然語言模型有什麼不同,舉個簡單的例子說明");
39 |
40 |
41 | foreach (IChatResult chatCompletionResult in await chatCompletion.GetChatCompletionsAsync(chatHistory, requestSettings))
42 | {
43 | ChatMessageBase chatMessage = await chatCompletionResult.GetChatMessageAsync();
44 | chatHistory.Add(chatMessage); //加入對話歷程
45 | Console.WriteLine($"Completions : {chatMessage.Content.ToString()}"); //生成結果
46 | }
47 |
48 | Console.WriteLine();
49 | Console.WriteLine();
50 | Console.WriteLine("---- chatHistory ------");
51 | foreach (var message in chatHistory.Messages)
52 | {
53 | Console.WriteLine($"{message.Role}: {message.Content}");
54 | }
55 | Console.WriteLine();
56 |
57 | Console.WriteLine("Hello, World!");
58 | }
59 | }
60 | }
--------------------------------------------------------------------------------
/KmSearch/KmSearch.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net7.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 | Always
18 |
19 |
20 | Always
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/KmSearch/Plugins/QASkill/AssistantResults/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "type": "completion",
4 | "description": "Answer any question based on text source",
5 | "completion": {
6 | "max_tokens": 2000,
7 | "temperature": 0.2
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/KmSearch/Plugins/QASkill/AssistantResults/skprompt.txt:
--------------------------------------------------------------------------------
1 | 這是從知識庫所搜尋到的結果
2 | ###
3 | {{$ans_result}}
4 | ###
5 |
6 | 請根據上述資料,簡短扼要的回答使用者的問題,不需要再廢話解釋資料來源
7 | 問題:{{$query_input}}
8 | 答案:
--------------------------------------------------------------------------------
/KmSearch/Program.cs:
--------------------------------------------------------------------------------
1 | using Azure;
2 | using Microsoft.SemanticKernel;
3 | using Microsoft.SemanticKernel.Memory;
4 | using Microsoft.SemanticKernel.Orchestration;
5 |
6 | namespace KmSearch
7 | {
8 | internal class Program
9 | {
10 | private const string deploy_Model = "xxx";
11 | private const string embedding_Model = "xxxx";
12 | private const string aoai_Endpoint = "https://xxxx.openai.azure.com";
13 | private const string api_Key = "xxxx";
14 | private const string embedding_CollectionName = "Law";
15 |
16 |
17 | static async Task Main(string[] args)
18 | {
19 | var kernel = new KernelBuilder()
20 | .WithAzureTextEmbeddingGenerationService(embedding_Model, aoai_Endpoint, api_Key)
21 | .WithMemoryStorage(new VolatileMemoryStore())
22 | .WithAzureChatCompletionService(
23 | deploy_Model, // Azure OpenAI Deployment Name
24 | aoai_Endpoint, // Azure OpenAI Endpoint
25 | api_Key // Azure OpenAI Key
26 | ).Build();
27 |
28 | //Init KM
29 | await ImportKm(kernel);
30 |
31 |
32 | // Import the Plugin from the plugins directory.
33 | var pluginsDirectory = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Plugins");
34 | var plugin = kernel.ImportSemanticSkillFromDirectory(pluginsDirectory, "QASkill");
35 |
36 | while (true)
37 | {
38 | Console.WriteLine("bot: 您好,我是法規知識大師,您想問什麼呢? \n");
39 | Console.Write("you: ");
40 |
41 | //var ask = "永久保存的機關檔案可以做為公開資料嗎?";
42 | //var ask = "不禮讓行人,會有罸則嗎";
43 | //var ask = "闖紅燈罸多少錢啊";
44 | //var ask = "檔案要傳送到國外可以嗎";
45 | var ask = Console.ReadLine();
46 | Console.Write("\n");
47 |
48 | if (string.Compare(ask, "exit", true) == 0)
49 | {
50 | break;
51 | }
52 |
53 | var searchResult = await kernel.Memory.SearchAsync(embedding_CollectionName, ask, minRelevanceScore: 0.8).FirstOrDefaultAsync();
54 |
55 | var ans = searchResult != null ? searchResult.Metadata.Text : "很抱歉,知識庫沒有相關資料可以提供";
56 |
57 | var variables = new ContextVariables
58 | {
59 | ["ans_result"] = ans,
60 | ["query_input"] = ask
61 | };
62 |
63 | //叫用GPT模型等得生成結果
64 | var result = (await kernel.RunAsync(variables, plugin["AssistantResults"])).Result;
65 |
66 | Console.WriteLine($"bot: {result} \n (法條原文:{ans}) \n");
67 | }
68 | }
69 |
70 | private static async Task ImportKm(IKernel kernel)
71 | {
72 | //知識庫轉存向量儲存
73 | await kernel.Memory.SaveInformationAsync(embedding_CollectionName, id: "第1條", text: "本細則依檔案法(以下簡稱本法)第二十九條規定訂定之。");
74 | await kernel.Memory.SaveInformationAsync(embedding_CollectionName, id: "第2條第1項", text: "本法第二條第二款所稱管理程序,指依文書處理或機關業務相關法令規定,完成核定、發文或辦結之程序。");
75 | await kernel.Memory.SaveInformationAsync(embedding_CollectionName, id: "第2條第2項", text: "本法第二條第二款所稱文字或非文字資料及其附件,指各機關處理公務或因公務而產生之各類紀錄資料及其附件,包括各機關所持有或保管之文書、圖片、紀錄、照片、錄影(音)、微縮片、電腦處理資料等,可供聽、讀、閱覽或藉助科技得以閱覽或理解之文書或物品。");
76 | await kernel.Memory.SaveInformationAsync(embedding_CollectionName, id: "第3條", text: "各機關管理檔案,應依本法第四條規定,並參照檔案中央主管機關訂定之機關檔案管理單位及人員配置基準,設置或指定專責單位或人員。");
77 | await kernel.Memory.SaveInformationAsync(embedding_CollectionName, id: "第4條第1項", text: "各機關依本法第五條規定,經該管機關核准,將檔案運往國外者,應先以微縮、電子或其他方式儲存,並經管理該檔案機關首長核定。");
78 | await kernel.Memory.SaveInformationAsync(embedding_CollectionName, id: "第4條第2項", text: "前項檔案如屬永久保存之機關檔案,並應經檔案中央主管機關同意。");
79 | await kernel.Memory.SaveInformationAsync(embedding_CollectionName, id: "第5條", text: "各機關依本法第六條第二項規定,將檔案中之器物交有關機構保管時,應訂定書面契約或作成紀錄存查。");
80 | }
81 | }
82 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Ian Chen
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 |
--------------------------------------------------------------------------------
/MWC-2023/MWC2023.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.6.33829.357
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MixSemanticFunAndNativeFun", "MixSemanticFunAndNativeFun\MixSemanticFunAndNativeFun.csproj", "{FF00B549-32B1-4C1C-AB01-E1221F2AFFF8}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SequentialPlannerSample", "SequentialPlannerSample\SequentialPlannerSample.csproj", "{3E07845B-30A2-476E-8EE3-8F0801F532F8}"
9 | EndProject
10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TransAndRag", "TransAndRag\TransAndRag.csproj", "{190DDA91-447C-4136-851F-34BB17ED7DFC}"
11 | EndProject
12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebSearch", "WebSearch\WebSearch.csproj", "{BDA3B4FE-FB65-4A71-9ECB-646A1837ECE6}"
13 | EndProject
14 | Global
15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
16 | Debug|Any CPU = Debug|Any CPU
17 | Release|Any CPU = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
20 | {FF00B549-32B1-4C1C-AB01-E1221F2AFFF8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {FF00B549-32B1-4C1C-AB01-E1221F2AFFF8}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {FF00B549-32B1-4C1C-AB01-E1221F2AFFF8}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {FF00B549-32B1-4C1C-AB01-E1221F2AFFF8}.Release|Any CPU.Build.0 = Release|Any CPU
24 | {3E07845B-30A2-476E-8EE3-8F0801F532F8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
25 | {3E07845B-30A2-476E-8EE3-8F0801F532F8}.Debug|Any CPU.Build.0 = Debug|Any CPU
26 | {3E07845B-30A2-476E-8EE3-8F0801F532F8}.Release|Any CPU.ActiveCfg = Release|Any CPU
27 | {3E07845B-30A2-476E-8EE3-8F0801F532F8}.Release|Any CPU.Build.0 = Release|Any CPU
28 | {190DDA91-447C-4136-851F-34BB17ED7DFC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
29 | {190DDA91-447C-4136-851F-34BB17ED7DFC}.Debug|Any CPU.Build.0 = Debug|Any CPU
30 | {190DDA91-447C-4136-851F-34BB17ED7DFC}.Release|Any CPU.ActiveCfg = Release|Any CPU
31 | {190DDA91-447C-4136-851F-34BB17ED7DFC}.Release|Any CPU.Build.0 = Release|Any CPU
32 | {BDA3B4FE-FB65-4A71-9ECB-646A1837ECE6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
33 | {BDA3B4FE-FB65-4A71-9ECB-646A1837ECE6}.Debug|Any CPU.Build.0 = Debug|Any CPU
34 | {BDA3B4FE-FB65-4A71-9ECB-646A1837ECE6}.Release|Any CPU.ActiveCfg = Release|Any CPU
35 | {BDA3B4FE-FB65-4A71-9ECB-646A1837ECE6}.Release|Any CPU.Build.0 = Release|Any CPU
36 | EndGlobalSection
37 | GlobalSection(SolutionProperties) = preSolution
38 | HideSolutionNode = FALSE
39 | EndGlobalSection
40 | GlobalSection(ExtensibilityGlobals) = postSolution
41 | SolutionGuid = {F36445AD-883D-4F2F-BF18-0E2957709C58}
42 | EndGlobalSection
43 | EndGlobal
44 |
--------------------------------------------------------------------------------
/MWC-2023/MixSemanticFunAndNativeFun/MixSemanticFunAndNativeFun.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net7.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | Always
17 |
18 |
19 | Always
20 |
21 |
22 | Always
23 |
24 |
25 | Always
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/MWC-2023/MixSemanticFunAndNativeFun/Plugins/CrmPlugin/Customer.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 | using Microsoft.SemanticKernel.Orchestration;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.ComponentModel;
6 | using System.Linq;
7 | using System.Text;
8 | using System.Threading.Tasks;
9 |
10 | namespace MixSemanticFunAndNativeFun.Plugins.CrmPlugin
11 | {
12 | public class Customer
13 | {
14 | [SKFunction, Description("取得客戶連絡人")]
15 | public string GetCustomerContact(string cusCode)
16 | {
17 | //撰寫從CRM DataBase 取得客戶連絡人資料邏輯
18 | //do something
19 | return $"陳伊恩({cusCode})";
20 | }
21 |
22 | [SKFunction, Description("根據客戶代碼及區域,取得客戶連絡人")]
23 | public string GetCustomerContactV2(SKContext context)
24 | {
25 | //撰寫從CRM DataBase 取得客戶連絡人資料邏輯
26 | //do something
27 | return $"{context.Variables["CusCode"]}-{context.Variables["Area"]} 陳伊恩";
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/MWC-2023/MixSemanticFunAndNativeFun/Plugins/WriterPlugin/Email/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "type": "completion",
4 | "description": "產生Email",
5 | "completion": {
6 | "max_tokens": 2000,
7 | "temperature": 0.2,
8 | "top_p": 0.0,
9 | "presence_penalty": 0.0,
10 | "frequency_penalty": 0.0
11 | },
12 | "input": {
13 | "parameters": [
14 | {
15 | "name": "CusCode",
16 | "description": "客戶編號",
17 | "defaultValue": ""
18 | }
19 | ]
20 | }
21 | }
--------------------------------------------------------------------------------
/MWC-2023/MixSemanticFunAndNativeFun/Plugins/WriterPlugin/Email/skprompt.txt:
--------------------------------------------------------------------------------
1 | 你是一位行政助理,負責處理我所交辧的文書作業任務
2 | 現在,請幫我寫一封信給底下的客戶,內容是關於下星期一開始我將休假一個月,有任何緊急事項,可以連繫公司代理人。
3 | 請產生email內容,不要廢話,使用 #zh-tw
4 |
5 | """
6 | {{CrmPlugin.GetCustomerContact $CusCode}}
7 | """
8 |
--------------------------------------------------------------------------------
/MWC-2023/MixSemanticFunAndNativeFun/Plugins/WriterPlugin/Email2/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "type": "completion",
4 | "description": "產生Email",
5 | "completion": {
6 | "max_tokens": 2000,
7 | "temperature": 0.2,
8 | "top_p": 0.0,
9 | "presence_penalty": 0.0,
10 | "frequency_penalty": 0.0
11 | },
12 | "input": {
13 | "parameters": [
14 | {
15 | "name": "CusCode",
16 | "description": "客戶編號",
17 | "defaultValue": ""
18 | }
19 | ]
20 | }
21 | }
--------------------------------------------------------------------------------
/MWC-2023/MixSemanticFunAndNativeFun/Plugins/WriterPlugin/Email2/skprompt.txt:
--------------------------------------------------------------------------------
1 | 你是一位行政助理,負責處理我所交辧的文書作業任務
2 | 現在,請幫我寫一封信給
3 | """
4 | {{CrmPlugin.GetCustomerContactV2}}
5 | """
6 | 內容是下星期1開始我將休假1個月,有任何緊急事項,可以連繫公司代理人
--------------------------------------------------------------------------------
/MWC-2023/MixSemanticFunAndNativeFun/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 | using Microsoft.SemanticKernel.Orchestration;
3 |
4 | namespace MixSemanticFunAndNativeFun
5 | {
6 | internal class Program
7 | {
8 | //AOAI
9 | private const string deploy_Model = "xxx";
10 | private const string aoai_Endpoint = "https://xxx.openai.azure.com";
11 | private const string api_Key = "xxx";
12 |
13 | //OpenAI
14 | private const string openai_Key = "xxx";
15 | private const string openai_deploy_Model = "gpt-4-1106-preview";
16 |
17 |
18 | static async Task Main(string[] args)
19 | {
20 | //Azure OpenAI
21 | //var kernel = new KernelBuilder()
22 | // .WithAzureChatCompletionService(
23 | // deploy_Model, // Azure OpenAI Deployment Name
24 | // aoai_Endpoint, // Azure OpenAI Endpoint
25 | // api_Key // Azure OpenAI Key
26 | // ).Build();
27 |
28 | //OpenAI
29 | var kernel = new KernelBuilder()
30 | .WithOpenAIChatCompletionService(
31 | modelId: openai_deploy_Model, // OpenAI Deployment Name
32 | apiKey: openai_Key // OpenAI Key
33 | ).Build();
34 |
35 | await WriteEmail(kernel);
36 |
37 | }
38 |
39 | private static async Task WriteEmail(IKernel kernel)
40 | {
41 | // Load native plugin into the kernel function collection
42 | // Functions loaded here are available as "CrmPlugin.*"
43 | var crmPlugin = kernel.ImportFunctions(new Plugins.CrmPlugin.Customer(), "CrmPlugin");
44 |
45 | var writePlugin = "WriterPlugin";
46 | var pluginsDirectory = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Plugins");
47 | kernel.ImportSemanticFunctionsFromDirectory(pluginsDirectory, writePlugin);
48 | var emailFun = kernel.Functions.GetFunction(writePlugin, "Email");
49 |
50 | // Show the result
51 | Console.WriteLine("========= Semantic Function result ======================\n\n");
52 | var emailResult = await kernel.RunAsync(emailFun, new ContextVariables() { { "CusCode", "C2023001" } });
53 |
54 | Console.WriteLine(emailResult.GetValue());
55 | }
56 | }
57 | }
--------------------------------------------------------------------------------
/MWC-2023/SequentialPlannerSample/Plugins/WriterPlugin/FacebookPoster/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "type": "completion",
4 | "description": "產生facebook貼文",
5 | "completion": {
6 | "max_tokens": 2000,
7 | "temperature": 0.2,
8 | "top_p": 0.0,
9 | "presence_penalty": 0.0,
10 | "frequency_penalty": 0.0
11 | },
12 | "input": {
13 | "parameters": [
14 | {
15 | "name": "input",
16 | "description": "貼文主題",
17 | "defaultValue": ""
18 | }
19 | ]
20 | }
21 | }
--------------------------------------------------------------------------------
/MWC-2023/SequentialPlannerSample/Plugins/WriterPlugin/FacebookPoster/skprompt.txt:
--------------------------------------------------------------------------------
1 | 你是一位facebook小編,撰寫下列主題的貼文,內容200個字以內,#zh-tw
2 |
3 | {{$input}}
4 |
--------------------------------------------------------------------------------
/MWC-2023/SequentialPlannerSample/Plugins/WriterPlugin/Translate/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "type": "completion",
4 | "description": "翻譯",
5 | "completion": {
6 | "max_tokens": 2000,
7 | "temperature": 0.2,
8 | "top_p": 0.0,
9 | "presence_penalty": 0.0,
10 | "frequency_penalty": 0.0
11 | },
12 | "input": {
13 | "parameters": [
14 | {
15 | "name": "input",
16 | "description": "要翻譯的內容",
17 | "defaultValue": ""
18 | }
19 | ]
20 | }
21 | }
--------------------------------------------------------------------------------
/MWC-2023/SequentialPlannerSample/Plugins/WriterPlugin/Translate/skprompt.txt:
--------------------------------------------------------------------------------
1 | 翻譯下列內容成為英文,並輸出原始中文資料及翻譯後的英文資料都要顯示出來,中英文內容分隔2行
2 |
3 | {{$input}}
4 |
5 |
--------------------------------------------------------------------------------
/MWC-2023/SequentialPlannerSample/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 | using Microsoft.SemanticKernel.Planners;
3 |
4 | namespace SequentialPlannerSample
5 | {
6 | internal class Program
7 | {
8 | //AOAI
9 | //AOAI
10 | private const string deploy_Model = "xxx";
11 | private const string aoai_Endpoint = "https://xxx.openai.azure.com";
12 | private const string api_Key = "xxx";
13 |
14 | //OpenAI
15 | private const string openai_Key = "xxx";
16 | private const string openai_deploy_Model = "gpt-4-1106-preview";
17 |
18 |
19 | static async Task Main(string[] args)
20 | {
21 | //Azure OpenAI
22 | //var kernel = new KernelBuilder()
23 | // .WithAzureChatCompletionService(
24 | // deploy_Model, // Azure OpenAI Deployment Name
25 | // aoai_Endpoint, // Azure OpenAI Endpoint
26 | // api_Key // Azure OpenAI Key
27 | // ).Build();
28 |
29 | //OpenAI
30 | var kernel = new KernelBuilder()
31 | .WithOpenAIChatCompletionService(
32 | modelId: openai_deploy_Model, // OpenAI Deployment Name
33 | apiKey: openai_Key // OpenAI Key
34 | ).Build();
35 |
36 | // Import the Plugin from the plugins directory.
37 | var pluginsDirectory = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Plugins");
38 | kernel.ImportSemanticFunctionsFromDirectory(pluginsDirectory, "WriterPlugin");
39 |
40 | var planner = new SequentialPlanner(kernel);
41 | var goal = "寫一則關於chatgpt對教育場景影響的臉書貼文,然後翻譯該則貼文為英文.";
42 | var plan = await planner.CreatePlanAsync(goal);
43 |
44 | Console.WriteLine("============ Original plan ====================");
45 |
46 | foreach (var step in plan.Steps)
47 | {
48 | Console.WriteLine($"step : {step.Name}");
49 | }
50 | Console.WriteLine("\n\n");
51 |
52 |
53 | var result = await kernel.RunAsync(plan);
54 | Console.WriteLine("============ Result ====================");
55 | Console.WriteLine(result.GetValue());
56 | }
57 | }
58 | }
--------------------------------------------------------------------------------
/MWC-2023/SequentialPlannerSample/SequentialPlannerSample.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net7.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | Always
17 |
18 |
19 | Always
20 |
21 |
22 | Always
23 |
24 |
25 | Always
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/MWC-2023/TransAndRag/Plugins/QAPlugin/AssistantResults/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "type": "completion",
4 | "description": "Answer any question based on text source",
5 | "completion": {
6 | "max_tokens": 2000,
7 | "temperature": 0.2
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/MWC-2023/TransAndRag/Plugins/QAPlugin/AssistantResults/skprompt.txt:
--------------------------------------------------------------------------------
1 | 這是使用者的提問
2 | ###
3 | {{$query_input}}
4 | ###
5 |
6 | 這是從知識庫所搜尋到的結果
7 | ###
8 | {{$ans_result}}
9 | ###
10 |
11 | 當回應使用者的問題時,請仔細閱讀上面所提供的資料,確保您的回答既簡短又具有針對性。
12 | 如果知識庫沒有可以參考的資料,也請具體回應無參考資料可供回答。
13 | 所有的回應,請思考使用者提問的語言,必須將回答翻譯成使用者的語言,以確保溝通無障礙,在翻譯過程中,都務必保留答案的原始意圖,避免添加或刪除任何可能改變答案意義的內容。
--------------------------------------------------------------------------------
/MWC-2023/TransAndRag/Plugins/QAPlugin/Translate/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "type": "completion",
4 | "description": "If it is not Traditional Chinese, please translate it into Traditional Chinese.",
5 | "completion": {
6 | "max_tokens": 2000,
7 | "temperature": 0.2
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/MWC-2023/TransAndRag/Plugins/QAPlugin/Translate/skprompt.txt:
--------------------------------------------------------------------------------
1 | 請你先分析以下文字的語言,如果是繁體中文就維持原內容,如果是其它語言,please translator to zh-tw
2 | ###
3 | {{$query_input}}
4 | ###
5 |
--------------------------------------------------------------------------------
/MWC-2023/TransAndRag/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel.Orchestration;
2 | using Microsoft.SemanticKernel.Plugins.Memory;
3 | using Microsoft.SemanticKernel;
4 | using Microsoft.SemanticKernel.Connectors.AI.OpenAI;
5 | using Microsoft.SemanticKernel.Memory;
6 | using System.Globalization;
7 |
8 | namespace TransAndRag
9 | {
10 | internal class Program
11 | {
12 | //AOAI
13 | private const string deploy_Model = "xxx";
14 | private const string embedding_Model = "xxx";
15 | private const string aoai_Endpoint = "https://xxx.openai.azure.com";
16 | private const string api_Key = "xxx";
17 | private const string embedding_CollectionName = "Law";
18 |
19 | //OpenAI
20 | private const string openai_Key = "xxx";
21 | private const string openai_deploy_Model = "gpt-4-1106-preview";
22 |
23 |
24 | static async Task Main(string[] args)
25 | {
26 | //AOAI
27 | //var kernel = new KernelBuilder()
28 | // .WithAzureChatCompletionService(
29 | // deploy_Model, // Azure OpenAI Deployment Name
30 | // aoai_Endpoint, // Azure OpenAI Endpoint
31 | // api_Key // Azure OpenAI Key
32 | // ).Build();
33 |
34 | //OpenAI
35 | var kernel = new KernelBuilder()
36 | .WithOpenAIChatCompletionService(
37 | modelId: openai_deploy_Model, // OpenAI Deployment Name
38 | apiKey: openai_Key // OpenAI Key
39 | ).Build();
40 |
41 |
42 | var memoryWithCustomDb = new MemoryBuilder()
43 | .WithAzureTextEmbeddingGenerationService(embedding_Model, aoai_Endpoint, api_Key)
44 | .WithMemoryStore(new VolatileMemoryStore())
45 | .Build();
46 |
47 | //Init KM
48 | await ImportKm(memoryWithCustomDb);
49 |
50 | // Import the Plugin from the plugins directory.
51 | var pluginsDirectory = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Plugins");
52 |
53 | var qaPlugin = "QAPlugin";
54 | kernel.ImportSemanticFunctionsFromDirectory(pluginsDirectory, qaPlugin);
55 | var transFun = kernel.Functions.GetFunction(qaPlugin, "Translate");
56 | var assistantResultsFun = kernel.Functions.GetFunction(qaPlugin, "AssistantResults");
57 |
58 |
59 | while (true)
60 | {
61 | Console.WriteLine("bot: 您好,您想問什麼呢? ( What can I help you with? ) \n");
62 | Console.Write("you: ");
63 |
64 | /*
65 | query sample case
66 | 1.永久保存的機關檔案可以做為公開資料嗎?
67 | 2.파일을 해외로 배송하는 데 제한이 있나요? (要把檔案運到國外,有什麼限制嗎)
68 | 3.公文書法で規制される内容とは何ですか? (檔案法所規範的內容是指哪些)
69 | 4.Can permanently preserved agency files be turned into public information?
70 | */
71 |
72 |
73 | var query = Console.ReadLine();
74 | Console.Write("\n");
75 |
76 | if (string.Compare(query, "exit", true) == 0)
77 | {
78 | break;
79 | }
80 |
81 | if (string.IsNullOrEmpty(query))
82 | {
83 | return;
84 | }
85 |
86 | //自動翻譯
87 | var transQuery = await kernel.RunAsync(transFun, new ContextVariables() { { "query_input", query } });
88 |
89 |
90 | //RAG Search
91 | var searchResult = memoryWithCustomDb
92 | .SearchAsync(embedding_CollectionName, transQuery.GetValue(), minRelevanceScore: 0.8);
93 |
94 | var ans = string.Empty;
95 |
96 | await foreach (var kmResult in searchResult)
97 | {
98 | ans += $"{kmResult.Metadata.Text}\n\n";
99 | }
100 |
101 | //return
102 | var assistantResult = await kernel.RunAsync(assistantResultsFun, new ContextVariables() { { "query_input", query }, { "ans_result", ans } });
103 | Console.WriteLine($"bot: {assistantResult.GetValue()} \n \n");
104 |
105 | }
106 | }
107 |
108 | private static async Task ImportKm(ISemanticTextMemory memoryBuilder)
109 | {
110 | //知識庫轉存向量儲存
111 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第1條", text: "本細則依檔案法(以下簡稱本法)第二十九條規定訂定之。");
112 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第2條第1項", text: "本法第二條第二款所稱管理程序,指依文書處理或機關業務相關法令規定,完成核定、發文或辦結之程序。");
113 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第2條第2項", text: "本法第二條第二款所稱文字或非文字資料及其附件,指各機關處理公務或因公務而產生之各類紀錄資料及其附件,包括各機關所持有或保管之文書、圖片、紀錄、照片、錄影(音)、微縮片、電腦處理資料等,可供聽、讀、閱覽或藉助科技得以閱覽或理解之文書或物品。");
114 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第3條", text: "各機關管理檔案,應依本法第四條規定,並參照檔案中央主管機關訂定之機關檔案管理單位及人員配置基準,設置或指定專責單位或人員。");
115 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第4條第1項", text: "各機關依本法第五條規定,經該管機關核准,將檔案運往國外者,應先以微縮、電子或其他方式儲存,並經管理該檔案機關首長核定。");
116 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第4條第2項", text: "前項檔案如屬永久保存之機關檔案,並應經檔案中央主管機關同意。");
117 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第5條", text: "各機關依本法第六條第二項規定,將檔案中之器物交有關機構保管時,應訂定書面契約或作成紀錄存查。");
118 | }
119 | }
120 | }
--------------------------------------------------------------------------------
/MWC-2023/TransAndRag/TransAndRag.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net7.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 | Always
18 |
19 |
20 | Always
21 |
22 |
23 | Always
24 |
25 |
26 | Always
27 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/MWC-2023/WebSearch/Plugins/QAPlugin/AssistantResults/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "type": "completion",
4 | "description": "Answer any question based on text source",
5 | "completion": {
6 | "max_tokens": 2000,
7 | "temperature": 0.2
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/MWC-2023/WebSearch/Plugins/QAPlugin/AssistantResults/skprompt.txt:
--------------------------------------------------------------------------------
1 | 這是從外部來源所搜尋到的結果
2 | ###
3 | {{$ans_result}}
4 | ###
5 |
6 | 請根據上述資料,回答使用者的問題,並且附上參考來源
7 | 問題:{{$query_input}}
8 | 答案:
9 |
--------------------------------------------------------------------------------
/MWC-2023/WebSearch/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 | using Microsoft.SemanticKernel.AI.ChatCompletion;
3 | using Microsoft.SemanticKernel.Connectors.AI.OpenAI.ChatCompletion;
4 | using Microsoft.SemanticKernel.Orchestration;
5 | using Microsoft.SemanticKernel.Plugins.Web;
6 | using Microsoft.SemanticKernel.Plugins.Web.Bing;
7 | using static System.Runtime.InteropServices.JavaScript.JSType;
8 | //using Microsoft.SemanticKernel.Skills.Web.Google;
9 |
10 | namespace WebSearch
11 | {
12 | internal class Program
13 | {
14 | //AOAI
15 | private const string deploy_Model = "xxx";
16 | private const string aoai_Endpoint = "https://xxx.openai.azure.com";
17 | private const string api_Key = "xxx";
18 | private const string bingSerach_Key = "xxx";
19 |
20 | //OpenAI
21 | private const string openai_Key = "xxx";
22 | private const string openai_deploy_Model = "gpt-4-1106-preview";
23 |
24 | static async Task Main(string[] args)
25 | {
26 | //Azure OpenAI
27 | //var kernel = new KernelBuilder()
28 | // .WithAzureChatCompletionService(
29 | // deploy_Model, // Azure OpenAI Deployment Name
30 | // aoai_Endpoint, // Azure OpenAI Endpoint
31 | // api_Key // Azure OpenAI Key
32 | // ).Build();
33 |
34 |
35 | //OpenAI
36 | var kernel = new KernelBuilder()
37 | .WithOpenAIChatCompletionService(
38 | modelId: openai_deploy_Model, // OpenAI Deployment Name
39 | apiKey: openai_Key // OpenAI Key
40 | ).Build();
41 |
42 |
43 | // Connector
44 | var searchPluginName = "bing";
45 | var bingConnector = new BingConnector(bingSerach_Key);
46 | kernel.ImportFunctions(new WebSearchEnginePlugin(bingConnector), searchPluginName);
47 |
48 | // Import the semantic function from the plugins directory.
49 | var qaPlugin = "QAPlugin";
50 | var pluginsDirectory = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Plugins");
51 | kernel.ImportSemanticFunctionsFromDirectory(pluginsDirectory, qaPlugin);
52 | var assistantResultsFun = kernel.Functions.GetFunction(qaPlugin, "AssistantResults");
53 |
54 | string question = string.Empty;
55 | while (true)
56 | {
57 | Console.WriteLine("bot: 你想問什麼事情呢? (結束請輸入exit) \n");
58 | Console.Write("you: ");
59 | question = Console.ReadLine();
60 | Console.Write("\n");
61 |
62 | if (question.ToLower() == "exit")
63 | {
64 | break;
65 | }
66 |
67 | var searchFun = kernel.Functions.GetFunction(searchPluginName, "search");
68 | var searchResult = await kernel.RunAsync(question, searchFun);
69 |
70 | //return
71 | var assistantResult = await kernel.RunAsync(assistantResultsFun, new ContextVariables() { { "query_input", question }, { "ans_result", searchResult.ToString() } });
72 | Console.WriteLine($"bot: {assistantResult.GetValue()} \n \n");
73 | }
74 | }
75 | }
76 | }
--------------------------------------------------------------------------------
/MWC-2023/WebSearch/WebSearch.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net7.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | Always
17 |
18 |
19 | Always
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/MixSemanticFunAndNativeFun/MixSemanticFunAndNativeFun.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net7.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | Always
17 |
18 |
19 | Always
20 |
21 |
22 | Always
23 |
24 |
25 | Always
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/MixSemanticFunAndNativeFun/Plugins/CrmPlugin/Customer.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 | using Microsoft.SemanticKernel.Orchestration;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.ComponentModel;
6 | using System.Linq;
7 | using System.Text;
8 | using System.Threading.Tasks;
9 |
10 | namespace MixSemanticFunAndNativeFun.Plugins.CrmPlugin
11 | {
12 | public class Customer
13 | {
14 | [SKFunction, Description("取得客戶連絡人")]
15 | public string GetCustomerContact(string cusCode)
16 | {
17 | //撰寫從CRM DataBase 取得客戶連絡人資料邏輯
18 | //do something
19 | return $"陳伊恩({cusCode})";
20 | }
21 |
22 | [SKFunction, Description("根據客戶代碼及區域,取得客戶連絡人")]
23 | public string GetCustomerContactV2(SKContext context)
24 | {
25 | //撰寫從CRM DataBase 取得客戶連絡人資料邏輯
26 | //do something
27 | return $"{context.Variables["CusCode"]}-{context.Variables["Area"]} 陳伊恩";
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/MixSemanticFunAndNativeFun/Plugins/WriterPlugin/Email/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "type": "completion",
4 | "description": "產生Email",
5 | "completion": {
6 | "max_tokens": 2000,
7 | "temperature": 0.2,
8 | "top_p": 0.0,
9 | "presence_penalty": 0.0,
10 | "frequency_penalty": 0.0
11 | },
12 | "input": {
13 | "parameters": [
14 | {
15 | "name": "CusCode",
16 | "description": "客戶編號",
17 | "defaultValue": ""
18 | }
19 | ]
20 | }
21 | }
--------------------------------------------------------------------------------
/MixSemanticFunAndNativeFun/Plugins/WriterPlugin/Email/skprompt.txt:
--------------------------------------------------------------------------------
1 | 你是一位行政助理,負責處理我所交辧的文書作業任務
2 | 現在,請幫我寫一封信給底下的客戶,內容是關於下星期一開始我將休假一個月,有任何緊急事項,可以連繫公司代理人。
3 | 請產生email內容,不要廢話,使用 #zh-tw
4 |
5 | """
6 | {{CrmPlugin.GetCustomerContact $CusCode}}
7 | """
8 |
--------------------------------------------------------------------------------
/MixSemanticFunAndNativeFun/Plugins/WriterPlugin/Email2/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "type": "completion",
4 | "description": "產生Email",
5 | "completion": {
6 | "max_tokens": 2000,
7 | "temperature": 0.2,
8 | "top_p": 0.0,
9 | "presence_penalty": 0.0,
10 | "frequency_penalty": 0.0
11 | },
12 | "input": {
13 | "parameters": [
14 | {
15 | "name": "CusCode",
16 | "description": "客戶編號",
17 | "defaultValue": ""
18 | }
19 | ]
20 | }
21 | }
--------------------------------------------------------------------------------
/MixSemanticFunAndNativeFun/Plugins/WriterPlugin/Email2/skprompt.txt:
--------------------------------------------------------------------------------
1 | 你是一位行政助理,負責處理我所交辧的文書作業任務
2 | 現在,請幫我寫一封信給
3 | """
4 | {{CrmPlugin.GetCustomerContactV2}}
5 | """
6 | 內容是下星期1開始我將休假1個月,有任何緊急事項,可以連繫公司代理人
--------------------------------------------------------------------------------
/MixSemanticFunAndNativeFun/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 | using Microsoft.SemanticKernel.Orchestration;
3 |
4 | namespace MixSemanticFunAndNativeFun
5 | {
6 | internal class Program
7 | {
8 | //OpenAI
9 | private const string openai_Key = "xxx";
10 | private const string openai_deploy_Model = "gpt-4-1106-preview";
11 |
12 | static async Task Main(string[] args)
13 | {
14 | //OpenAI
15 | var kernel = new KernelBuilder()
16 | .WithOpenAIChatCompletionService(
17 | modelId: openai_deploy_Model, // OpenAI Deployment Name
18 | apiKey: openai_Key // OpenAI Key
19 | ).Build();
20 |
21 | await WriteEmail(kernel);
22 | //await WriteEmail2(kernel);
23 |
24 | }
25 |
26 | //semantic function調用native function範例
27 | private static async Task WriteEmail(IKernel kernel)
28 | {
29 | // Load native plugin into the kernel function collection
30 | // Functions loaded here are available as "CrmPlugin.*"
31 | var crmPlugin = kernel.ImportFunctions(new Plugins.CrmPlugin.Customer(), "CrmPlugin");
32 |
33 | var writePlugin = "WriterPlugin";
34 | var pluginsDirectory = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Plugins");
35 | kernel.ImportSemanticFunctionsFromDirectory(pluginsDirectory, writePlugin);
36 | var emailFun = kernel.Functions.GetFunction(writePlugin, "Email");
37 |
38 | // Show the result
39 | Console.WriteLine("========= Semantic Function result ======================");
40 | var emailResult = await kernel.RunAsync(emailFun, new ContextVariables() { { "CusCode", "C2023001" } });
41 |
42 | Console.WriteLine(emailResult.GetValue());
43 | }
44 |
45 | //native function 傳遞多個參數範例(共享上下文SKContext)
46 | private static async Task WriteEmail2(IKernel kernel)
47 | {
48 | // Load native plugin into the kernel function collection
49 | // Functions loaded here are available as "CrmPlugin.*"
50 | var crmPlugin = kernel.ImportSkill(new Plugins.CrmPlugin.Customer(), "CrmPlugin");
51 |
52 | // Import the Plugin from the plugins directory.
53 | var pluginsDirectory = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Plugins");
54 | var writePlugin = kernel.ImportSemanticSkillFromDirectory(pluginsDirectory, "WriterPlugin");
55 | var contextVars = new ContextVariables()
56 | {
57 | ["CusCode"] = "C2023001",
58 | ["Area"] = "KH"
59 | };
60 |
61 |
62 | // Show the result
63 | Console.WriteLine("--- Semantic Function result");
64 | var result = await kernel.RunAsync(contextVars, writePlugin["Email2"]);
65 | Console.WriteLine(result);
66 | }
67 | }
68 | }
--------------------------------------------------------------------------------
/MultiChatCompletionSample/MultiChatCompletionSample.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net7.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/MultiChatCompletionSample/Program.cs:
--------------------------------------------------------------------------------
1 | using Azure.AI.OpenAI;
2 | using Microsoft.SemanticKernel.AI.ChatCompletion;
3 | using Microsoft.SemanticKernel.Connectors.AI.OpenAI;
4 | using Microsoft.SemanticKernel.Connectors.AI.OpenAI.ChatCompletion;
5 |
6 | namespace MultiChatCompletionSample
7 | {
8 | internal class Program
9 | {
10 | private const string deploy_model = "xxx";
11 | private const string aoai_Endpoint = "https://xxx.openai.azure.com";
12 | private const string api_Key = "xxxx";
13 |
14 |
15 | static async Task Main(string[] args)
16 | {
17 | var chatCompletion = new AzureChatCompletion(
18 | deploy_model, // Azure OpenAI Deployment Name
19 | aoai_Endpoint, // Azure OpenAI Endpoint
20 | api_Key // Azure OpenAI Key
21 | );
22 |
23 | var requestSettings = new OpenAIRequestSettings()
24 | {
25 | MaxTokens = 1024,
26 | FrequencyPenalty = 0,
27 | PresencePenalty = 0,
28 | Temperature = 0.2,
29 | TopP = 0.5
30 | };
31 |
32 | var chatHistory = chatCompletion.CreateNewChat("你是一位自然語言人工智慧研究專家");
33 | chatHistory.AddUserMessage("ChatGPT與過去的自然語言模型有什麼不同,舉個簡單的例子說明");
34 |
35 | foreach (IChatResult chatCompletionResult in await chatCompletion.GetChatCompletionsAsync(chatHistory, requestSettings))
36 | {
37 | ChatMessageBase chatMessage = await chatCompletionResult.GetChatMessageAsync();
38 | chatHistory.Add(chatMessage); //加入對話歷程
39 | Console.WriteLine($"Completions : {chatMessage.Content.ToString()}"); //生成結果
40 | }
41 |
42 | Console.WriteLine();
43 | Console.WriteLine();
44 | Console.WriteLine("---- chatHistory ------");
45 | foreach (var message in chatHistory.Messages)
46 | {
47 | Console.WriteLine($"{message.Role}: {message.Content}");
48 | }
49 | Console.WriteLine();
50 | }
51 | }
52 | }
--------------------------------------------------------------------------------
/NativeFunctionSample/NativeFunctionSample.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net7.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | Always
17 |
18 |
19 | Always
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/NativeFunctionSample/Plugins/CrmPlugin/Customer.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel.SkillDefinition;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.ComponentModel;
5 | using System.Linq;
6 | using System.Text;
7 | using System.Threading.Tasks;
8 |
9 | namespace NativeFunctionSample.Plugins.CrmPlugin
10 | {
11 | public class Customer
12 | {
13 | [SKFunction, Description("取得客戶連絡人")]
14 | public string GetCustomerContact(string cusCode)
15 | {
16 | //撰寫從CRM DataBase 取得客戶連絡人資料邏輯
17 | //do something
18 | return $"居匹踢";
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/NativeFunctionSample/Plugins/WriterPlugin/Email/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "type": "completion",
4 | "description": "產生Email",
5 | "completion": {
6 | "max_tokens": 2000,
7 | "temperature": 0.2,
8 | "top_p": 0.0,
9 | "presence_penalty": 0.0,
10 | "frequency_penalty": 0.0
11 | },
12 | "input": {
13 | "parameters": [
14 | {
15 | "name": "Input",
16 | "description": "客戶姓名",
17 | "defaultValue": ""
18 | }
19 | ]
20 | }
21 | }
--------------------------------------------------------------------------------
/NativeFunctionSample/Plugins/WriterPlugin/Email/skprompt.txt:
--------------------------------------------------------------------------------
1 | 你是一位行政助理,負責處理我所交辧的文書作業任務
2 | 現在,請幫我寫一封信給
3 | """
4 | {{$input}}
5 | """
6 | 內容是下星期1開始我將休假1個月,有任何緊急事項,可以連繫公司代理人
--------------------------------------------------------------------------------
/NativeFunctionSample/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel.Orchestration;
2 | using Microsoft.SemanticKernel;
3 | using Azure.Core;
4 |
5 | namespace NativeFunctionSample
6 | {
7 | internal class Program
8 | {
9 | private const string deploy_model = "xxx";
10 | private const string aoai_Endpoint = "https://xxx.openai.azure.com";
11 | private const string api_Key = "xxxx";
12 |
13 | static async Task Main(string[] args)
14 | {
15 | var kernel = new KernelBuilder()
16 | .WithAzureChatCompletionService(
17 | deploy_model, // Azure OpenAI Deployment Name
18 | aoai_Endpoint, // Azure OpenAI Endpoint
19 | api_Key // Azure OpenAI Key
20 | ).Build();
21 |
22 | await Sample1Async(kernel);
23 |
24 | //await Sample2Async(kernel);
25 | }
26 |
27 | static async Task Sample1Async(IKernel kernel)
28 | {
29 | // Import the Plugin .
30 | var crmPlugin = kernel.ImportSkill(new Plugins.CrmPlugin.Customer(), "CrmPlugin");
31 |
32 | // 經由Native Function取得指定客戶編號的連絡人姓名
33 | var cusContactName = await kernel.RunAsync("C2023001", crmPlugin["GetCustomerContact"]);
34 |
35 | Console.WriteLine(cusContactName);
36 | }
37 |
38 | static async Task Sample2Async(IKernel kernel)
39 | {
40 | // Import the Plugin .
41 | var crmPlugin = kernel.ImportSkill(new Plugins.CrmPlugin.Customer(), "CrmPlugin");
42 |
43 | // Import the Plugin from the plugins directory.
44 | var pluginsDirectory = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Plugins");
45 | var plugin = kernel.ImportSemanticSkillFromDirectory(pluginsDirectory, "WriterPlugin");
46 |
47 | //調用CrmPlugin/GetCustomerContact function拿到客戶姓名
48 | var getCusContact = kernel.Skills.GetFunction("CrmPlugin", "GetCustomerContact");
49 | string cusContact = (await kernel.RunAsync("C2023001", getCusContact)).Result;
50 |
51 | //調用WriterPlugin/Email function寫email內容
52 | var writeEmail = kernel.Skills.GetFunction("WriterPlugin", "Email");
53 | string email = (await kernel.RunAsync(cusContact, writeEmail)).Result;
54 |
55 |
56 | Console.WriteLine(email);
57 | }
58 | }
59 | }
--------------------------------------------------------------------------------
/NatvieFunctions/NatvieFunctions.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net7.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | Always
17 |
18 |
19 | Always
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/NatvieFunctions/Plugins/QAPlugin/AssistantResults/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "type": "completion",
4 | "description": "Answer any question based on text source",
5 | "completion": {
6 | "max_tokens": 2000,
7 | "temperature": 0.2
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/NatvieFunctions/Plugins/QAPlugin/AssistantResults/skprompt.txt:
--------------------------------------------------------------------------------
1 | 這是從外部來源所搜尋到的結果
2 | ###
3 | {{$ans_result}}
4 | ###
5 |
6 | 請根據上述資料,回答使用者的問題,並且附上參考來源
7 | 問題:{{$query_input}}
8 | 答案:
9 |
--------------------------------------------------------------------------------
/NatvieFunctions/Program.cs:
--------------------------------------------------------------------------------
1 | namespace NatvieFunctions
2 | {
3 | internal class Program
4 | {
5 | static void Main(string[] args)
6 | {
7 | Console.WriteLine("Hello, World!");
8 | }
9 | }
10 | }
--------------------------------------------------------------------------------
/NetConf2023.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/iangithub/sklearn/84b3a565b6fc20e7762ebc837b5b4244152e2000/NetConf2023.zip
--------------------------------------------------------------------------------
/NetConf2023/01-GetStart/01-GetStart.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net8.0
6 | _01_GetStart
7 | enable
8 | enable
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/NetConf2023/01-GetStart/Plugins/Chat.yaml:
--------------------------------------------------------------------------------
1 | name: Chat
2 | template: |
3 | 你是一位萬事通助理,根據使用者的提問來回答問題,請一律使用 #zh-tw 回答
4 |
5 | {{#each messages}}
6 | {{~Content~}}
7 | {{/each}}
8 | template_format: handlebars
9 | description: 使用聊天歷史來回應用戶的功能
10 | input_variables:
11 | - name: messages
12 | description: 聊天歷史
13 | is_required: true
14 | execution_settings:
15 | service1:
16 | model_id: gpt-4
17 | temperature: 0.6
18 | service2:
19 | model_id: gpt-3
20 | temperature: 0.4
21 | default:
22 | temperature: 0.5
23 |
--------------------------------------------------------------------------------
/NetConf2023/01-GetStart/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 | using Microsoft.VisualBasic;
3 | using System.Reflection;
4 | using Newtonsoft.Json;
5 | using Microsoft.SemanticKernel.PromptTemplates.Handlebars;
6 | using Microsoft.SemanticKernel.ChatCompletion;
7 | using Microsoft.SemanticKernel.Connectors.OpenAI;
8 |
9 | string Gpt4DeploymentName = "xxx";
10 | string Gpt4ModelId = "xxx";
11 | string AzureOpenAIEndpoint = "https://xxx.openai.azure.com/";
12 | string AzureOpenAIApiKey = "xxx";
13 | string currentDirectory = Directory.GetCurrentDirectory();
14 |
15 | Kernel kernel = Kernel.CreateBuilder()
16 | .AddAzureOpenAIChatCompletion(
17 | deploymentName: Gpt4DeploymentName,
18 | endpoint: AzureOpenAIEndpoint,
19 | apiKey: AzureOpenAIApiKey,
20 | modelId: Gpt4ModelId)
21 | .Build();
22 |
23 | // Load prompt from resource
24 | using StreamReader reader = new(Path.Combine(currentDirectory, "Plugins", "Chat.yaml"));
25 | KernelFunction prompt = kernel.CreateFunctionFromPromptYaml(
26 | reader.ReadToEnd(),
27 | promptTemplateFactory: new HandlebarsPromptTemplateFactory()
28 | );
29 |
30 |
31 | // #pragma warning disable SKEXP0004
32 | // kernel.PromptRendered += (sender, args) =>
33 | // {
34 | // Console.WriteLine("=========== PromptRendered Start ===========");
35 | // Console.WriteLine(args.RenderedPrompt);
36 | // Console.WriteLine("=========== PromptRendered End ===========\n\n");
37 |
38 | // };
39 | // #pragma warning restore SKEXP0004
40 |
41 |
42 | ChatHistory chatMessages = [];
43 |
44 |
45 | while (true)
46 | {
47 | // Get user input
48 | System.Console.Write("User > ");
49 | chatMessages.AddUserMessage(Console.ReadLine()!);
50 |
51 | // Enable auto invocation of kernel functions
52 | OpenAIPromptExecutionSettings openAIPromptExecutionSettings = new()
53 | {
54 | ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions
55 | };
56 |
57 | // Get the chat completions
58 | var result = kernel.InvokeStreamingAsync(
59 | prompt,
60 | arguments: new(openAIPromptExecutionSettings) {
61 | { "messages", chatMessages }
62 | });
63 |
64 |
65 | ChatMessageContent? chatMessageContent = null;
66 |
67 | await foreach (var content in result)
68 | {
69 | System.Console.Write(content);
70 | if (chatMessageContent == null)
71 | {
72 | System.Console.Write("Assistant > ");
73 | chatMessageContent = new ChatMessageContent(
74 | content.Role ?? AuthorRole.Assistant,
75 | content.ModelId!,
76 | content.Content!,
77 | content.InnerContent,
78 | content.Encoding,
79 | content.Metadata);
80 | }
81 | else
82 | {
83 | chatMessageContent.Content += content;
84 | }
85 | }
86 | System.Console.WriteLine("\n");
87 |
88 | chatMessages.Add(chatMessageContent!);
89 | }
--------------------------------------------------------------------------------
/NetConf2023/02-NativeFunc/02-NativeFunc.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net8.0
6 | _02_NativeFunc
7 | enable
8 | enable
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/NetConf2023/02-NativeFunc/Plugins/ChatPlugin/Chat.yaml:
--------------------------------------------------------------------------------
1 | name: Chat
2 | template: |
3 | 你是一位萬事通助理,根據使用者的提問來回答問題,請一律使用 #zh-tw 回答
4 |
5 | {{#each messages}}
6 | {{~Content~}}
7 | {{/each}}
8 | template_format: handlebars
9 | description: 使用聊天歷史來回應用戶的功能
10 | input_variables:
11 | - name: messages
12 | description: 聊天歷史
13 | is_required: true
14 | execution_settings:
15 | service1:
16 | model_id: gpt-4
17 | temperature: 0.6
18 | service2:
19 | model_id: gpt-3
20 | temperature: 0.4
21 | default:
22 | temperature: 0.5
23 |
--------------------------------------------------------------------------------
/NetConf2023/02-NativeFunc/Plugins/DateTimePlugin/DateTimePlugin.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 | using Microsoft.SemanticKernel;
3 |
4 | namespace MyPlugins;
5 |
6 | internal class DataTimePlugin
7 | {
8 | [KernelFunction("GetCurrentDateTime")]
9 | [Description("Get the current date and time.'")]
10 | public string GetCurrentDateTime()
11 | {
12 | return DateTime.Now.ToString();
13 | }
14 | }
--------------------------------------------------------------------------------
/NetConf2023/02-NativeFunc/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 | using Microsoft.VisualBasic;
3 | using System.Reflection;
4 | using Newtonsoft.Json;
5 | using Microsoft.SemanticKernel.PromptTemplates.Handlebars;
6 | using Microsoft.SemanticKernel.ChatCompletion;
7 | using Microsoft.SemanticKernel.Connectors.OpenAI;
8 | using MyPlugins;
9 |
10 | string Gpt4DeploymentName = "xxx";
11 | string Gpt4ModelId = "xxx";
12 | string AzureOpenAIEndpoint = "https://xxx.openai.azure.com/";
13 | string AzureOpenAIApiKey = "xxx";
14 | string currentDirectory = Directory.GetCurrentDirectory();
15 |
16 | Kernel kernel = Kernel.CreateBuilder()
17 | .AddAzureOpenAIChatCompletion(
18 | deploymentName: Gpt4DeploymentName,
19 | modelId: Gpt4ModelId,
20 | endpoint: AzureOpenAIEndpoint,
21 | apiKey: AzureOpenAIApiKey)
22 | .Build();
23 |
24 | // Load prompt from resource
25 | using StreamReader reader = new(Path.Combine(currentDirectory, "Plugins", "ChatPlugin", "Chat.yaml"));
26 | KernelFunction prompt = kernel.CreateFunctionFromPromptYaml(
27 | reader.ReadToEnd(),
28 | promptTemplateFactory: new HandlebarsPromptTemplateFactory()
29 | );
30 |
31 | //Load Plugins
32 | kernel.Plugins.AddFromType();
33 |
34 |
35 | #pragma warning disable SKEXP0004
36 |
37 | kernel.PromptRendered += (sender, args) =>
38 | {
39 | Console.WriteLine("=========== PromptRendered Start ===========");
40 | Console.WriteLine(args.RenderedPrompt);
41 | Console.WriteLine("=========== PromptRendered End ===========\n\n");
42 | };
43 |
44 |
45 | kernel.FunctionInvoking += (sender, args) =>
46 | {
47 | Console.WriteLine("=========== FunctionInvoking Start ===========");
48 | Console.WriteLine(args.Function.Name);
49 | Console.WriteLine("=========== FunctionInvoking End ===========\n\n");
50 |
51 | };
52 |
53 | #pragma warning restore SKEXP0004
54 |
55 |
56 | // Create the chat history
57 | ChatHistory chatMessages = [];
58 |
59 | while (true)
60 | {
61 | // Get user input
62 | System.Console.Write("User > ");
63 | var userMessage = Console.ReadLine()!;
64 | chatMessages.AddUserMessage(userMessage);
65 |
66 | // Enable auto invocation of kernel functions
67 | OpenAIPromptExecutionSettings openAIPromptExecutionSettings = new()
68 | {
69 | ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions
70 | };
71 |
72 | var result = kernel.InvokeStreamingAsync(
73 | prompt,
74 | arguments: new(openAIPromptExecutionSettings) {
75 | { "messages", chatMessages }
76 | });
77 |
78 | // Print the chat completions
79 | ChatMessageContent? chatMessageContent = null;
80 |
81 | await foreach (var content in result)
82 | {
83 | System.Console.Write(content);
84 | if (chatMessageContent == null)
85 | {
86 | System.Console.Write("Assistant > ");
87 | chatMessageContent = new ChatMessageContent(
88 | content.Role ?? AuthorRole.Assistant,
89 | content.ModelId!,
90 | content.Content!,
91 | content.InnerContent,
92 | content.Encoding,
93 | content.Metadata);
94 | }
95 | else
96 | {
97 | chatMessageContent.Content += content;
98 | }
99 | }
100 | System.Console.WriteLine("\n");
101 |
102 | chatMessages.Add(chatMessageContent!);
103 |
104 | }
105 |
--------------------------------------------------------------------------------
/NetConf2023/03-MultiSemanticFuncs/03-MultiSemanticFuncs.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net8.0
6 | _03_SequentialPlanner
7 | enable
8 | enable
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/NetConf2023/03-MultiSemanticFuncs/Plugins/TranslatePlugin/Translate.yaml:
--------------------------------------------------------------------------------
1 | name: Translate
2 | template: |
3 | 翻譯下列內容成為英文,並輸出原始中文資料及翻譯後的英文資料都要顯示出來,中英文內容分隔2行
4 | {{$postcontent}}
5 | template_format: semantic-kernel
6 | description: 根據使用者提供的內容,翻譯成英文
7 | input_variables:
8 | - name: postcontent
9 | description: 使用者提供的內容
10 | is_required: true
11 | execution_settings:
12 | service1:
13 | model_id: gpt-4
14 | temperature: 0.6
15 |
--------------------------------------------------------------------------------
/NetConf2023/03-MultiSemanticFuncs/Plugins/WriterPlugin/Writer.yaml:
--------------------------------------------------------------------------------
1 | name: Writer
2 | template: |
3 | 你是一位facebook小編,撰寫下列主題的貼文,內容200個字以內,#zh-tw
4 | {{$topic}}
5 | template_format: semantic-kernel
6 | description: 根據使用者提供的內容,撰寫facebook貼文
7 | input_variables:
8 | - name: topic
9 | description: 貼文的主題
10 | is_required: true
11 | execution_settings:
12 | service1:
13 | model_id: gpt-4
14 | temperature: 0.6
15 |
--------------------------------------------------------------------------------
/NetConf2023/03-MultiSemanticFuncs/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 | using Microsoft.VisualBasic;
3 | using System.Reflection;
4 | using Newtonsoft.Json;
5 | using Microsoft.SemanticKernel.PromptTemplates.Handlebars;
6 | using Microsoft.SemanticKernel.ChatCompletion;
7 | using Microsoft.SemanticKernel.Connectors.OpenAI;
8 |
9 | string Gpt4DeploymentName = "xxx";
10 | string Gpt4ModelId = "xxx";
11 | string AzureOpenAIEndpoint = "https://xxx.openai.azure.com/";
12 | string AzureOpenAIApiKey = "xxx";
13 | string currentDirectory = Directory.GetCurrentDirectory();
14 |
15 | Kernel kernel = Kernel.CreateBuilder()
16 | .AddAzureOpenAIChatCompletion(
17 | deploymentName: Gpt4DeploymentName,
18 | endpoint: AzureOpenAIEndpoint,
19 | apiKey: AzureOpenAIApiKey,
20 | modelId: Gpt4ModelId)
21 | .Build();
22 |
23 | // Load prompt from Directory
24 | using StreamReader reader = new(Path.Combine(currentDirectory, "Plugins", "WriterPlugin", "Writer.yaml"));
25 | KernelFunction writerPlugin = kernel.CreateFunctionFromPromptYaml(reader.ReadToEnd());
26 |
27 | using StreamReader reader2 = new(Path.Combine(currentDirectory, "Plugins", "TranslatePlugin", "Translate.yaml"));
28 | KernelFunction transPlugin = kernel.CreateFunctionFromPromptYaml(reader2.ReadToEnd());
29 |
30 | while (true)
31 | {
32 | System.Console.Write("User > ");
33 | var userMessage = Console.ReadLine()!;
34 |
35 | var writerResult = (await kernel.InvokeAsync(writerPlugin, arguments: new()
36 | {
37 | { "topic", userMessage }
38 | })).ToString();
39 |
40 | var finalResult = (await kernel.InvokeAsync(transPlugin, arguments: new()
41 | {
42 | { "topic", userMessage },{ "postcontent", writerResult }
43 | })).ToString();
44 |
45 | System.Console.WriteLine($"Assistant > {finalResult}");
46 | }
47 |
--------------------------------------------------------------------------------
/NetConf2023/04-TransAndRag/Plugins/QAPlugin/AssistantResults/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "description": "Answer any question based on knowledge base source",
4 | "execution_settings": [
5 | {
6 | "max_tokens": 512,
7 | "temperature": 0.2,
8 | "top_p": 0.0,
9 | "presence_penalty": 0.0,
10 | "frequency_penalty": 0.0
11 | }
12 | ],
13 | "input_variables": [
14 | {
15 | "name": "query_input",
16 | "description": "user question",
17 | "default": ""
18 | },
19 | {
20 | "name": "ans_result",
21 | "description": "knowledge base source",
22 | "default": ""
23 | }
24 | ]
25 | }
26 |
--------------------------------------------------------------------------------
/NetConf2023/04-TransAndRag/Plugins/QAPlugin/AssistantResults/skprompt.txt:
--------------------------------------------------------------------------------
1 | 你是一位法規助理,使用者會詢問問題,請你協助回答,並且根據以下原則進行回答。
2 |
3 | 1. 當回應使用者的問題時,請仔細閱讀下面知識庫所提供的參考資料,以確保您的回答既簡短又具有針對性。
4 | 2. 假如沒有知識庫參考資料,就說無法回答,這很重要,一旦亂回答我將會失去我的工作,請你一定要記住。
5 | 3. 所有的回應,請思考使用者提問的語言,必須將回答翻譯成使用者的語言,以確保溝通無障礙,在翻譯過程中,都務必保留答案的原始意圖,避免添加或刪除任何可能改變答案意義的內容。
6 |
7 | #範例1
8 | 使用者提問:我想知道如何申請營業稅
9 | [知識庫參考資料-開始]
10 |
11 | [知識庫參考資料-結束]
12 |
13 | 回答:您好,由於我的知識庫參考資料並未提供相關資訊,因此我無法回答您的問題,謝謝您。
14 |
15 | #範例2
16 | 使用者提問:不禮讓行人罰款多少錢
17 | [知識庫參考資料-開始]
18 | 根據道路交通管理處罰條例第 43 條第 1 項規定,違反第 43 條第 1 項規定者,處新臺幣 300 元以上 600 元以下罰鍰。
19 | [知識庫參考資料-結束]
20 |
21 | 回答:您好,根據道路交通管理處罰條例第 43 條第 1 項規定,處新臺幣 300 元以上 600 元以下罰鍰。
22 |
23 |
24 | 這是使用者的提問
25 | ###
26 | {{$query_input}}
27 | ###
28 |
29 | 這是從知識庫所搜尋到的結果
30 | [知識庫參考資料-開始]
31 | {{$reference_content}}
32 | [知識庫參考資料-結束]
33 |
34 |
--------------------------------------------------------------------------------
/NetConf2023/04-TransAndRag/Plugins/QAPlugin/Translate/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "description": "If it is not Traditional Chinese, please translate it into Traditional Chinese.",
4 | "execution_settings": [
5 | {
6 | "max_tokens": 1000,
7 | "temperature": 0.2,
8 | "top_p": 0.0,
9 | "presence_penalty": 0.0,
10 | "frequency_penalty": 0.0
11 | }
12 | ],
13 | "input_variables": [
14 | {
15 | "name": "query_input",
16 | "description": "user question content",
17 | "default": ""
18 | }
19 | ]
20 | }
21 |
--------------------------------------------------------------------------------
/NetConf2023/04-TransAndRag/Plugins/QAPlugin/Translate/skprompt.txt:
--------------------------------------------------------------------------------
1 | 請你先分析以下文字的語言,如果是繁體中文就維持原內容,如果是其它語言,please translator to zh-tw
2 | ###
3 | {{$query_input}}
4 | ###
5 |
--------------------------------------------------------------------------------
/NetConf2023/04-TransAndRag/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel.Plugins.Memory;
2 | using Microsoft.SemanticKernel;
3 | using Microsoft.SemanticKernel.Connectors.AI.OpenAI;
4 | using Microsoft.SemanticKernel.Memory;
5 | using System.Globalization;
6 | #pragma warning disable SKEXP0052
7 | #pragma warning disable SKEXP0011
8 | #pragma warning disable SKEXP0026
9 | #pragma warning disable SKEXP0003
10 |
11 | namespace TransAndRag
12 | {
13 | internal class Program
14 | {
15 |
16 | //AOAI
17 | private const string deploy_Model = "xxx";
18 | private const string gpt4ModelId = "xxx";
19 | private const string aoai_Endpoint = "https://xxx.openai.azure.com";
20 | private const string api_Key = "xxx";
21 | private const string embedding_DeploymentName = "xxx";
22 | private const string embedding_ModelId = "xxx";
23 | private const string embedding_CollectionName = "Law";
24 |
25 | static async Task Main(string[] args)
26 | {
27 | //AOAI
28 | var kernel = new KernelBuilder()
29 | .AddAzureOpenAIChatCompletion(
30 | deploymentName: deploy_Model,
31 | modelId: gpt4ModelId,
32 | endpoint: aoai_Endpoint,
33 | apiKey: api_Key)
34 | .Build();
35 |
36 | var memoryWithCustomDb = new MemoryBuilder()
37 | .WithAzureOpenAITextEmbeddingGeneration(embedding_DeploymentName, embedding_ModelId, aoai_Endpoint, api_Key)
38 | .WithMemoryStore(new VolatileMemoryStore())
39 | .Build();
40 |
41 | //Init KM
42 | await ImportKm(memoryWithCustomDb);
43 |
44 | // Import the Plugin from the plugins directory.
45 | var pluginsDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Plugins");
46 | var plugin = kernel.ImportPluginFromPromptDirectory(Path.Combine(pluginsDirectory, "QAPlugin"));
47 | KernelFunction assistantResultsFun = plugin["AssistantResults"];
48 | KernelFunction transFun = plugin["Translate"];
49 |
50 | #region show kernel plugins and functions
51 | // var functions = kernel.Plugins.GetFunctionsMetadata();
52 | // Console.WriteLine("*****************************************");
53 | // Console.WriteLine("****** Registered plugins and functions ******");
54 | // Console.WriteLine("*****************************************");
55 | // Console.WriteLine();
56 | // foreach (KernelFunctionMetadata func in functions)
57 | // {
58 | // Console.WriteLine($"func_Name > {func.Name}, func_Description > {func.Description}");
59 | // if (func.Parameters.Count > 0)
60 | // {
61 | // Console.WriteLine("func_Params > ");
62 | // foreach (var p in func.Parameters)
63 | // {
64 | // Console.WriteLine($"Parameter_Name > {p.Name}: {p.Description}");
65 | // Console.WriteLine($"Parameter_DefaultValue > '{p.DefaultValue}'");
66 | // }
67 | // }
68 | // }
69 | // Console.WriteLine("=========================================\n\n");
70 | #endregion
71 |
72 | while (true)
73 | {
74 | Console.WriteLine("Assistant > 您好,您想問什麼呢? ( What can I help you with? ) \n");
75 | Console.Write("User > ");
76 |
77 | var query = Console.ReadLine();
78 | Console.Write("\n");
79 |
80 | if (string.Compare(query, "exit", true) == 0)
81 | {
82 | Console.WriteLine("Assistant > bye........");
83 | break;
84 | }
85 |
86 | if (string.IsNullOrEmpty(query))
87 | {
88 | return;
89 | }
90 |
91 | //自動翻譯
92 | var transQuery = (await kernel.InvokeAsync(transFun, arguments: new()
93 | {{"query_input", query }})).ToString();
94 |
95 | //RAG Search
96 | var searchResult = memoryWithCustomDb
97 | .SearchAsync(embedding_CollectionName, transQuery, minRelevanceScore: 0.8);
98 |
99 | var refContent = string.Empty;
100 |
101 | await foreach (var kmResult in searchResult)
102 | {
103 | refContent += $"{kmResult.Metadata.Text}\n\n";
104 | }
105 |
106 | #region show kernel prompt render
107 |
108 | // kernel.PromptRendering += (sender, e) =>
109 | // {
110 | // Console.WriteLine("========== Prompt Rendering Start ================");
111 | // Console.WriteLine($"Function.Name => {e.Function.Name} ");
112 | // Console.WriteLine("========== Prompt Rendering End ================");
113 |
114 | // };
115 |
116 | // kernel.PromptRendered += (sender, e) =>
117 | // {
118 | // Console.WriteLine("========== Prompt Rendering Start ================");
119 | // Console.WriteLine($"RenderedPrompt => {e.RenderedPrompt} ");
120 | // Console.WriteLine("========== Prompt Rendering End ================");
121 | // };
122 |
123 | #endregion
124 |
125 | //return
126 | var assistantResult = await kernel.InvokeAsync(assistantResultsFun, arguments: new() { { "query_input", query }, { "reference_content", refContent } });
127 |
128 | Console.WriteLine($"Assistant > {assistantResult.GetValue()} \n \n");
129 | }
130 | }
131 |
132 | private static async Task ImportKm(ISemanticTextMemory memoryBuilder)
133 | {
134 | //知識庫轉存向量儲存
135 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第1條", text: "本細則依檔案法(以下簡稱本法)第二十九條規定訂定之。");
136 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第2條第1項", text: "本法第二條第二款所稱管理程序,指依文書處理或機關業務相關法令規定,完成核定、發文或辦結之程序。");
137 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第2條第2項", text: "本法第二條第二款所稱文字或非文字資料及其附件,指各機關處理公務或因公務而產生之各類紀錄資料及其附件,包括各機關所持有或保管之文書、圖片、紀錄、照片、錄影(音)、微縮片、電腦處理資料等,可供聽、讀、閱覽或藉助科技得以閱覽或理解之文書或物品。");
138 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第3條", text: "各機關管理檔案,應依本法第四條規定,並參照檔案中央主管機關訂定之機關檔案管理單位及人員配置基準,設置或指定專責單位或人員。");
139 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第4條第1項", text: "各機關依本法第五條規定,經該管機關核准,將檔案運往國外者,應先以微縮、電子或其他方式儲存,並經管理該檔案機關首長核定。");
140 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第4條第2項", text: "前項檔案如屬永久保存之機關檔案,並應經檔案中央主管機關同意。");
141 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第5條", text: "各機關依本法第六條第二項規定,將檔案中之器物交有關機構保管時,應訂定書面契約或作成紀錄存查。");
142 | }
143 | }
144 | }
145 |
146 | /*
147 | sample case :
148 | 1.永久保存的機關檔案可以做為公開資料嗎?
149 | 2.파일을 해외로 배송하는 데 제한이 있나요? (要把檔案運到國外,有什麼限制嗎)
150 | 3.公文書法で規制される内容とは何ですか? (檔案法所規範的內容是指哪些)
151 | 4.Can permanently preserved agency files be turned into public information?
152 | */
--------------------------------------------------------------------------------
/NetConf2023/04-TransAndRag/TransAndRag.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net8.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | Always
20 |
21 |
22 | Always
23 |
24 |
25 | Always
26 |
27 |
28 | Always
29 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/NetConf2023/05-EasySummaryClassification/05-EasySummaryClassification.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net8.0
6 | _05_EasySummaryClassification
7 | enable
8 | enable
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/NetConf2023/05-EasySummaryClassification/Plugins/SummarizePlugin/Summarize/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "description": "總結給定的文本內容,並以json格式返回結果。",
4 | "execution_settings": {
5 | "default": {
6 | "max_tokens": 1024,
7 | "temperature": 0.2,
8 | "top_p": 0.0,
9 | "presence_penalty": 0.0,
10 | "frequency_penalty": 0.0
11 | }
12 | },
13 | "input_variables": [
14 | {
15 | "name": "user_input",
16 | "description": "Text to summarize",
17 | "default": "",
18 | "is_required": true
19 | }
20 | ]
21 | }
--------------------------------------------------------------------------------
/NetConf2023/05-EasySummaryClassification/Plugins/SummarizePlugin/Summarize/skprompt.txt:
--------------------------------------------------------------------------------
1 | 你是一位專業的飯店客服人員,擅長判斷客人回饋的評論以及整理評論中的重點,
2 | 請你負責分析客戶的評論是正面或負面,正面請用positive,負面請用negative,
3 | 並且做內容重點摘要以及歸類該評論是屬於"硬體設備"、"服務態度"、"餐點"、"整潔度"的哪一項分類,
4 | 分析結果請採用以下json格式輸出
5 |
6 | 【總結規則】
7 | 不要廢話
8 | 使用簡短、清晰、完整的句子。
9 | 請勿使用要點或破折號。
10 | 最大化細節,意義
11 | 專注於內容
12 | 不要重複
13 |
14 | [範例]
15 | 總結:
16 | 預定公園景頂級房結果被升等到套房,太幸運了。原本想說就是看中公園頂級房的浴缸是面對公園景,所以才選購的,被通知升等的時候還有點擔心,但完全是多餘的擔心,因為在房間床上的時間絕對是大於在浴缸的時間,所以面公園的景緻在房間窗戶絕對是更好的。 (而且後來發現人如果在公園,往上看英迪格酒店,是會看得到房間的,也就是如果你人在公園頂級房的浴室裸體的話,窗簾是必須要先拉起來,等人入浴之後再開窗簾才會不會曝光) 整體體驗非常好,服務人員態度親切,只是沒有地下停車場,要停在後巷的配合停車場,要跟櫃台索取條碼,是不需要停車費的,但如果下雨提行李會很不方便。 房間真的沒有什麼缺點,床鋪很好躺,枕頭有多種選擇,電視的畫質其實不錯,不像其他評論的差(不知道是不是後來有更新過),還有膠囊咖啡機。 浴缸非常大可以一次兩個人泡,淋浴間也很大,三個人可以一起洗,但是浴室如果有暖氣會更好,不然出來的時候很冷。 還有雙面盆,吹風機風力很強。 早餐中規中矩,有主餐可以選。 入住可以跟櫃台索取IHG的飲料券,可以兌換頂樓酒吧的紅白酒或是一樓的咖啡冷飲等。 走路一分鐘就是中央公園捷運站,非常方便的地點,值得再來。
17 |
18 | [輸出json格式]
19 | {
20 | "summary":"客人原本預定公園景頂級房,但被升等到套房,感到非常幸運。雖然一開始有些擔心因為特別看中原房間的浴缸景觀,但最終發現升等後的房間更好。服務人員態度親切,房間舒適,床鋪和枕頭多樣化,電視畫質好,提供膠囊咖啡機。浴室設施寬敞,但若加裝暖氣會更佳。早餐品質中等,酒店位置便利。",
21 | "Emotion":"positive",
22 | "Classification":"硬體設備"
23 | }
24 |
25 |
26 | 客戶評論
27 | {{$user_input}}
28 |
29 | [輸出json格式]
30 | {
31 | "summary":"......",
32 | "Emotion":"...",
33 | "Classification":"..."
34 | }
--------------------------------------------------------------------------------
/NetConf2023/05-EasySummaryClassification/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 |
3 | string Gpt4DeploymentName = "xxx";
4 | string Gpt4ModelId = "xxx";
5 | string AzureOpenAIEndpoint = "https://xxx.openai.azure.com/";
6 | string AzureOpenAIApiKey = "xxx";
7 | string currentDirectory = Directory.GetCurrentDirectory();
8 |
9 | Kernel kernel = Kernel.CreateBuilder()
10 | .AddAzureOpenAIChatCompletion(
11 | deploymentName: Gpt4DeploymentName,
12 | endpoint: AzureOpenAIEndpoint,
13 | apiKey: AzureOpenAIApiKey,
14 | modelId: Gpt4ModelId)
15 | .Build();
16 |
17 | // Import the Plugin from the plugins directory.
18 | var pluginsDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Plugins");
19 | var plugin = kernel.ImportPluginFromPromptDirectory(Path.Combine(pluginsDirectory, "SummarizePlugin"));
20 | KernelFunction summarizeFun = plugin["Summarize"];
21 |
22 | while (true)
23 | {
24 | Console.WriteLine("Assistant > 您好,請留下您的寶貴意見 \n");
25 | Console.Write("User > ");
26 | var user_Input = Console.ReadLine();
27 | Console.Write("\n");
28 |
29 | if (string.Compare(user_Input, "exit", true) == 0)
30 | {
31 | Console.WriteLine("Assistant > bye........");
32 | break;
33 | }
34 |
35 | var result = (await kernel.InvokeAsync(summarizeFun, arguments: new()
36 | {
37 | { "user_input", user_Input }
38 | })).ToString();
39 |
40 | Console.WriteLine($"Assistant > {result} \n \n");
41 |
42 | }
43 |
44 | /*
45 | sample case
46 |
47 | 1.為了來阿里山,所以入住阿里山英迪格。飯店的位置有他先天的限制,座落在被民宅包圍,離阿里山森林遊樂區還有一小時的車程,對於幻想可以衝到祝山看日出的旅客,除非開車,否則是有難度的,因此,我們是抱著不看日出,隨遇而安的心情來的。必須讚美一下飯店的接駁行程,讓我們輕易的前往奮起湖,又能暢遊阿里山森林遊樂區,對於只靠雙腿的遊客真的幫助很大。飯店很新(廢話),很高科技,用AI可以播音樂,開燈,關電視之類的,適合懶人,前提是要先讓她聽得懂中文(大笑)。標準房的房間其實不算大,但也足夠四個人一起聊天哈啦。比較奇怪是無浴缸的房型,浴室也很大,感覺比例不太協調,導致走道很小,但缺點的反面是優點,上廁所就沒有壓迫感XDDD。早餐我覺得蠻不錯,提供的麵包類都很好吃,特別是馬告生吐司,各類可頌等,餐點總類不是最多,但也提供了多樣選擇,尤其是加入很多阿里山當地的食材。房間的零食飲料都是免費享用,這點非常體貼。不過,我還是忍不住要評論房間的地毯,尤其穿着襪子跟飯店拖鞋要特別當心,地毯與地板的高低差太容易被絆倒跟腳滑。
48 |
49 | 2.本來看到了負評有點擔心,實際入住後,發現很優質很滿意啊!入住的是七樓山景房,房間看出去遠眺山景,視野開闊。四點入住後到頂樓,有無邊際溫水游泳池和熱水池,提供毛巾浴袍和水,還有美麗的雲海相伴,晚上點燈更氣氛很迷人!晚餐是另外自費半自助式套餐,雖然一個人3千多不算便宜,但主食(我們點黑毛牛排)很好吃,自助式的餐點雖然不大但每道都很好吃,甚至有不少很新鮮的海鮮,廣島生蠔另人驚艷,非常肥美!頂樓就可以看日出也是賣點,不必一早4點就上祝山還不見得看得到,櫃台很貼心告知大約日出時刻,睡到時間差不多直接上頂樓就可以欣賞啦!早餐小而美,選擇雖然不是非常多,但細節用心,肉鬆不是用廉價豆粉而是有肉脯的,有現做蛋料理,麵類都很美味!終於有阿里山賓館外的好飯店可以選擇了,下次還會選擇英迪格來住!
50 |
51 | 3.來慶生覺得很雷訂了兩間房一間雙床房給長輩,另一間一張大床房給我們自己慶生,結果居然兩間都給我們雙床房,我確認過很多次確定自己是訂對的房型甚至事先打電話確認細節,結果還是出錯。原本以為是佈置好才會讓我們上去結果我們在房門口遇到來送蛋糕的員工整個就很尷尬。因為我們提早到,就在大廳等但沒有跟我們說茶飲在哪裡是我們自己看到自己拿但其他人就是裝好送過去。短髮櫃檯人員服務態度完全感覺不到是五星級飯店該有的樣子,非常冷淡而且其他服務人員告知其他房客的資訊也都沒有說,不知道是不是因為我們買專案價格所以差別待遇,總之感受很差。等電梯要等很久因為全部只有兩部,早餐晚餐還不錯但飲料選擇很少基本上只有鋁箔包的果汁跟鋁罐裝的飲料。入住時間是下午四點但check out時間是十一點,除了頂樓外沒什麼設施可以使用,入住二樓跟五樓基本上是完全沒有景而且房間偏小。結論大概就是沒有這個價位該有的服務品質跟景色,對整體體驗非常失望。
52 |
53 | */
--------------------------------------------------------------------------------
/NetConf2023/DotNetConf-2023-SemanticKernel.pptx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/iangithub/sklearn/84b3a565b6fc20e7762ebc837b5b4244152e2000/NetConf2023/DotNetConf-2023-SemanticKernel.pptx
--------------------------------------------------------------------------------
/NetConf2023/netconf2023.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.8.34330.188
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "01-GetStart", "01-GetStart\01-GetStart.csproj", "{DC91F3A8-8354-43A5-B176-FF34B0810BA6}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "02-NativeFunc", "02-NativeFunc\02-NativeFunc.csproj", "{50FC5952-FBDD-4C6C-BC6C-F390A4E8E014}"
9 | EndProject
10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "03-MultiSemanticFuncs", "03-MultiSemanticFuncs\03-MultiSemanticFuncs.csproj", "{4D73EFD0-7583-4FD2-843C-EC1A015D827D}"
11 | EndProject
12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TransAndRag", "04-TransAndRag\TransAndRag.csproj", "{DBAE123A-4771-48FF-9D17-A941A7A44005}"
13 | EndProject
14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "05-EasySummaryClassification", "05-EasySummaryClassification\05-EasySummaryClassification.csproj", "{ECAC4F85-6CBB-4FBD-8685-6D5206B6BA68}"
15 | EndProject
16 | Global
17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
18 | Debug|Any CPU = Debug|Any CPU
19 | Release|Any CPU = Release|Any CPU
20 | EndGlobalSection
21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
22 | {DC91F3A8-8354-43A5-B176-FF34B0810BA6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
23 | {DC91F3A8-8354-43A5-B176-FF34B0810BA6}.Debug|Any CPU.Build.0 = Debug|Any CPU
24 | {DC91F3A8-8354-43A5-B176-FF34B0810BA6}.Release|Any CPU.ActiveCfg = Release|Any CPU
25 | {DC91F3A8-8354-43A5-B176-FF34B0810BA6}.Release|Any CPU.Build.0 = Release|Any CPU
26 | {50FC5952-FBDD-4C6C-BC6C-F390A4E8E014}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27 | {50FC5952-FBDD-4C6C-BC6C-F390A4E8E014}.Debug|Any CPU.Build.0 = Debug|Any CPU
28 | {50FC5952-FBDD-4C6C-BC6C-F390A4E8E014}.Release|Any CPU.ActiveCfg = Release|Any CPU
29 | {50FC5952-FBDD-4C6C-BC6C-F390A4E8E014}.Release|Any CPU.Build.0 = Release|Any CPU
30 | {4D73EFD0-7583-4FD2-843C-EC1A015D827D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
31 | {4D73EFD0-7583-4FD2-843C-EC1A015D827D}.Debug|Any CPU.Build.0 = Debug|Any CPU
32 | {4D73EFD0-7583-4FD2-843C-EC1A015D827D}.Release|Any CPU.ActiveCfg = Release|Any CPU
33 | {4D73EFD0-7583-4FD2-843C-EC1A015D827D}.Release|Any CPU.Build.0 = Release|Any CPU
34 | {DBAE123A-4771-48FF-9D17-A941A7A44005}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
35 | {DBAE123A-4771-48FF-9D17-A941A7A44005}.Debug|Any CPU.Build.0 = Debug|Any CPU
36 | {DBAE123A-4771-48FF-9D17-A941A7A44005}.Release|Any CPU.ActiveCfg = Release|Any CPU
37 | {DBAE123A-4771-48FF-9D17-A941A7A44005}.Release|Any CPU.Build.0 = Release|Any CPU
38 | {ECAC4F85-6CBB-4FBD-8685-6D5206B6BA68}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
39 | {ECAC4F85-6CBB-4FBD-8685-6D5206B6BA68}.Debug|Any CPU.Build.0 = Debug|Any CPU
40 | {ECAC4F85-6CBB-4FBD-8685-6D5206B6BA68}.Release|Any CPU.ActiveCfg = Release|Any CPU
41 | {ECAC4F85-6CBB-4FBD-8685-6D5206B6BA68}.Release|Any CPU.Build.0 = Release|Any CPU
42 | EndGlobalSection
43 | GlobalSection(SolutionProperties) = preSolution
44 | HideSolutionNode = FALSE
45 | EndGlobalSection
46 | GlobalSection(ExtensibilityGlobals) = postSolution
47 | SolutionGuid = {5F447545-4CAA-4264-BB76-356D6C303E1B}
48 | EndGlobalSection
49 | EndGlobal
50 |
--------------------------------------------------------------------------------
/PromptTemplateEngineSample/Program.cs:
--------------------------------------------------------------------------------
1 | using Azure.AI.OpenAI;
2 | using Microsoft.SemanticKernel;
3 | using Microsoft.SemanticKernel.Connectors.AI.OpenAI;
4 | using Microsoft.SemanticKernel.Plugins.Core;
5 | using Microsoft.SemanticKernel.TemplateEngine.Basic;
6 |
7 | namespace PromptTemplateEngineSample
8 | {
9 | public class Program
10 | {
11 | private const string deploy_model = "xxx";
12 | private const string aoai_Endpoint = "https://xxx.openai.azure.com";
13 | private const string api_Key = "xxxx";
14 |
15 | static async Task Main(string[] args)
16 | {
17 | var kernel = new KernelBuilder()
18 | .WithAzureChatCompletionService(
19 | deploy_model, // Azure OpenAI Deployment Name
20 | aoai_Endpoint, // Azure OpenAI Endpoint
21 | api_Key // Azure OpenAI Key
22 | ).Build();
23 |
24 | //掛載TextPlugin
25 | kernel.ImportFunctions(new TextPlugin(), "textplugin");
26 |
27 | var context = kernel.CreateNewContext();
28 | context.Variables["subject"] = "愛惡作劇";
29 | context.Variables["major_character"] = "耿鬼";
30 |
31 | var prompt = @"寫一個則童話故事,有關於: {{textplugin.Concat input=$subject input2=$major_character}}";
32 |
33 | //建立BasicPromptTemplateEngine物件並調用RenderAsync方法
34 | var promptRenderer = new BasicPromptTemplateEngine();
35 | var renderedPrompt = await promptRenderer.RenderAsync(prompt, context);
36 | Console.WriteLine("--- Rendered Prompt ---");
37 | Console.WriteLine(renderedPrompt);
38 |
39 | //建立SemanticFunction
40 | var semanticFunc = kernel.CreateSemanticFunction(prompt, requestSettings: new OpenAIRequestSettings() { MaxTokens = 1000 });
41 |
42 | Console.WriteLine("--- Semantic Function result ---");
43 | //取得生成結果
44 | var result = await kernel.RunAsync(context.Variables, semanticFunc);
45 | Console.WriteLine(result.GetValue());
46 |
47 | }
48 | }
49 | }
--------------------------------------------------------------------------------
/PromptTemplateEngineSample/PromptTemplateEngineSample.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net7.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # sklearn
2 | 學習 semantic kernel 的基礎範例程式
3 |
4 | 建議搭配2023鐵人賽文章 https://ithelp.ithome.com.tw/users/20126569/ironman/6022
5 |
6 |
7 |
--------------------------------------------------------------------------------
/SequentialPlannerSample/Plugins/WriterPlugin/FacebookPoster/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "type": "completion",
4 | "description": "產生facebook貼文",
5 | "completion": {
6 | "max_tokens": 2000,
7 | "temperature": 0.2,
8 | "top_p": 0.0,
9 | "presence_penalty": 0.0,
10 | "frequency_penalty": 0.0
11 | },
12 | "input": {
13 | "parameters": [
14 | {
15 | "name": "input",
16 | "description": "貼文主題",
17 | "defaultValue": ""
18 | }
19 | ]
20 | }
21 | }
--------------------------------------------------------------------------------
/SequentialPlannerSample/Plugins/WriterPlugin/FacebookPoster/skprompt.txt:
--------------------------------------------------------------------------------
1 | 你是一位facebook小編,撰寫下列主題的貼文,內容200個字以內,#zh-tw
2 |
3 | {{$input}}
4 |
--------------------------------------------------------------------------------
/SequentialPlannerSample/Plugins/WriterPlugin/Translate/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "type": "completion",
4 | "description": "翻譯",
5 | "completion": {
6 | "max_tokens": 2000,
7 | "temperature": 0.2,
8 | "top_p": 0.0,
9 | "presence_penalty": 0.0,
10 | "frequency_penalty": 0.0
11 | },
12 | "input": {
13 | "parameters": [
14 | {
15 | "name": "input",
16 | "description": "要翻譯的內容",
17 | "defaultValue": ""
18 | }
19 | ]
20 | }
21 | }
--------------------------------------------------------------------------------
/SequentialPlannerSample/Plugins/WriterPlugin/Translate/skprompt.txt:
--------------------------------------------------------------------------------
1 | 翻譯下列內容成為英文,並輸出原始中文資料及翻譯後的英文資料都要顯示出來,中英文內容分隔2行
2 |
3 | {{$input}}
4 |
5 |
--------------------------------------------------------------------------------
/SequentialPlannerSample/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 | using Microsoft.SemanticKernel.Planners;
3 |
4 | namespace SequentialPlannerSample
5 | {
6 | internal class Program
7 | {
8 | //OpenAI
9 | private const string openai_Key = "xxx";
10 | private const string openai_deploy_Model = "gpt-4-1106-preview";
11 |
12 |
13 | static async Task Main(string[] args)
14 | {
15 | var kernel = new KernelBuilder()
16 | .WithOpenAIChatCompletionService(
17 | modelId: openai_deploy_Model, // OpenAI Deployment Name
18 | apiKey: openai_Key // OpenAI Key
19 | ).Build();
20 |
21 | // Import the Plugin from the plugins directory.
22 | var pluginsDirectory = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Plugins");
23 | kernel.ImportSemanticFunctionsFromDirectory(pluginsDirectory, "WriterPlugin");
24 |
25 | var planner = new SequentialPlanner(kernel);
26 | var goal = "寫一則關於chatgpt對教育場景影響的臉書貼文,然後翻譯該則貼文為英文.";
27 | var plan = await planner.CreatePlanAsync(goal);
28 |
29 | Console.WriteLine("============ Original plan ====================");
30 |
31 | foreach (var step in plan.Steps)
32 | {
33 | Console.WriteLine($"step : {step.Name}");
34 | }
35 | Console.WriteLine("\n\n");
36 |
37 |
38 | var result = await kernel.RunAsync(plan);
39 | Console.WriteLine("============ Result ====================");
40 | Console.WriteLine(result.GetValue());
41 | }
42 | }
43 | }
--------------------------------------------------------------------------------
/SequentialPlannerSample/SequentialPlannerSample.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net7.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | Always
17 |
18 |
19 | Always
20 |
21 |
22 | Always
23 |
24 |
25 | Always
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/SerializingSemanticFunction/Plugins/WriterPlugin/FacebookPoster/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "type": "completion",
4 | "description": "產生facebook貼文",
5 | "completion": {
6 | "max_tokens": 2000,
7 | "temperature": 0.2,
8 | "top_p": 0.0,
9 | "presence_penalty": 0.0,
10 | "frequency_penalty": 0.0
11 | },
12 | "input": {
13 | "parameters": [
14 | {
15 | "name": "fewshot_sample",
16 | "description": "寫作風格參考資料",
17 | "defaultValue": ""
18 | },
19 | {
20 | "name": "post_subject",
21 | "description": "貼文主題",
22 | "defaultValue": ""
23 | }
24 | ]
25 | }
26 | }
--------------------------------------------------------------------------------
/SerializingSemanticFunction/Plugins/WriterPlugin/FacebookPoster/skprompt.txt:
--------------------------------------------------------------------------------
1 | 你是一位facebook小編,請先思考一下下列提供的範例寫作風格
2 | ###
3 | {{$fewshot_sample}}
4 | ###
5 |
6 | 接著撰寫下列主題的貼文,內容500個字以內,#zh-tw
7 | ###
8 | {{$post_subject}}
9 | ###
--------------------------------------------------------------------------------
/SerializingSemanticFunction/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 | using Microsoft.SemanticKernel.Orchestration;
3 |
4 | namespace SerializingSemanticFunction
5 | {
6 | internal class Program
7 | {
8 | private const string deploy_model = "xxx";
9 | private const string aoai_Endpoint = "https://xxxx.openai.azure.com";
10 | private const string api_Key = "xxxx";
11 |
12 | static async Task Main(string[] args)
13 | {
14 | var kernel = new KernelBuilder()
15 | .WithAzureChatCompletionService(
16 | deploy_model, // Azure OpenAI Deployment Name
17 | aoai_Endpoint, // Azure OpenAI Endpoint
18 | api_Key // Azure OpenAI Key
19 | ).Build();
20 |
21 | // Import the Plugin from the plugins directory.
22 | var pluginsDirectory = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Plugins");
23 | var plugin = kernel.ImportSemanticSkillFromDirectory(pluginsDirectory, "WriterPlugin");
24 |
25 | //few-shot,帶入方文山詞創作範例
26 | string fewshot_sample = @"
27 | 竹籬上 停留著 蜻蜓
28 | 玻璃瓶裡插滿 小小 森林
29 | 青春 嫩綠的很 鮮明
30 |
31 | 百葉窗 折射的 光影
32 | 像有著心事的 一張 表情
33 | 而你 低頭拆信 想知道關於我的事情
34 |
35 | 月色搖晃樹影 穿梭在熱帶雨林
36 | 你離去的原因從來不說明
37 | 你的謊像陷阱我最後才清醒
38 | 幸福只是水中的倒影
39 |
40 | 月色搖晃樹影穿梭在熱帶雨林
41 | 悲傷的雨不停全身血淋淋
42 | 那深陷在沼澤我不堪的愛情
43 | 是我無能為力的傷心
44 |
45 | 蘆葦花開歲已寒 若霜又降路遙漫長
46 | 牆外是誰在吟唱 鳳求凰
47 | 梨園台上 西皮二黃
48 | 卻少了妳 無人問暖
49 | 誰在彼岸 天涯一方
50 |
51 | 在夢裡我醞釀著情緒
52 | 等回憶等那一種熟悉
53 | 人世間最溫柔的消息
54 | 是曾經被你擁入懷裡
55 | ";
56 |
57 | var contextVars = new ContextVariables()
58 | {
59 | ["fewshot_sample"] = fewshot_sample,
60 | ["post_subject"] = "ChatGPT對校園教育的衝擊"
61 | };
62 |
63 | //叫用GPT模型等得生成結果
64 | var result = (await kernel.RunAsync(contextVars, plugin["FacebookPoster"])).Result;
65 |
66 | Console.WriteLine(result);
67 |
68 | }
69 | }
70 | }
--------------------------------------------------------------------------------
/SerializingSemanticFunction/SerializingSemanticFunction.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net7.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | Always
17 |
18 |
19 | Always
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/TransAndRag/Plugins/QAPlugin/AssistantResults/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "type": "completion",
4 | "description": "Answer any question based on text source",
5 | "completion": {
6 | "max_tokens": 2000,
7 | "temperature": 0.2
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/TransAndRag/Plugins/QAPlugin/AssistantResults/skprompt.txt:
--------------------------------------------------------------------------------
1 | 這是使用者的提問
2 | ###
3 | {{$query_input}}
4 | ###
5 |
6 | 這是從知識庫所搜尋到的結果
7 | ###
8 | {{$ans_result}}
9 | ###
10 |
11 | 當回應使用者的問題時,請仔細閱讀上面所提供的資料,確保您的回答既簡短又具有針對性。
12 | 如果知識庫沒有可以參考的資料,也請具體回應無參考資料可供回答。
13 | 所有的回應,請思考使用者提問的語言,必須將回答翻譯成使用者的語言,以確保溝通無障礙,在翻譯過程中,都務必保留答案的原始意圖,避免添加或刪除任何可能改變答案意義的內容。
--------------------------------------------------------------------------------
/TransAndRag/Plugins/QAPlugin/Translate/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "type": "completion",
4 | "description": "If it is not Traditional Chinese, please translate it into Traditional Chinese.",
5 | "completion": {
6 | "max_tokens": 2000,
7 | "temperature": 0.2
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/TransAndRag/Plugins/QAPlugin/Translate/skprompt.txt:
--------------------------------------------------------------------------------
1 | 請你先分析以下文字的語言,如果是繁體中文就維持原內容,如果是其它語言,please translator to zh-tw
2 | ###
3 | {{$query_input}}
4 | ###
5 |
--------------------------------------------------------------------------------
/TransAndRag/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel.Orchestration;
2 | using Microsoft.SemanticKernel.Plugins.Memory;
3 | using Microsoft.SemanticKernel;
4 | using Microsoft.SemanticKernel.Connectors.AI.OpenAI;
5 | using Microsoft.SemanticKernel.Memory;
6 | using System.Globalization;
7 |
8 | namespace TransAndRag
9 | {
10 | internal class Program
11 | {
12 | //AOAI
13 | private const string deploy_Model = "xxx";
14 | private const string embedding_Model = "xxx";
15 | private const string aoai_Endpoint = "https://xxx.openai.azure.com";
16 | private const string api_Key = "xxx";
17 | private const string embedding_CollectionName = "Law";
18 |
19 | //OpenAI
20 | private const string openai_Key = "xxx";
21 | private const string openai_deploy_Model = "gpt-4-1106-preview";
22 |
23 | static async Task Main(string[] args)
24 | {
25 | //AOAI
26 | //var kernel = new KernelBuilder()
27 | // .WithAzureChatCompletionService(
28 | // deploy_Model, // Azure OpenAI Deployment Name
29 | // aoai_Endpoint, // Azure OpenAI Endpoint
30 | // api_Key // Azure OpenAI Key
31 | // ).Build();
32 |
33 | //OpenAI
34 | var kernel = new KernelBuilder()
35 | .WithOpenAIChatCompletionService(
36 | modelId: openai_deploy_Model, // OpenAI Deployment Name
37 | apiKey: openai_Key // OpenAI Key
38 | ).Build();
39 |
40 |
41 | var memoryWithCustomDb = new MemoryBuilder()
42 | .WithAzureTextEmbeddingGenerationService(embedding_Model, aoai_Endpoint, api_Key)
43 | .WithMemoryStore(new VolatileMemoryStore())
44 | .Build();
45 |
46 | //Init KM
47 | await ImportKm(memoryWithCustomDb);
48 |
49 | // Import the Plugin from the plugins directory.
50 | var pluginsDirectory = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Plugins");
51 |
52 | var qaPlugin = "QAPlugin";
53 | kernel.ImportSemanticFunctionsFromDirectory(pluginsDirectory, qaPlugin);
54 | var transFun = kernel.Functions.GetFunction(qaPlugin, "Translate");
55 | var assistantResultsFun = kernel.Functions.GetFunction(qaPlugin, "AssistantResults");
56 |
57 |
58 | while (true)
59 | {
60 | Console.WriteLine("bot: 您好,您想問什麼呢? ( What can I help you with? ) \n");
61 | Console.Write("you: ");
62 |
63 | /*
64 | query sample case
65 | 1.永久保存的機關檔案可以做為公開資料嗎?
66 | 2.파일을 해외로 배송하는 데 제한이 있나요? (要把檔案運到國外,有什麼限制嗎)
67 | 3.公文書法で規制される内容とは何ですか? (檔案法所規範的內容是指哪些)
68 | 4.Can permanently preserved agency files be turned into public information?
69 | */
70 |
71 |
72 | var query = Console.ReadLine();
73 | Console.Write("\n");
74 |
75 | if (string.Compare(query, "exit", true) == 0)
76 | {
77 | break;
78 | }
79 |
80 | if (string.IsNullOrEmpty(query))
81 | {
82 | return;
83 | }
84 |
85 | //自動翻譯
86 | var transQuery = await kernel.RunAsync(transFun, new ContextVariables() { { "query_input", query } });
87 |
88 |
89 | //RAG Search
90 | var searchResult = memoryWithCustomDb
91 | .SearchAsync(embedding_CollectionName, transQuery.GetValue(), minRelevanceScore: 0.8);
92 |
93 | var ans = string.Empty;
94 |
95 | await foreach (var kmResult in searchResult)
96 | {
97 | ans += $"{kmResult.Metadata.Text}\n\n";
98 | }
99 |
100 | //return
101 | var assistantResult = await kernel.RunAsync(assistantResultsFun, new ContextVariables() { { "query_input", query }, { "ans_result", ans } });
102 | Console.WriteLine($"bot: {assistantResult.GetValue()} \n \n");
103 |
104 | }
105 | }
106 |
107 | private static async Task ImportKm(ISemanticTextMemory memoryBuilder)
108 | {
109 | //知識庫轉存向量儲存
110 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第1條", text: "本細則依檔案法(以下簡稱本法)第二十九條規定訂定之。");
111 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第2條第1項", text: "本法第二條第二款所稱管理程序,指依文書處理或機關業務相關法令規定,完成核定、發文或辦結之程序。");
112 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第2條第2項", text: "本法第二條第二款所稱文字或非文字資料及其附件,指各機關處理公務或因公務而產生之各類紀錄資料及其附件,包括各機關所持有或保管之文書、圖片、紀錄、照片、錄影(音)、微縮片、電腦處理資料等,可供聽、讀、閱覽或藉助科技得以閱覽或理解之文書或物品。");
113 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第3條", text: "各機關管理檔案,應依本法第四條規定,並參照檔案中央主管機關訂定之機關檔案管理單位及人員配置基準,設置或指定專責單位或人員。");
114 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第4條第1項", text: "各機關依本法第五條規定,經該管機關核准,將檔案運往國外者,應先以微縮、電子或其他方式儲存,並經管理該檔案機關首長核定。");
115 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第4條第2項", text: "前項檔案如屬永久保存之機關檔案,並應經檔案中央主管機關同意。");
116 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第5條", text: "各機關依本法第六條第二項規定,將檔案中之器物交有關機構保管時,應訂定書面契約或作成紀錄存查。");
117 | }
118 | }
119 | }
--------------------------------------------------------------------------------
/TransAndRag/TransAndRag.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net7.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 | Always
18 |
19 |
20 | Always
21 |
22 |
23 | Always
24 |
25 |
26 | Always
27 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/TransAndRagUseSemanticFun/Plugins/QAPlugin/AssistantResults/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "type": "completion",
4 | "description": "Answer any question based on text source",
5 | "completion": {
6 | "max_tokens": 2000,
7 | "temperature": 0.2
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/TransAndRagUseSemanticFun/Plugins/QAPlugin/AssistantResults/skprompt.txt:
--------------------------------------------------------------------------------
1 | 這是使用者的提問,請你先分析文字的語言,如果是繁體中文就維持原內容,如果是其它語言,please translator to zh-tw
2 | ###
3 | {{$input}}
4 | ###
5 |
6 |
7 | 這是從知識庫所搜尋到的結果
8 | ###
9 | {{$ans_ref}}
10 | ###
11 |
12 | 請根據上述資料,簡短扼要的回答使用者的問題,如果使用者的問題內容不是繁體中文語言,請把知識庫所搜尋到的結果內容翻譯成使用者所提問的語言,然後再進行回覆,並且回覆的內容不能失去原意
13 |
--------------------------------------------------------------------------------
/TransAndRagUseSemanticFun/Plugins/QAPlugin/KmSearch.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 | using Microsoft.SemanticKernel.Connectors.AI.OpenAI;
3 | using Microsoft.SemanticKernel.Orchestration;
4 | using Microsoft.SemanticKernel.Plugins.Memory;
5 | using System;
6 | using System.Collections.Generic;
7 | using System.ComponentModel;
8 | using System.Linq;
9 | using System.Text;
10 | using System.Threading.Tasks;
11 |
12 | namespace TransAndRagUseSemanticFun.Plugins.QAPlugin
13 | {
14 | public class KmSearch
15 | {
16 | private const string deploy_Model = "gpt4demo";
17 | private const string embedding_Model = "textembedding";
18 | private const string aoai_Endpoint = "https://demo0222.openai.azure.com";
19 | private const string api_Key = "ece107c84324497e9987d15f916845e4";
20 | private const string embedding_CollectionName = "Law";
21 |
22 | [SKFunction, Description("從知識庫中取得參考資料")]
23 | public async Task GetKm(string input, SKContext skContext)
24 | {
25 |
26 | var memoryWithCustomDb = new MemoryBuilder()
27 | .WithAzureTextEmbeddingGenerationService(embedding_Model, aoai_Endpoint, api_Key)
28 | .WithMemoryStore(new VolatileMemoryStore())
29 | .Build();
30 |
31 | //RAG Search
32 | var searchResult = memoryWithCustomDb
33 | .SearchAsync(embedding_CollectionName, input, minRelevanceScore: 0.8);
34 |
35 | var ans = string.Empty;
36 |
37 | await foreach (var kmResult in searchResult)
38 | {
39 | ans += $"{kmResult.Metadata.Text}\n\n";
40 | }
41 |
42 | if (string.IsNullOrEmpty(ans))
43 | {
44 | ans = "很抱歉,知識庫沒有相關資料可以提供";
45 | }
46 |
47 | return ans;
48 | }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/TransAndRagUseSemanticFun/Plugins/QAPlugin/Translate/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "type": "completion",
4 | "description": "If it is not Traditional Chinese, please translate it into Traditional Chinese.",
5 | "completion": {
6 | "max_tokens": 2000,
7 | "temperature": 0.2
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/TransAndRagUseSemanticFun/Plugins/QAPlugin/Translate/skprompt.txt:
--------------------------------------------------------------------------------
1 | 請你先分析以下文字的語言,如果是繁體中文就維持原內容,如果是其它語言,please translator to zh-tw
2 | ###
3 | {{$query_input}}
4 | ###
5 |
--------------------------------------------------------------------------------
/TransAndRagUseSemanticFun/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel.Orchestration;
2 | using Microsoft.SemanticKernel.Plugins.Memory;
3 | using Microsoft.SemanticKernel;
4 | using Microsoft.SemanticKernel.Connectors.AI.OpenAI;
5 | using Microsoft.SemanticKernel.Memory;
6 | using System.Globalization;
7 | using System.Threading.Tasks;
8 |
9 | namespace TransAndRagUseSemanticFun
10 | {
11 | internal class Program
12 | {
13 | private const string deploy_Model = "gpt4demo";
14 | private const string embedding_Model = "textembedding";
15 | private const string aoai_Endpoint = "https://demo0222.openai.azure.com";
16 | private const string api_Key = "ece107c84324497e9987d15f916845e4";
17 | private const string embedding_CollectionName = "Law";
18 |
19 | static async Task Main(string[] args)
20 | {
21 | var kernel = new KernelBuilder()
22 | .WithAzureChatCompletionService(
23 | deploy_Model, // Azure OpenAI Deployment Name
24 | aoai_Endpoint, // Azure OpenAI Endpoint
25 | api_Key // Azure OpenAI Key
26 | ).Build();
27 |
28 |
29 | var memoryWithCustomDb = new MemoryBuilder()
30 | .WithAzureTextEmbeddingGenerationService(embedding_Model, aoai_Endpoint, api_Key)
31 | .WithMemoryStore(new VolatileMemoryStore())
32 | .Build();
33 |
34 | //Init KM
35 | await ImportKm(memoryWithCustomDb);
36 |
37 | // Import the Plugin from the plugins directory.
38 | var pluginsDirectory = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Plugins");
39 |
40 | //semantic fun
41 | kernel.ImportSemanticFunctionsFromDirectory(pluginsDirectory, "QAPlugin");
42 | var assistantResultsFun = kernel.Functions.GetFunction("QAPlugin", "AssistantResults");
43 | var transFun = kernel.Functions.GetFunction("QAPlugin", "Translate");
44 |
45 | //native fun
46 | kernel.ImportFunctions(new Plugins.QAPlugin.KmSearch(), "KmSearchPlugin");
47 | var kmSearchFun = kernel.Functions.GetFunction("KmSearchPlugin", "GetKm");
48 |
49 | while (true)
50 | {
51 | Console.WriteLine("bot: 您好,我是法規知識大師,您想問什麼呢? \n");
52 | Console.Write("you: ");
53 |
54 | //var query = "永久保存的機關檔案可以做為公開資料嗎?";
55 | //var query = "不禮讓行人,會有罸則嗎";
56 | //var query = "闖紅燈罸多少錢啊";
57 | //var query = "檔案要傳送到國外可以嗎";
58 | var query = Console.ReadLine();
59 | Console.Write("\n");
60 |
61 | if (string.Compare(query, "exit", true) == 0)
62 | {
63 | break;
64 | }
65 |
66 | if (string.IsNullOrEmpty(query))
67 | {
68 | return;
69 | }
70 |
71 |
72 | var cv = new ContextVariables() {
73 | { "query_input", query },
74 | { "trans_input", string.Empty },
75 | { "ans_ref", string.Empty },
76 | };
77 |
78 | var result = await kernel.RunAsync(
79 | cv,
80 | transFun,
81 | kmSearchFun,
82 | assistantResultsFun
83 | );
84 |
85 |
86 | //return
87 | Console.WriteLine($"bot: {result.GetValue()} \n \n");
88 |
89 | }
90 | }
91 |
92 | private static async Task ImportKm(ISemanticTextMemory memoryBuilder)
93 | {
94 | //知識庫轉存向量儲存
95 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第1條", text: "本細則依檔案法(以下簡稱本法)第二十九條規定訂定之。");
96 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第2條第1項", text: "本法第二條第二款所稱管理程序,指依文書處理或機關業務相關法令規定,完成核定、發文或辦結之程序。");
97 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第2條第2項", text: "本法第二條第二款所稱文字或非文字資料及其附件,指各機關處理公務或因公務而產生之各類紀錄資料及其附件,包括各機關所持有或保管之文書、圖片、紀錄、照片、錄影(音)、微縮片、電腦處理資料等,可供聽、讀、閱覽或藉助科技得以閱覽或理解之文書或物品。");
98 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第3條", text: "各機關管理檔案,應依本法第四條規定,並參照檔案中央主管機關訂定之機關檔案管理單位及人員配置基準,設置或指定專責單位或人員。");
99 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第4條第1項", text: "各機關依本法第五條規定,經該管機關核准,將檔案運往國外者,應先以微縮、電子或其他方式儲存,並經管理該檔案機關首長核定。");
100 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第4條第2項", text: "前項檔案如屬永久保存之機關檔案,並應經檔案中央主管機關同意。");
101 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第5條", text: "各機關依本法第六條第二項規定,將檔案中之器物交有關機構保管時,應訂定書面契約或作成紀錄存查。");
102 | }
103 | }
104 | }
--------------------------------------------------------------------------------
/TransAndRagUseSemanticFun/TransAndRagUseSemanticFun.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net7.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | Always
17 |
18 |
19 | Always
20 |
21 |
22 | Always
23 |
24 |
25 | Always
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/WebSearch/Plugins/QAPlugin/AssistantResults/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "type": "completion",
4 | "description": "Answer any question based on text source",
5 | "completion": {
6 | "max_tokens": 2000,
7 | "temperature": 0.2
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/WebSearch/Plugins/QAPlugin/AssistantResults/skprompt.txt:
--------------------------------------------------------------------------------
1 | 這是從外部來源所搜尋到的結果
2 | ###
3 | {{$ans_result}}
4 | ###
5 |
6 | 請根據上述資料,回答使用者的問題,並且附上參考來源
7 | 問題:{{$query_input}}
8 | 答案:
9 |
--------------------------------------------------------------------------------
/WebSearch/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 | using Microsoft.SemanticKernel.AI.ChatCompletion;
3 | using Microsoft.SemanticKernel.Connectors.AI.OpenAI.ChatCompletion;
4 | using Microsoft.SemanticKernel.Orchestration;
5 | using Microsoft.SemanticKernel.Plugins.Web;
6 | using Microsoft.SemanticKernel.Plugins.Web.Bing;
7 | using static System.Runtime.InteropServices.JavaScript.JSType;
8 | //using Microsoft.SemanticKernel.Skills.Web.Google;
9 |
10 | namespace WebSearch
11 | {
12 | internal class Program
13 | {
14 | //AOAI
15 | private const string deploy_Model = "xxx";
16 | private const string aoai_Endpoint = "https://xxx.openai.azure.com";
17 | private const string api_Key = "xxx";
18 | private const string bingSerach_Key = "xxx";
19 |
20 | //OpenAI
21 | private const string openai_Key = "xxx";
22 | private const string openai_deploy_Model = "gpt-4-1106-preview";
23 |
24 | static async Task Main(string[] args)
25 | {
26 | //Azure OpenAI
27 | //var kernel = new KernelBuilder()
28 | // .WithAzureChatCompletionService(
29 | // deploy_Model, // Azure OpenAI Deployment Name
30 | // aoai_Endpoint, // Azure OpenAI Endpoint
31 | // api_Key // Azure OpenAI Key
32 | // ).Build();
33 |
34 |
35 | //OpenAI
36 | var kernel = new KernelBuilder()
37 | .WithOpenAIChatCompletionService(
38 | modelId: openai_deploy_Model, // OpenAI Deployment Name
39 | apiKey: openai_Key // OpenAI Key
40 | ).Build();
41 |
42 |
43 | // Connector
44 | var searchPluginName = "bing";
45 | var bingConnector = new BingConnector(bingSerach_Key);
46 | kernel.ImportFunctions(new WebSearchEnginePlugin(bingConnector),searchPluginName);
47 |
48 | // Import the semantic function from the plugins directory.
49 | var qaPlugin = "QAPlugin";
50 | var pluginsDirectory = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Plugins");
51 | kernel.ImportSemanticFunctionsFromDirectory(pluginsDirectory, qaPlugin);
52 | var assistantResultsFun = kernel.Functions.GetFunction(qaPlugin, "AssistantResults");
53 |
54 | string question = string.Empty;
55 | while (true)
56 | {
57 | Console.WriteLine("bot: 你想問什麼事情呢? (結束請輸入exit) \n");
58 | Console.Write("you: ");
59 | question = Console.ReadLine();
60 | Console.Write("\n");
61 |
62 | if (question.ToLower() == "exit")
63 | {
64 | break;
65 | }
66 |
67 | var searchFun = kernel.Functions.GetFunction(searchPluginName, "search");
68 | var searchResult = await kernel.RunAsync(question, searchFun);
69 |
70 | //return
71 | var assistantResult = await kernel.RunAsync(assistantResultsFun, new ContextVariables() { { "query_input", question }, { "ans_result", searchResult.ToString() } });
72 | Console.WriteLine($"bot: {assistantResult.GetValue()} \n \n");
73 | }
74 | }
75 | }
76 | }
--------------------------------------------------------------------------------
/WebSearch/WebSearch.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net7.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 | Always
18 |
19 |
20 | Always
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/WithoutSkSample/WithoutSkSample.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.6.33829.357
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WithoutSkSample", "WithoutSkSample\WithoutSkSample.csproj", "{000B27FD-6534-4A79-8602-659C220BB8B6}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {000B27FD-6534-4A79-8602-659C220BB8B6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {000B27FD-6534-4A79-8602-659C220BB8B6}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {000B27FD-6534-4A79-8602-659C220BB8B6}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {000B27FD-6534-4A79-8602-659C220BB8B6}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {EDA9175B-5732-4CCB-9A1E-79EFE521CEEE}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/WithoutSkSample/WithoutSkSample/GPT4/PromptTemplate.txt:
--------------------------------------------------------------------------------
1 | 請你閱讀###內的文章的寫作風格
2 |
3 | ###
4 | 你要做一個不動聲色的大人了。不准情緒化,不准偷偷想念,不准回頭看。去過自己另外的生活。
5 | 就經驗性來說,人強烈追求什麼的時候,那東西基本上是不來的,而當你極力迴避它的時候,它卻自然找到頭上。
6 | 不管全世界所有人怎麼說,我都認為自己的感受才是正確的。 無論別人怎麼看,我絕不打亂自己的節奏。 喜歡的事自然可以堅持,不喜歡怎麼也長久不了。
7 | 哪裡有人喜歡孤獨,只不過不亂交朋友罷了,那樣只能落得失望。
8 | 剛剛好,看見你幸福的樣子,於是幸福著你的幸福。
9 | 我們的人生,在那之間有所謂陰影的中間地帶。能夠認識那陰影的層次,並去理解它,才是健全的知性。
10 | 我認為我的工作是觀察人和世界,而不是去評判他們。我一直希望自己遠離所謂的結論,我想讓世界一切都敞開懷抱
11 | 歸根結底,一個人是否有可能對另一個人有完美的理解?我們可以花費大量時間和精力去結識另一個人,但最後,我們可以接近那個人的本質嗎?我們說服自己,我們很了解對方,但是我們真的了解任何人的重要本質嗎?
12 | ###
13 |
14 | 請你使用相同的寫作風格,對下面的文章進行改寫,並且產生500個字以內的內容,使用繁體中文
15 |
16 | ###
17 | {{user_prompt}}
18 | ###
19 |
--------------------------------------------------------------------------------
/WithoutSkSample/WithoutSkSample/GPT4/RequestModel.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | namespace WithoutSkSample.GPT4
9 | {
10 | public class RequestModel
11 | {
12 | [JsonProperty(PropertyName = "messages")]
13 | public List Messages { get; private set; }
14 |
15 | [JsonProperty(PropertyName = "temperature")]
16 | public float Temperature { get; set; }
17 |
18 | [JsonProperty(PropertyName = "top_p")]
19 | public float Top_p { get; set; }
20 |
21 | [JsonProperty(PropertyName = "frequency_penalty")]
22 | public int Frequency_Penalty { get; set; }
23 |
24 | [JsonProperty(PropertyName = "presence_penalty")]
25 | public int Presence_Penalty { get; set; }
26 | [JsonProperty(PropertyName = "max_tokens")]
27 | public int Max_Tokens { get; set; }
28 |
29 | public RequestModel(string sysContent)
30 | {
31 | /*
32 | * sysContent Sample :
33 | * "現在開始你是一位專欄作家"
34 | */
35 |
36 | Messages = new List
37 | {
38 | new Message() { Role = "system", Content = sysContent }
39 | };
40 | Temperature = 0.8f;
41 | Top_p = 0.95f;
42 | Frequency_Penalty = 0;
43 | Presence_Penalty = 0;
44 | Max_Tokens = 2000;
45 | }
46 |
47 | public void AddUserMessages(string message)
48 | {
49 | this.Messages.Add(new Message() { Role = "user", Content = message });
50 | }
51 | public void AddGptMessages(string message)
52 | {
53 | this.Messages.Add(new Message() { Role = "assistant", Content = message });
54 | }
55 | }
56 |
57 | public class Message
58 | {
59 | ///
60 | /// system/assistant/user
61 | ///
62 | [JsonProperty(PropertyName = "role")]
63 | public string Role { get; set; }
64 | [JsonProperty(PropertyName = "content")]
65 | public string Content { get; set; }
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/WithoutSkSample/WithoutSkSample/GPT4/ResponseModel.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | namespace WithoutSkSample.GPT4
9 | {
10 | public class Completion
11 | {
12 | [JsonProperty(PropertyName = "id")]
13 | public string Id { get; set; }
14 | [JsonProperty(PropertyName = "object")]
15 | public string AiType { get; set; }
16 | [JsonProperty(PropertyName = "created")]
17 | public int Created { get; set; }
18 | [JsonProperty(PropertyName = "model")]
19 | public string Model { get; set; }
20 | [JsonProperty(PropertyName = "choices")]
21 | public List Choices { get; set; }
22 | [JsonProperty(PropertyName = "usage")]
23 | public Usage Usage { get; set; }
24 | }
25 |
26 | public class Choices
27 | {
28 | [JsonProperty(PropertyName = "message")]
29 | public Message Message { get; set; }
30 | [JsonProperty(PropertyName = "index")]
31 | public int Index { get; set; }
32 | [JsonProperty(PropertyName = "logprobs")]
33 | public object Logprobs { get; set; }
34 | [JsonProperty(PropertyName = "finish_reason")]
35 | public string Finish_reason { get; set; }
36 | }
37 |
38 | public class Usage
39 | {
40 | [JsonProperty(PropertyName = "prompt_tokens")]
41 | public int Prompt_Tokens { get; set; }
42 | [JsonProperty(PropertyName = "completion_tokens")]
43 | public int Completion_Tokens { get; set; }
44 | [JsonProperty(PropertyName = "total_tokens")]
45 | public int Total_Tokens { get; set; }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/WithoutSkSample/WithoutSkSample/Program.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using System.Text;
3 | using WithoutSkSample.GPT4;
4 |
5 | namespace WithoutSkSample
6 | {
7 | internal class Program
8 | {
9 | //API授權金鑰
10 | const string api_Key = "{aoai_key}";
11 | const string aoai_Service_Name = "{aoai_service_name}";
12 | const string deployment_Name = "{aoai_deploy_name}";
13 | const string api_Version = "2023-07-01-preview";
14 |
15 | //使用 Chat Completions API 搭配 GPT-4 模型
16 | const string api_Endpoint = $"https://{aoai_Service_Name}.openai.azure.com/openai/deployments/{deployment_Name}/chat/completions?api-version={api_Version}";
17 |
18 |
19 | static async Task Main(string[] args)
20 | {
21 | var prompt = @"隨著科技的進步,人工智能(AI)在各個領域中的應用越來越廣泛,教育領域也不例外。
22 | 近年來,ChatGPT(生成式對話機器人)已經在教學領域中發揮了重要作用,
23 | 從而為教師和學生提供了更多的學習機會和資源。
24 | 本文將探討ChatGPT在教育領域的幾個主要應用,以及它如何改變了當代教育的面貌。
25 | 1. 輔助教學
26 | ChatGPT可作為教師的助手,協助他們解答學生的疑問。這樣一來,教師便能專注於教授課程內容,
27 | 同時保證每位學生都能得到足夠的關注。此外,ChatGPT具有自然語言處理(NLP)功能,
28 | 能夠理解並回答各種問題,有助於學生在課堂以外的時間獲得即時反饋。
29 | 2. 個性化學習
30 | ChatGPT具有強大的學習能力,能夠根據每個學生的需求和興趣提供個性化的學習計劃。
31 | 這意味著學生可以在自己的節奏下學習,避免了因跟不上課程進度而感到沮喪的情況。
32 | 此外,ChatGPT還能夠根據學生的學習情況給出建議,幫助他們在學習過程中取得更好的成果。
33 | 3. 語言學習助手
34 | 對於正在學習外語的學生,ChatGPT可以作為一個出色的語言學習助手。它可以與學生進行即時對話,
35 | 幫助他們練習口語和聽力技能。此外,ChatGPT還
36 | 能提供寫作建議,協助學生改進他們的寫作技巧。這樣的互動式學習方式對於提高學生的語言水平具有很大的幫助。
37 | 4. 在線評估與測試
38 | ChatGPT可以自動生成各種題型的試題,為教師提供了一個簡單而有效的評估工具。
39 | 這不僅可以節省教師編制試題的時間,還能確保試題的多樣性和客觀性。
40 | 此外,ChatGPT還能夠進行自動評分,為教師提供及時的學生表現反饋。";
41 |
42 | //村上春樹風格-內容改寫優化
43 | try
44 | {
45 | string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GPT4", "PromptTemplate.txt");
46 |
47 | // 以template方式,進行prompt改造
48 | string prompt_template = File.ReadAllText(filePath);
49 | prompt_template = prompt_template.Replace("{{user_prompt}}", prompt);
50 |
51 | using (HttpClient client = new HttpClient())
52 | {
53 | //設定模型扮演的角色
54 | var requestModel = new RequestModel("現在開始你是一位專欄作家。");
55 | //加入改造後的prompt
56 | requestModel.AddUserMessages(prompt_template);
57 |
58 | //API請求
59 | var json = JsonConvert.SerializeObject(requestModel);
60 | var data = new StringContent(json, Encoding.UTF8, "application/json");
61 | client.DefaultRequestHeaders.Add("api-key", api_Key);
62 | var response = await client.PostAsync(api_Endpoint, data);
63 | var responseContent = await response.Content.ReadAsStringAsync();
64 |
65 | //API回應
66 | var completion = JsonConvert.DeserializeObject(responseContent);
67 |
68 | //輸出模型生成結果
69 | Console.WriteLine(completion.Choices[0].Message.Content);
70 |
71 | }
72 | }
73 | catch (Exception e)
74 | {
75 | Console.WriteLine(e.Message);
76 | }
77 | }
78 | }
79 | }
--------------------------------------------------------------------------------
/WithoutSkSample/WithoutSkSample/WithoutSkSample.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net6.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | Always
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/WriterPlannerSample/Program.cs:
--------------------------------------------------------------------------------
1 | namespace WriterPlannerSample
2 | {
3 | internal class Program
4 | {
5 | static void Main(string[] args)
6 | {
7 | Console.WriteLine("Hello, World!");
8 | }
9 | }
10 | }
--------------------------------------------------------------------------------
/WriterPlannerSample/WriterPlannerSample.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net7.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/sklearn.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.6.33829.357
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IntroSample", "IntroSample\IntroSample.csproj", "{2B2910FC-E464-4346-856B-6AD02E3DBB91}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "KmSearch", "KmSearch\KmSearch.csproj", "{80554755-3E18-470E-B32C-EB990578A9B1}"
9 | EndProject
10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebSearch", "WebSearch\WebSearch.csproj", "{1A5A734B-F65A-4705-9454-7DDE7947E387}"
11 | EndProject
12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WithoutSkSample", "WithoutSkSample\WithoutSkSample\WithoutSkSample.csproj", "{90341A53-5DB2-4DAA-B25E-BA6705E88AAC}"
13 | EndProject
14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "InlineSemanticFunction", "InlineSemanticFunction\InlineSemanticFunction.csproj", "{24205929-D7D9-425D-A07E-40C8DB4778A4}"
15 | EndProject
16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SerializingSemanticFunction", "SerializingSemanticFunction\SerializingSemanticFunction.csproj", "{88A97B30-5898-42BE-BF00-D14DF63A5BA8}"
17 | EndProject
18 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MixSemanticFunAndNativeFun", "MixSemanticFunAndNativeFun\MixSemanticFunAndNativeFun.csproj", "{1E6FABE2-EA08-4797-A641-A79E67BBDFB5}"
19 | EndProject
20 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ChainSemanticFunc", "ChainSemanticFunc\ChainSemanticFunc.csproj", "{66763AFB-DBFC-4C55-B515-936ECFD09992}"
21 | EndProject
22 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SequentialPlannerSample", "SequentialPlannerSample\SequentialPlannerSample.csproj", "{5D4E6A34-DFC2-476A-9EEF-990FE2B3EB89}"
23 | EndProject
24 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WriterPlannerSample", "WriterPlannerSample\WriterPlannerSample.csproj", "{CD555666-E76E-40CD-89A7-54C5354EC3DD}"
25 | EndProject
26 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PromptTemplateEngineSample", "PromptTemplateEngineSample\PromptTemplateEngineSample.csproj", "{7C8DB197-DB5F-4457-9A6C-13AF14322684}"
27 | EndProject
28 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MultiChatCompletionSample", "MultiChatCompletionSample\MultiChatCompletionSample.csproj", "{A7693345-4E26-4D92-BCF4-50D4D54DB7A2}"
29 | EndProject
30 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "KernelChatCompletion", "KernelChatCompletion\KernelChatCompletion.csproj", "{FB8E71D3-7709-40AE-BF74-FA2815B0F652}"
31 | EndProject
32 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TransAndRag", "TransAndRag\TransAndRag.csproj", "{5AD1B5E2-CD9B-48D6-9CE2-FE4D2ED21FD6}"
33 | EndProject
34 | Global
35 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
36 | Debug|Any CPU = Debug|Any CPU
37 | Release|Any CPU = Release|Any CPU
38 | EndGlobalSection
39 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
40 | {2B2910FC-E464-4346-856B-6AD02E3DBB91}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
41 | {2B2910FC-E464-4346-856B-6AD02E3DBB91}.Debug|Any CPU.Build.0 = Debug|Any CPU
42 | {2B2910FC-E464-4346-856B-6AD02E3DBB91}.Release|Any CPU.ActiveCfg = Release|Any CPU
43 | {2B2910FC-E464-4346-856B-6AD02E3DBB91}.Release|Any CPU.Build.0 = Release|Any CPU
44 | {80554755-3E18-470E-B32C-EB990578A9B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
45 | {80554755-3E18-470E-B32C-EB990578A9B1}.Debug|Any CPU.Build.0 = Debug|Any CPU
46 | {80554755-3E18-470E-B32C-EB990578A9B1}.Release|Any CPU.ActiveCfg = Release|Any CPU
47 | {80554755-3E18-470E-B32C-EB990578A9B1}.Release|Any CPU.Build.0 = Release|Any CPU
48 | {1A5A734B-F65A-4705-9454-7DDE7947E387}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
49 | {1A5A734B-F65A-4705-9454-7DDE7947E387}.Debug|Any CPU.Build.0 = Debug|Any CPU
50 | {1A5A734B-F65A-4705-9454-7DDE7947E387}.Release|Any CPU.ActiveCfg = Release|Any CPU
51 | {1A5A734B-F65A-4705-9454-7DDE7947E387}.Release|Any CPU.Build.0 = Release|Any CPU
52 | {90341A53-5DB2-4DAA-B25E-BA6705E88AAC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
53 | {90341A53-5DB2-4DAA-B25E-BA6705E88AAC}.Debug|Any CPU.Build.0 = Debug|Any CPU
54 | {90341A53-5DB2-4DAA-B25E-BA6705E88AAC}.Release|Any CPU.ActiveCfg = Release|Any CPU
55 | {90341A53-5DB2-4DAA-B25E-BA6705E88AAC}.Release|Any CPU.Build.0 = Release|Any CPU
56 | {24205929-D7D9-425D-A07E-40C8DB4778A4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
57 | {24205929-D7D9-425D-A07E-40C8DB4778A4}.Debug|Any CPU.Build.0 = Debug|Any CPU
58 | {24205929-D7D9-425D-A07E-40C8DB4778A4}.Release|Any CPU.ActiveCfg = Release|Any CPU
59 | {24205929-D7D9-425D-A07E-40C8DB4778A4}.Release|Any CPU.Build.0 = Release|Any CPU
60 | {88A97B30-5898-42BE-BF00-D14DF63A5BA8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
61 | {88A97B30-5898-42BE-BF00-D14DF63A5BA8}.Debug|Any CPU.Build.0 = Debug|Any CPU
62 | {88A97B30-5898-42BE-BF00-D14DF63A5BA8}.Release|Any CPU.ActiveCfg = Release|Any CPU
63 | {88A97B30-5898-42BE-BF00-D14DF63A5BA8}.Release|Any CPU.Build.0 = Release|Any CPU
64 | {1E6FABE2-EA08-4797-A641-A79E67BBDFB5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
65 | {1E6FABE2-EA08-4797-A641-A79E67BBDFB5}.Debug|Any CPU.Build.0 = Debug|Any CPU
66 | {1E6FABE2-EA08-4797-A641-A79E67BBDFB5}.Release|Any CPU.ActiveCfg = Release|Any CPU
67 | {1E6FABE2-EA08-4797-A641-A79E67BBDFB5}.Release|Any CPU.Build.0 = Release|Any CPU
68 | {66763AFB-DBFC-4C55-B515-936ECFD09992}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
69 | {66763AFB-DBFC-4C55-B515-936ECFD09992}.Debug|Any CPU.Build.0 = Debug|Any CPU
70 | {66763AFB-DBFC-4C55-B515-936ECFD09992}.Release|Any CPU.ActiveCfg = Release|Any CPU
71 | {66763AFB-DBFC-4C55-B515-936ECFD09992}.Release|Any CPU.Build.0 = Release|Any CPU
72 | {5D4E6A34-DFC2-476A-9EEF-990FE2B3EB89}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
73 | {5D4E6A34-DFC2-476A-9EEF-990FE2B3EB89}.Debug|Any CPU.Build.0 = Debug|Any CPU
74 | {5D4E6A34-DFC2-476A-9EEF-990FE2B3EB89}.Release|Any CPU.ActiveCfg = Release|Any CPU
75 | {5D4E6A34-DFC2-476A-9EEF-990FE2B3EB89}.Release|Any CPU.Build.0 = Release|Any CPU
76 | {CD555666-E76E-40CD-89A7-54C5354EC3DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
77 | {CD555666-E76E-40CD-89A7-54C5354EC3DD}.Debug|Any CPU.Build.0 = Debug|Any CPU
78 | {CD555666-E76E-40CD-89A7-54C5354EC3DD}.Release|Any CPU.ActiveCfg = Release|Any CPU
79 | {CD555666-E76E-40CD-89A7-54C5354EC3DD}.Release|Any CPU.Build.0 = Release|Any CPU
80 | {7C8DB197-DB5F-4457-9A6C-13AF14322684}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
81 | {7C8DB197-DB5F-4457-9A6C-13AF14322684}.Debug|Any CPU.Build.0 = Debug|Any CPU
82 | {7C8DB197-DB5F-4457-9A6C-13AF14322684}.Release|Any CPU.ActiveCfg = Release|Any CPU
83 | {7C8DB197-DB5F-4457-9A6C-13AF14322684}.Release|Any CPU.Build.0 = Release|Any CPU
84 | {A7693345-4E26-4D92-BCF4-50D4D54DB7A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
85 | {A7693345-4E26-4D92-BCF4-50D4D54DB7A2}.Debug|Any CPU.Build.0 = Debug|Any CPU
86 | {A7693345-4E26-4D92-BCF4-50D4D54DB7A2}.Release|Any CPU.ActiveCfg = Release|Any CPU
87 | {A7693345-4E26-4D92-BCF4-50D4D54DB7A2}.Release|Any CPU.Build.0 = Release|Any CPU
88 | {FB8E71D3-7709-40AE-BF74-FA2815B0F652}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
89 | {FB8E71D3-7709-40AE-BF74-FA2815B0F652}.Debug|Any CPU.Build.0 = Debug|Any CPU
90 | {FB8E71D3-7709-40AE-BF74-FA2815B0F652}.Release|Any CPU.ActiveCfg = Release|Any CPU
91 | {FB8E71D3-7709-40AE-BF74-FA2815B0F652}.Release|Any CPU.Build.0 = Release|Any CPU
92 | {5AD1B5E2-CD9B-48D6-9CE2-FE4D2ED21FD6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
93 | {5AD1B5E2-CD9B-48D6-9CE2-FE4D2ED21FD6}.Debug|Any CPU.Build.0 = Debug|Any CPU
94 | {5AD1B5E2-CD9B-48D6-9CE2-FE4D2ED21FD6}.Release|Any CPU.ActiveCfg = Release|Any CPU
95 | {5AD1B5E2-CD9B-48D6-9CE2-FE4D2ED21FD6}.Release|Any CPU.Build.0 = Release|Any CPU
96 | EndGlobalSection
97 | GlobalSection(SolutionProperties) = preSolution
98 | HideSolutionNode = FALSE
99 | EndGlobalSection
100 | GlobalSection(ExtensibilityGlobals) = postSolution
101 | SolutionGuid = {A34431B3-F993-4EF6-BF68-98D781C8846C}
102 | EndGlobalSection
103 | EndGlobal
104 |
--------------------------------------------------------------------------------
/skv1_start/01-GetStart/01-GetStart.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net8.0
6 | _01_GetStart
7 | enable
8 | enable
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/skv1_start/01-GetStart/Plugins/Chat.yaml:
--------------------------------------------------------------------------------
1 | name: Chat
2 | template: |
3 | 你是一位萬事通助理,根據使用者的提問來回答問題,請一律使用 #zh-tw 回答
4 |
5 | {{#each messages}}
6 | {{~Content~}}
7 | {{/each}}
8 | template_format: handlebars
9 | description: 使用聊天歷史來回應用戶的功能
10 | input_variables:
11 | - name: messages
12 | description: 聊天歷史
13 | is_required: true
14 | execution_settings:
15 | service1:
16 | model_id: gpt-4
17 | temperature: 0.6
18 | service2:
19 | model_id: gpt-3
20 | temperature: 0.4
21 | default:
22 | temperature: 0.5
23 |
--------------------------------------------------------------------------------
/skv1_start/01-GetStart/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 | using Microsoft.VisualBasic;
3 | using System.Reflection;
4 | using Newtonsoft.Json;
5 | using Microsoft.SemanticKernel.PromptTemplates.Handlebars;
6 | using Microsoft.SemanticKernel.ChatCompletion;
7 | using Microsoft.SemanticKernel.Connectors.OpenAI;
8 |
9 | string gpt4DeploymentName = "xxx";
10 | string modelId = "xxx";
11 | string azureOpenAIEndpoint = "https://xxx.openai.azure.com/";
12 | string azureOpenAIApiKey = "xxx";
13 | string currentDirectory = Directory.GetCurrentDirectory();
14 |
15 | Kernel kernel = Kernel.CreateBuilder()
16 | .AddAzureOpenAIChatCompletion(
17 | deploymentName: gpt4DeploymentName,
18 | endpoint: azureOpenAIEndpoint,
19 | apiKey: azureOpenAIApiKey,
20 | modelId: modelId)
21 | .Build();
22 |
23 | // Load prompt from resource
24 | using StreamReader reader = new(Path.Combine(currentDirectory, "Plugins", "Chat.yaml"));
25 | KernelFunction prompt = kernel.CreateFunctionFromPromptYaml(
26 | reader.ReadToEnd(),
27 | promptTemplateFactory: new HandlebarsPromptTemplateFactory()
28 | );
29 |
30 |
31 | // #pragma warning disable SKEXP0004
32 | // kernel.PromptRendered += (sender, args) =>
33 | // {
34 | // Console.WriteLine("=========== PromptRendered Start ===========");
35 | // Console.WriteLine(args.RenderedPrompt);
36 | // Console.WriteLine("=========== PromptRendered End ===========\n\n");
37 |
38 | // };
39 | // #pragma warning restore SKEXP0004
40 |
41 |
42 | ChatHistory chatMessages = [];
43 |
44 |
45 | while (true)
46 | {
47 | // Get user input
48 | System.Console.Write("User > ");
49 | chatMessages.AddUserMessage(Console.ReadLine()!);
50 |
51 | // Enable auto invocation of kernel functions
52 | OpenAIPromptExecutionSettings openAIPromptExecutionSettings = new()
53 | {
54 | ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions
55 | };
56 |
57 | // Get the chat completions
58 | var result = kernel.InvokeStreamingAsync(
59 | prompt,
60 | arguments: new(openAIPromptExecutionSettings) {
61 | { "messages", chatMessages }
62 | });
63 |
64 |
65 | ChatMessageContent? chatMessageContent = null;
66 |
67 | await foreach (var content in result)
68 | {
69 | System.Console.Write(content);
70 | if (chatMessageContent == null)
71 | {
72 | System.Console.Write("Assistant > ");
73 | chatMessageContent = new ChatMessageContent(
74 | content.Role ?? AuthorRole.Assistant,
75 | content.ModelId!,
76 | content.Content!,
77 | content.InnerContent,
78 | content.Encoding,
79 | content.Metadata);
80 | }
81 | else
82 | {
83 | chatMessageContent.Content += content;
84 | }
85 | }
86 | System.Console.WriteLine("\n");
87 |
88 | chatMessages.Add(chatMessageContent!);
89 | }
--------------------------------------------------------------------------------
/skv1_start/02-NativeFunc/02-NativeFunc.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net8.0
6 | _02_NativeFunc
7 | enable
8 | enable
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/skv1_start/02-NativeFunc/Plugins/ChatPlugin/Chat.yaml:
--------------------------------------------------------------------------------
1 | name: Chat
2 | template: |
3 | 你是一位萬事通助理,根據使用者的提問來回答問題,請一律使用 #zh-tw 回答
4 |
5 | {{#each messages}}
6 | {{~Content~}}
7 | {{/each}}
8 | template_format: handlebars
9 | description: 使用聊天歷史來回應用戶的功能
10 | input_variables:
11 | - name: messages
12 | description: 聊天歷史
13 | is_required: true
14 | execution_settings:
15 | service1:
16 | model_id: gpt-4
17 | temperature: 0.6
18 | service2:
19 | model_id: gpt-3
20 | temperature: 0.4
21 | default:
22 | temperature: 0.5
23 |
--------------------------------------------------------------------------------
/skv1_start/02-NativeFunc/Plugins/DateTimePlugin/DateTimePlugin.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 | using Microsoft.SemanticKernel;
3 |
4 | namespace MyPlugins;
5 |
6 | internal class DataTimePlugin
7 | {
8 | [KernelFunction("GetCurrentDateTime")]
9 | [Description("Get the current date and time.'")]
10 | public string GetCurrentDateTime()
11 | {
12 | return DateTime.Now.ToString();
13 | }
14 | }
--------------------------------------------------------------------------------
/skv1_start/02-NativeFunc/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 | using Microsoft.VisualBasic;
3 | using System.Reflection;
4 | using Newtonsoft.Json;
5 | using Microsoft.SemanticKernel.PromptTemplates.Handlebars;
6 | using Microsoft.SemanticKernel.ChatCompletion;
7 | using Microsoft.SemanticKernel.Connectors.OpenAI;
8 | using MyPlugins;
9 |
10 | string gpt4DeploymentName = "xxx";
11 | string modelId = "xxx";
12 | string azureOpenAIEndpoint = "https://xxx.openai.azure.com/";
13 | string azureOpenAIApiKey = "xxx";
14 | string currentDirectory = Directory.GetCurrentDirectory();
15 |
16 | Kernel kernel = Kernel.CreateBuilder()
17 | .AddAzureOpenAIChatCompletion(
18 | deploymentName: gpt4DeploymentName,
19 | modelId: modelId,
20 | endpoint: azureOpenAIEndpoint,
21 | apiKey: azureOpenAIApiKey)
22 | .Build();
23 |
24 | // Load prompt from resource
25 | using StreamReader reader = new(Path.Combine(currentDirectory, "Plugins", "ChatPlugin", "Chat.yaml"));
26 | KernelFunction prompt = kernel.CreateFunctionFromPromptYaml(
27 | reader.ReadToEnd(),
28 | promptTemplateFactory: new HandlebarsPromptTemplateFactory()
29 | );
30 |
31 | //Load Plugins
32 | kernel.Plugins.AddFromType();
33 |
34 |
35 | #pragma warning disable SKEXP0004
36 |
37 | kernel.PromptRendered += (sender, args) =>
38 | {
39 | Console.WriteLine("=========== PromptRendered Start ===========");
40 | Console.WriteLine(args.RenderedPrompt);
41 | Console.WriteLine("=========== PromptRendered End ===========\n\n");
42 | };
43 |
44 |
45 | kernel.FunctionInvoking += (sender, args) =>
46 | {
47 | Console.WriteLine("=========== FunctionInvoking Start ===========");
48 | Console.WriteLine(args.Function.Name);
49 | Console.WriteLine("=========== FunctionInvoking End ===========\n\n");
50 |
51 | };
52 |
53 | #pragma warning restore SKEXP0004
54 |
55 |
56 | // Create the chat history
57 | ChatHistory chatMessages = [];
58 |
59 | while (true)
60 | {
61 | // Get user input
62 | System.Console.Write("User > ");
63 | var userMessage = Console.ReadLine()!;
64 | chatMessages.AddUserMessage(userMessage);
65 |
66 | // Enable auto invocation of kernel functions
67 | OpenAIPromptExecutionSettings openAIPromptExecutionSettings = new()
68 | {
69 | ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions
70 | };
71 |
72 | var result = kernel.InvokeStreamingAsync(
73 | prompt,
74 | arguments: new(openAIPromptExecutionSettings) {
75 | { "messages", chatMessages }
76 | });
77 |
78 | // Print the chat completions
79 | ChatMessageContent? chatMessageContent = null;
80 |
81 | await foreach (var content in result)
82 | {
83 | System.Console.Write(content);
84 | if (chatMessageContent == null)
85 | {
86 | System.Console.Write("Assistant > ");
87 | chatMessageContent = new ChatMessageContent(
88 | content.Role ?? AuthorRole.Assistant,
89 | content.ModelId!,
90 | content.Content!,
91 | content.InnerContent,
92 | content.Encoding,
93 | content.Metadata);
94 | }
95 | else
96 | {
97 | chatMessageContent.Content += content;
98 | }
99 | }
100 | System.Console.WriteLine("\n");
101 |
102 | chatMessages.Add(chatMessageContent!);
103 |
104 | }
105 |
--------------------------------------------------------------------------------
/skv1_start/03-MultiSemanticFuncs/03-MultiSemanticFuncs.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net8.0
6 | _03_SequentialPlanner
7 | enable
8 | enable
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/skv1_start/03-MultiSemanticFuncs/Plugins/TranslatePlugin/Translate.yaml:
--------------------------------------------------------------------------------
1 | name: Translate
2 | template: |
3 | 翻譯下列內容成為英文,並輸出原始中文資料及翻譯後的英文資料都要顯示出來,中英文內容分隔2行
4 | {{$postcontent}}
5 | template_format: semantic-kernel
6 | description: 根據使用者提供的內容,翻譯成英文
7 | input_variables:
8 | - name: postcontent
9 | description: 使用者提供的內容
10 | is_required: true
11 | execution_settings:
12 | service1:
13 | model_id: gpt-4
14 | temperature: 0.6
15 |
--------------------------------------------------------------------------------
/skv1_start/03-MultiSemanticFuncs/Plugins/WriterPlugin/Writer.yaml:
--------------------------------------------------------------------------------
1 | name: Writer
2 | template: |
3 | 你是一位facebook小編,撰寫下列主題的貼文,內容200個字以內,#zh-tw
4 | {{$topic}}
5 | template_format: semantic-kernel
6 | description: 根據使用者提供的內容,撰寫facebook貼文
7 | input_variables:
8 | - name: topic
9 | description: 貼文的主題
10 | is_required: true
11 | execution_settings:
12 | service1:
13 | model_id: gpt-4
14 | temperature: 0.6
15 |
--------------------------------------------------------------------------------
/skv1_start/03-MultiSemanticFuncs/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 | using Microsoft.VisualBasic;
3 | using System.Reflection;
4 | using Newtonsoft.Json;
5 | using Microsoft.SemanticKernel.PromptTemplates.Handlebars;
6 | using Microsoft.SemanticKernel.ChatCompletion;
7 | using Microsoft.SemanticKernel.Connectors.OpenAI;
8 |
9 | string gpt4DeploymentName = "xxx";
10 | string modelId = "xxx";
11 | string azureOpenAIEndpoint = "https://xxx.openai.azure.com/";
12 | string azureOpenAIApiKey = "xxx";
13 | string currentDirectory = Directory.GetCurrentDirectory();
14 |
15 | Kernel kernel = Kernel.CreateBuilder()
16 | .AddAzureOpenAIChatCompletion(
17 | deploymentName: gpt4DeploymentName,
18 | endpoint: azureOpenAIEndpoint,
19 | apiKey: azureOpenAIApiKey,
20 | modelId: modelId)
21 | .Build();
22 |
23 | // Load prompt from Directory
24 | using StreamReader reader = new(Path.Combine(currentDirectory, "Plugins", "WriterPlugin", "Writer.yaml"));
25 | KernelFunction writerPlugin = kernel.CreateFunctionFromPromptYaml(reader.ReadToEnd());
26 |
27 | using StreamReader reader2 = new(Path.Combine(currentDirectory, "Plugins", "TranslatePlugin", "Translate.yaml"));
28 | KernelFunction transPlugin = kernel.CreateFunctionFromPromptYaml(reader2.ReadToEnd());
29 |
30 | while (true)
31 | {
32 | System.Console.Write("User > ");
33 | var userMessage = Console.ReadLine()!;
34 |
35 | var writerResult = (await kernel.InvokeAsync(writerPlugin, arguments: new()
36 | {
37 | { "topic", userMessage }
38 | })).ToString();
39 |
40 | var finalResult = (await kernel.InvokeAsync(transPlugin, arguments: new()
41 | {
42 | { "topic", userMessage },{ "postcontent", writerResult }
43 | })).ToString();
44 |
45 | System.Console.WriteLine($"Assistant > {finalResult}");
46 | }
47 |
--------------------------------------------------------------------------------
/skv1_start/04-TransAndRag/Plugins/QAPlugin/AssistantResults/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "description": "Answer any question based on knowledge base source",
4 | "execution_settings": [
5 | {
6 | "max_tokens": 512,
7 | "temperature": 0.2,
8 | "top_p": 0.0,
9 | "presence_penalty": 0.0,
10 | "frequency_penalty": 0.0
11 | }
12 | ],
13 | "input_variables": [
14 | {
15 | "name": "query_input",
16 | "description": "user question",
17 | "default": ""
18 | },
19 | {
20 | "name": "ans_result",
21 | "description": "knowledge base source",
22 | "default": ""
23 | }
24 | ]
25 | }
26 |
--------------------------------------------------------------------------------
/skv1_start/04-TransAndRag/Plugins/QAPlugin/AssistantResults/skprompt.txt:
--------------------------------------------------------------------------------
1 | 你是一位法規助理,使用者會詢問問題,請你協助回答,並且根據以下原則進行回答。
2 |
3 | 1. 當回應使用者的問題時,請仔細閱讀下面知識庫所提供的參考資料,以確保您的回答既簡短又具有針對性。
4 | 2. 假如沒有知識庫參考資料,就說無法回答,這很重要,一旦亂回答我將會失去我的工作,請你一定要記住。
5 | 3. 所有的回應,請思考使用者提問的語言,必須將回答翻譯成使用者的語言,以確保溝通無障礙,在翻譯過程中,都務必保留答案的原始意圖,避免添加或刪除任何可能改變答案意義的內容。
6 |
7 | #範例1
8 | 使用者提問:我想知道如何申請營業稅
9 | [知識庫參考資料-開始]
10 |
11 | [知識庫參考資料-結束]
12 |
13 | 回答:您好,由於我的知識庫參考資料並未提供相關資訊,因此我無法回答您的問題,謝謝您。
14 |
15 | #範例2
16 | 使用者提問:不禮讓行人罰款多少錢
17 | [知識庫參考資料-開始]
18 | 根據道路交通管理處罰條例第 43 條第 1 項規定,違反第 43 條第 1 項規定者,處新臺幣 300 元以上 600 元以下罰鍰。
19 | [知識庫參考資料-結束]
20 |
21 | 回答:您好,根據道路交通管理處罰條例第 43 條第 1 項規定,處新臺幣 300 元以上 600 元以下罰鍰。
22 |
23 |
24 | 這是使用者的提問
25 | ###
26 | {{$query_input}}
27 | ###
28 |
29 | 這是從知識庫所搜尋到的結果
30 | [知識庫參考資料-開始]
31 | {{$reference_content}}
32 | [知識庫參考資料-結束]
33 |
34 |
--------------------------------------------------------------------------------
/skv1_start/04-TransAndRag/Plugins/QAPlugin/Translate/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "description": "If it is not Traditional Chinese, please translate it into Traditional Chinese.",
4 | "execution_settings": [
5 | {
6 | "max_tokens": 1000,
7 | "temperature": 0.2,
8 | "top_p": 0.0,
9 | "presence_penalty": 0.0,
10 | "frequency_penalty": 0.0
11 | }
12 | ],
13 | "input_variables": [
14 | {
15 | "name": "query_input",
16 | "description": "user question content",
17 | "default": ""
18 | }
19 | ]
20 | }
21 |
--------------------------------------------------------------------------------
/skv1_start/04-TransAndRag/Plugins/QAPlugin/Translate/skprompt.txt:
--------------------------------------------------------------------------------
1 | 請你先分析以下文字的語言,如果是繁體中文就維持原內容,如果是其它語言,please translator to zh-tw
2 | ###
3 | {{$query_input}}
4 | ###
5 |
--------------------------------------------------------------------------------
/skv1_start/04-TransAndRag/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel.Plugins.Memory;
2 | using Microsoft.SemanticKernel;
3 | using Microsoft.SemanticKernel.Connectors.AI.OpenAI;
4 | using Microsoft.SemanticKernel.Memory;
5 | using System.Globalization;
6 | #pragma warning disable SKEXP0052
7 | #pragma warning disable SKEXP0011
8 | #pragma warning disable SKEXP0026
9 | #pragma warning disable SKEXP0003
10 |
11 | namespace TransAndRag
12 | {
13 | internal class Program
14 | {
15 |
16 | //AOAI
17 | private const string deploy_Model = "xxx";
18 | private const string gpt4ModelId = "xxx";
19 | private const string aoai_Endpoint = "https://xxx.openai.azure.com";
20 | private const string api_Key = "xxx";
21 | private const string embedding_DeploymentName = "xxx";
22 | private const string embedding_ModelId = "xxx";
23 | private const string embedding_CollectionName = "Law";
24 |
25 | static async Task Main(string[] args)
26 | {
27 | //AOAI
28 | var kernel = new KernelBuilder()
29 | .AddAzureOpenAIChatCompletion(
30 | deploymentName: deploy_Model,
31 | modelId: gpt4ModelId,
32 | endpoint: aoai_Endpoint,
33 | apiKey: api_Key)
34 | .Build();
35 |
36 | var memoryWithCustomDb = new MemoryBuilder()
37 | .WithAzureOpenAITextEmbeddingGeneration(embedding_DeploymentName, embedding_ModelId, aoai_Endpoint, api_Key)
38 | .WithMemoryStore(new VolatileMemoryStore())
39 | .Build();
40 |
41 | //Init KM
42 | await ImportKm(memoryWithCustomDb);
43 |
44 | // Import the Plugin from the plugins directory.
45 | var pluginsDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Plugins");
46 | var plugin = kernel.ImportPluginFromPromptDirectory(Path.Combine(pluginsDirectory, "QAPlugin"));
47 | KernelFunction assistantResultsFun = plugin["AssistantResults"];
48 | KernelFunction transFun = plugin["Translate"];
49 |
50 | #region show kernel plugins and functions
51 | // var functions = kernel.Plugins.GetFunctionsMetadata();
52 | // Console.WriteLine("*****************************************");
53 | // Console.WriteLine("****** Registered plugins and functions ******");
54 | // Console.WriteLine("*****************************************");
55 | // Console.WriteLine();
56 | // foreach (KernelFunctionMetadata func in functions)
57 | // {
58 | // Console.WriteLine($"func_Name > {func.Name}, func_Description > {func.Description}");
59 | // if (func.Parameters.Count > 0)
60 | // {
61 | // Console.WriteLine("func_Params > ");
62 | // foreach (var p in func.Parameters)
63 | // {
64 | // Console.WriteLine($"Parameter_Name > {p.Name}: {p.Description}");
65 | // Console.WriteLine($"Parameter_DefaultValue > '{p.DefaultValue}'");
66 | // }
67 | // }
68 | // }
69 | // Console.WriteLine("=========================================\n\n");
70 | #endregion
71 |
72 | while (true)
73 | {
74 | Console.WriteLine("Assistant > 您好,您想問什麼呢? ( What can I help you with? ) \n");
75 | Console.Write("User > ");
76 |
77 | var query = Console.ReadLine();
78 | Console.Write("\n");
79 |
80 | if (string.Compare(query, "exit", true) == 0)
81 | {
82 | Console.WriteLine("Assistant > bye........");
83 | break;
84 | }
85 |
86 | if (string.IsNullOrEmpty(query))
87 | {
88 | return;
89 | }
90 |
91 | //自動翻譯
92 | var transQuery = (await kernel.InvokeAsync(transFun, arguments: new()
93 | {{"query_input", query }})).ToString();
94 |
95 | //RAG Search
96 | var searchResult = memoryWithCustomDb
97 | .SearchAsync(embedding_CollectionName, transQuery, minRelevanceScore: 0.8);
98 |
99 | var refContent = string.Empty;
100 |
101 | await foreach (var kmResult in searchResult)
102 | {
103 | refContent += $"{kmResult.Metadata.Text}\n\n";
104 | }
105 |
106 | #region show kernel prompt render
107 |
108 | // kernel.PromptRendering += (sender, e) =>
109 | // {
110 | // Console.WriteLine("========== Prompt Rendering Start ================");
111 | // Console.WriteLine($"Function.Name => {e.Function.Name} ");
112 | // Console.WriteLine("========== Prompt Rendering End ================");
113 |
114 | // };
115 |
116 | // kernel.PromptRendered += (sender, e) =>
117 | // {
118 | // Console.WriteLine("========== Prompt Rendering Start ================");
119 | // Console.WriteLine($"RenderedPrompt => {e.RenderedPrompt} ");
120 | // Console.WriteLine("========== Prompt Rendering End ================");
121 | // };
122 |
123 | #endregion
124 |
125 | //return
126 | var assistantResult = await kernel.InvokeAsync(assistantResultsFun, arguments: new() { { "query_input", query }, { "reference_content", refContent } });
127 |
128 | Console.WriteLine($"Assistant > {assistantResult.GetValue()} \n \n");
129 | }
130 | }
131 |
132 | private static async Task ImportKm(ISemanticTextMemory memoryBuilder)
133 | {
134 | //知識庫轉存向量儲存
135 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第1條", text: "本細則依檔案法(以下簡稱本法)第二十九條規定訂定之。");
136 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第2條第1項", text: "本法第二條第二款所稱管理程序,指依文書處理或機關業務相關法令規定,完成核定、發文或辦結之程序。");
137 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第2條第2項", text: "本法第二條第二款所稱文字或非文字資料及其附件,指各機關處理公務或因公務而產生之各類紀錄資料及其附件,包括各機關所持有或保管之文書、圖片、紀錄、照片、錄影(音)、微縮片、電腦處理資料等,可供聽、讀、閱覽或藉助科技得以閱覽或理解之文書或物品。");
138 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第3條", text: "各機關管理檔案,應依本法第四條規定,並參照檔案中央主管機關訂定之機關檔案管理單位及人員配置基準,設置或指定專責單位或人員。");
139 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第4條第1項", text: "各機關依本法第五條規定,經該管機關核准,將檔案運往國外者,應先以微縮、電子或其他方式儲存,並經管理該檔案機關首長核定。");
140 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第4條第2項", text: "前項檔案如屬永久保存之機關檔案,並應經檔案中央主管機關同意。");
141 | await memoryBuilder.SaveInformationAsync(embedding_CollectionName, id: "第5條", text: "各機關依本法第六條第二項規定,將檔案中之器物交有關機構保管時,應訂定書面契約或作成紀錄存查。");
142 | }
143 | }
144 | }
145 |
146 | /*
147 | sample case :
148 | 1.永久保存的機關檔案可以做為公開資料嗎?
149 | 2.파일을 해외로 배송하는 데 제한이 있나요? (要把檔案運到國外,有什麼限制嗎)
150 | 3.公文書法で規制される内容とは何ですか? (檔案法所規範的內容是指哪些)
151 | 4.Can permanently preserved agency files be turned into public information?
152 | */
--------------------------------------------------------------------------------
/skv1_start/04-TransAndRag/TransAndRag.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net8.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | Always
20 |
21 |
22 | Always
23 |
24 |
25 | Always
26 |
27 |
28 | Always
29 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/skv1_start/05-EasySummaryClassification/05-EasySummaryClassification.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net8.0
6 | _05_EasySummaryClassification
7 | enable
8 | enable
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/skv1_start/05-EasySummaryClassification/Plugins/SummarizePlugin/Summarize/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "description": "總結給定的文本內容,並以json格式返回結果。",
4 | "execution_settings": {
5 | "default": {
6 | "max_tokens": 1024,
7 | "temperature": 0.2,
8 | "top_p": 0.0,
9 | "presence_penalty": 0.0,
10 | "frequency_penalty": 0.0
11 | }
12 | },
13 | "input_variables": [
14 | {
15 | "name": "user_input",
16 | "description": "Text to summarize",
17 | "default": "",
18 | "is_required": true
19 | }
20 | ]
21 | }
--------------------------------------------------------------------------------
/skv1_start/05-EasySummaryClassification/Plugins/SummarizePlugin/Summarize/skprompt.txt:
--------------------------------------------------------------------------------
1 | 你是一位專業的飯店客服人員,擅長判斷客人回饋的評論以及整理評論中的重點,
2 | 請你負責分析客戶的評論是正面或負面,正面請用positive,負面請用negative,
3 | 並且做內容重點摘要以及歸類該評論是屬於"硬體設備"、"服務態度"、"餐點"、"整潔度"的哪一項分類,
4 | 分析結果請採用以下json格式輸出
5 |
6 | 【總結規則】
7 | 不要廢話
8 | 使用簡短、清晰、完整的句子。
9 | 請勿使用要點或破折號。
10 | 最大化細節,意義
11 | 專注於內容
12 | 不要重複
13 |
14 | [範例]
15 | 總結:
16 | 預定公園景頂級房結果被升等到套房,太幸運了。原本想說就是看中公園頂級房的浴缸是面對公園景,所以才選購的,被通知升等的時候還有點擔心,但完全是多餘的擔心,因為在房間床上的時間絕對是大於在浴缸的時間,所以面公園的景緻在房間窗戶絕對是更好的。 (而且後來發現人如果在公園,往上看英迪格酒店,是會看得到房間的,也就是如果你人在公園頂級房的浴室裸體的話,窗簾是必須要先拉起來,等人入浴之後再開窗簾才會不會曝光) 整體體驗非常好,服務人員態度親切,只是沒有地下停車場,要停在後巷的配合停車場,要跟櫃台索取條碼,是不需要停車費的,但如果下雨提行李會很不方便。 房間真的沒有什麼缺點,床鋪很好躺,枕頭有多種選擇,電視的畫質其實不錯,不像其他評論的差(不知道是不是後來有更新過),還有膠囊咖啡機。 浴缸非常大可以一次兩個人泡,淋浴間也很大,三個人可以一起洗,但是浴室如果有暖氣會更好,不然出來的時候很冷。 還有雙面盆,吹風機風力很強。 早餐中規中矩,有主餐可以選。 入住可以跟櫃台索取IHG的飲料券,可以兌換頂樓酒吧的紅白酒或是一樓的咖啡冷飲等。 走路一分鐘就是中央公園捷運站,非常方便的地點,值得再來。
17 |
18 | [輸出json格式]
19 | {
20 | "summary":"客人原本預定公園景頂級房,但被升等到套房,感到非常幸運。雖然一開始有些擔心因為特別看中原房間的浴缸景觀,但最終發現升等後的房間更好。服務人員態度親切,房間舒適,床鋪和枕頭多樣化,電視畫質好,提供膠囊咖啡機。浴室設施寬敞,但若加裝暖氣會更佳。早餐品質中等,酒店位置便利。",
21 | "Emotion":"positive",
22 | "Classification":"硬體設備"
23 | }
24 |
25 |
26 | 客戶評論
27 | {{$user_input}}
28 |
29 | [輸出json格式]
30 | {
31 | "summary":"......",
32 | "Emotion":"...",
33 | "Classification":"..."
34 | }
--------------------------------------------------------------------------------
/skv1_start/05-EasySummaryClassification/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Http;
2 | using Microsoft.SemanticKernel;
3 |
4 | string gpt4DeploymentName = "XXX";
5 | string modelId = "XXX";
6 | string azureOpenAIEndpoint = "https://XXX.openai.azure.com/";
7 | string azureOpenAIApiKey = "XXX";
8 | string currentDirectory = Directory.GetCurrentDirectory();
9 |
10 |
11 | /*
12 | 注意:本範例尚未更新為SK1.0版本
13 | */
14 |
15 | Kernel kernel = Kernel.CreateBuilder()
16 | .AddAzureOpenAIChatCompletion(
17 | deploymentName: gpt4DeploymentName,
18 | endpoint: azureOpenAIEndpoint,
19 | apiKey: azureOpenAIApiKey,
20 | modelId: modelId)
21 | .Build();
22 |
23 | // Import the Plugin from the plugins directory.
24 | var pluginsDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Plugins");
25 | var plugin = kernel.ImportPluginFromPromptDirectory(Path.Combine(pluginsDirectory, "SummarizePlugin"));
26 | KernelFunction summarizeFun = plugin["Summarize"];
27 |
28 | while (true)
29 | {
30 | Console.WriteLine("Assistant > 您好,請留下您的寶貴意見 \n");
31 | Console.Write("User > ");
32 | var user_Input = Console.ReadLine();
33 | Console.Write("\n");
34 |
35 | if (string.Compare(user_Input, "exit", true) == 0)
36 | {
37 | Console.WriteLine("Assistant > bye........");
38 | break;
39 | }
40 |
41 | var result = (await kernel.InvokeAsync(summarizeFun, arguments: new()
42 | {
43 | { "user_input", user_Input }
44 | })).ToString();
45 |
46 | Console.WriteLine($"Assistant > {result} \n \n");
47 |
48 | }
49 |
50 | /*
51 | sample case
52 |
53 | 1.為了來阿里山,所以入住阿里山英迪格。飯店的位置有他先天的限制,座落在被民宅包圍,離阿里山森林遊樂區還有一小時的車程,對於幻想可以衝到祝山看日出的旅客,除非開車,否則是有難度的,因此,我們是抱著不看日出,隨遇而安的心情來的。必須讚美一下飯店的接駁行程,讓我們輕易的前往奮起湖,又能暢遊阿里山森林遊樂區,對於只靠雙腿的遊客真的幫助很大。飯店很新(廢話),很高科技,用AI可以播音樂,開燈,關電視之類的,適合懶人,前提是要先讓她聽得懂中文(大笑)。標準房的房間其實不算大,但也足夠四個人一起聊天哈啦。比較奇怪是無浴缸的房型,浴室也很大,感覺比例不太協調,導致走道很小,但缺點的反面是優點,上廁所就沒有壓迫感XDDD。早餐我覺得蠻不錯,提供的麵包類都很好吃,特別是馬告生吐司,各類可頌等,餐點總類不是最多,但也提供了多樣選擇,尤其是加入很多阿里山當地的食材。房間的零食飲料都是免費享用,這點非常體貼。不過,我還是忍不住要評論房間的地毯,尤其穿着襪子跟飯店拖鞋要特別當心,地毯與地板的高低差太容易被絆倒跟腳滑。
54 |
55 | 2.本來看到了負評有點擔心,實際入住後,發現很優質很滿意啊!入住的是七樓山景房,房間看出去遠眺山景,視野開闊。四點入住後到頂樓,有無邊際溫水游泳池和熱水池,提供毛巾浴袍和水,還有美麗的雲海相伴,晚上點燈更氣氛很迷人!晚餐是另外自費半自助式套餐,雖然一個人3千多不算便宜,但主食(我們點黑毛牛排)很好吃,自助式的餐點雖然不大但每道都很好吃,甚至有不少很新鮮的海鮮,廣島生蠔另人驚艷,非常肥美!頂樓就可以看日出也是賣點,不必一早4點就上祝山還不見得看得到,櫃台很貼心告知大約日出時刻,睡到時間差不多直接上頂樓就可以欣賞啦!早餐小而美,選擇雖然不是非常多,但細節用心,肉鬆不是用廉價豆粉而是有肉脯的,有現做蛋料理,麵類都很美味!終於有阿里山賓館外的好飯店可以選擇了,下次還會選擇英迪格來住!
56 |
57 | 3.來慶生覺得很雷訂了兩間房一間雙床房給長輩,另一間一張大床房給我們自己慶生,結果居然兩間都給我們雙床房,我確認過很多次確定自己是訂對的房型甚至事先打電話確認細節,結果還是出錯。原本以為是佈置好才會讓我們上去結果我們在房門口遇到來送蛋糕的員工整個就很尷尬。因為我們提早到,就在大廳等但沒有跟我們說茶飲在哪裡是我們自己看到自己拿但其他人就是裝好送過去。短髮櫃檯人員服務態度完全感覺不到是五星級飯店該有的樣子,非常冷淡而且其他服務人員告知其他房客的資訊也都沒有說,不知道是不是因為我們買專案價格所以差別待遇,總之感受很差。等電梯要等很久因為全部只有兩部,早餐晚餐還不錯但飲料選擇很少基本上只有鋁箔包的果汁跟鋁罐裝的飲料。入住時間是下午四點但check out時間是十一點,除了頂樓外沒什麼設施可以使用,入住二樓跟五樓基本上是完全沒有景而且房間偏小。結論大概就是沒有這個價位該有的服務品質跟景色,對整體體驗非常失望。
58 |
59 | */
--------------------------------------------------------------------------------
/skv1_start/readme.md:
--------------------------------------------------------------------------------
1 | # 說明
2 |
3 | 本範例區將以Semantic Kernel v1.0 (含1.x)為主,並提供SK入門範例,以快速學習SK為目標,範例將逐一增加,為降低學習門框所有範例以主控台應用為主
4 |
5 | ## 參考資源
6 |
7 | - 我的Blog: https://medium.com/@ianchen_27500
8 | - SK官方網站: https://learn.microsoft.com/en-us/semantic-kernel/overview/
9 |
10 |
11 |
--------------------------------------------------------------------------------
/skv1_start/skv1_start.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.8.34330.188
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "01-GetStart", "01-GetStart\01-GetStart.csproj", "{3F2D8E65-5805-4173-BA15-A8601B8F4264}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "02-NativeFunc", "02-NativeFunc\02-NativeFunc.csproj", "{6C91DCC2-7436-4393-A82B-AE332AD5B944}"
9 | EndProject
10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "03-MultiSemanticFuncs", "03-MultiSemanticFuncs\03-MultiSemanticFuncs.csproj", "{E85140AD-D5B7-47FA-BE81-6611A7BD390C}"
11 | EndProject
12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TransAndRag", "04-TransAndRag\TransAndRag.csproj", "{50470A68-39A1-4178-AC81-78CF0CEA0E02}"
13 | EndProject
14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "05-EasySummaryClassification", "05-EasySummaryClassification\05-EasySummaryClassification.csproj", "{55C40090-230F-47AA-9F60-FB35A555F1C6}"
15 | EndProject
16 | Global
17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
18 | Debug|Any CPU = Debug|Any CPU
19 | Release|Any CPU = Release|Any CPU
20 | EndGlobalSection
21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
22 | {3F2D8E65-5805-4173-BA15-A8601B8F4264}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
23 | {3F2D8E65-5805-4173-BA15-A8601B8F4264}.Debug|Any CPU.Build.0 = Debug|Any CPU
24 | {3F2D8E65-5805-4173-BA15-A8601B8F4264}.Release|Any CPU.ActiveCfg = Release|Any CPU
25 | {3F2D8E65-5805-4173-BA15-A8601B8F4264}.Release|Any CPU.Build.0 = Release|Any CPU
26 | {6C91DCC2-7436-4393-A82B-AE332AD5B944}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27 | {6C91DCC2-7436-4393-A82B-AE332AD5B944}.Debug|Any CPU.Build.0 = Debug|Any CPU
28 | {6C91DCC2-7436-4393-A82B-AE332AD5B944}.Release|Any CPU.ActiveCfg = Release|Any CPU
29 | {6C91DCC2-7436-4393-A82B-AE332AD5B944}.Release|Any CPU.Build.0 = Release|Any CPU
30 | {E85140AD-D5B7-47FA-BE81-6611A7BD390C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
31 | {E85140AD-D5B7-47FA-BE81-6611A7BD390C}.Debug|Any CPU.Build.0 = Debug|Any CPU
32 | {E85140AD-D5B7-47FA-BE81-6611A7BD390C}.Release|Any CPU.ActiveCfg = Release|Any CPU
33 | {E85140AD-D5B7-47FA-BE81-6611A7BD390C}.Release|Any CPU.Build.0 = Release|Any CPU
34 | {50470A68-39A1-4178-AC81-78CF0CEA0E02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
35 | {50470A68-39A1-4178-AC81-78CF0CEA0E02}.Debug|Any CPU.Build.0 = Debug|Any CPU
36 | {50470A68-39A1-4178-AC81-78CF0CEA0E02}.Release|Any CPU.ActiveCfg = Release|Any CPU
37 | {50470A68-39A1-4178-AC81-78CF0CEA0E02}.Release|Any CPU.Build.0 = Release|Any CPU
38 | {55C40090-230F-47AA-9F60-FB35A555F1C6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
39 | {55C40090-230F-47AA-9F60-FB35A555F1C6}.Debug|Any CPU.Build.0 = Debug|Any CPU
40 | {55C40090-230F-47AA-9F60-FB35A555F1C6}.Release|Any CPU.ActiveCfg = Release|Any CPU
41 | {55C40090-230F-47AA-9F60-FB35A555F1C6}.Release|Any CPU.Build.0 = Release|Any CPU
42 | EndGlobalSection
43 | GlobalSection(SolutionProperties) = preSolution
44 | HideSolutionNode = FALSE
45 | EndGlobalSection
46 | GlobalSection(ExtensibilityGlobals) = postSolution
47 | SolutionGuid = {091D25FC-49E1-4FE7-8016-A7A44B623095}
48 | EndGlobalSection
49 | EndGlobal
50 |
--------------------------------------------------------------------------------