├── .devcontainer
├── devcontainer.json
└── post-create.sh
├── .editorconfig
├── .gitattributes
├── .github
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
├── ado-compliance.yml
├── dependabot.yml
├── pull_request_template.md
└── workflows
│ ├── codeql-analysis.yml
│ ├── dotnet-ci.yml
│ ├── dotnet-format.yml
│ ├── dotnet-pr.yml
│ └── update-version.sh
├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── SECURITY.md
├── SUPPORT.md
├── sk-csharp-azure-functions
├── .vscode
│ ├── extensions.json
│ ├── launch.json
│ ├── settings.json
│ └── tasks.json
├── Directory.Build.props
├── Directory.Build.targets
├── ExecuteFunctionEndpoint.cs
├── Models
│ ├── ErrorResponse.cs
│ ├── ExecuteFunctionRequest.cs
│ └── ExecuteFunctionResponse.cs
├── Program.cs
├── README.md
├── config
│ ├── EndpointTypes.cs
│ ├── KernelBuilderExtensions.cs
│ ├── KernelSettings.cs
│ ├── ServiceTypes.cs
│ ├── appsettings.json.azure-example
│ └── appsettings.json.openai-example
├── host.json
├── local.settings.json
├── sk-csharp-azure-functions.csproj
└── skills
│ └── FunSkill
│ ├── Excuses
│ ├── config.json
│ └── skprompt.txt
│ ├── Joke
│ ├── config.json
│ └── skprompt.txt
│ └── Limerick
│ ├── config.json
│ └── skprompt.txt
├── sk-csharp-chatgpt-plugin
├── .gitignore
├── .vscode
│ ├── extensions.json
│ ├── launch.json
│ ├── settings.json
│ └── tasks.json
├── README.md
├── azure-function
│ ├── AiPluginJson.cs
│ ├── Directory.Build.props
│ ├── Directory.Build.targets
│ ├── Extensions
│ │ ├── AIPluginRunner.cs
│ │ ├── IAIPluginRunner.cs
│ │ ├── KernelBuilderExtensions.cs
│ │ └── KernelExtensions.cs
│ ├── Logo.cs
│ ├── Models
│ │ ├── AiPluginSettings.cs
│ │ ├── AppSettings.cs
│ │ ├── KernelSettings.cs
│ │ └── ServiceTypes.cs
│ ├── Program.cs
│ ├── Prompts
│ │ └── Joke
│ │ │ ├── config.json
│ │ │ └── skprompt.txt
│ ├── appsettings.json
│ ├── config-samples
│ │ ├── appsettings.json.azure-example
│ │ └── appsettings.json.openai-example
│ ├── host.json
│ ├── local.settings.json.example
│ ├── logo.png
│ └── sk-chatgpt-azure-function.csproj
└── semantic-functions-generator
│ ├── Extensions
│ └── GeneratorExecutionContextExtensions.cs
│ ├── Models
│ └── PromptConfig.cs
│ ├── SemanticFunctionGenerator.cs
│ └── semantic-functions-generator.csproj
├── sk-csharp-console-chat
├── .gitignore
├── .vscode
│ ├── launch.json
│ └── tasks.json
├── ConsoleChat.cs
├── Program.cs
├── README.md
├── config
│ ├── KernelSettings.cs
│ ├── ServiceCollectionExtensions.cs
│ ├── ServiceTypes.cs
│ ├── appsettings.json.azure-example
│ └── appsettings.json.openai-example
├── plugins
│ └── LightPlugin.cs
├── sk-csharp-console-chat.csproj
└── sk-csharp-console-chat.sln
├── sk-csharp-hello-world
├── .gitignore
├── .vscode
│ ├── extensions.json
│ ├── launch.json
│ ├── settings.json
│ └── tasks.json
├── Program.cs
├── README.md
├── config
│ ├── EndpointTypes.cs
│ ├── KernelSettings.cs
│ ├── ServiceCollectionExtensions.cs
│ ├── ServiceTypes.cs
│ ├── appsettings.json.azure-example
│ └── appsettings.json.openai-example
├── plugins
│ └── LightPlugin.cs
├── prompts
│ └── Chat.yaml
├── sk-csharp-hello-world.csproj
└── sk-csharp-hello-world.sln
├── sk-java-hello-world
├── README.md
├── example.conf.properties
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── com
│ │ └── microsoft
│ │ └── semantickernel
│ │ └── helloworld
│ │ └── Main.java
│ └── resources
│ └── skills
│ └── FunSkill
│ ├── Excuses
│ ├── config.json
│ └── skprompt.txt
│ ├── Joke
│ ├── config.json
│ └── skprompt.txt
│ └── Limerick
│ ├── config.json
│ └── skprompt.txt
├── sk-process-framework
├── declarative
│ └── ProductDocumentation
│ │ ├── README.md
│ │ ├── images
│ │ ├── debug-process.jpeg
│ │ ├── preview-process.jpeg
│ │ └── select-model.jpeg
│ │ └── product-documentation.process.yaml
├── dotnet
│ └── ProductDocumentation
│ │ ├── ProductDocumentation.csproj
│ │ ├── README.md
│ │ ├── Steps
│ │ ├── GenerateDocumentationStep.cs
│ │ ├── GetProductInfoStep.cs
│ │ └── PublishDocumentationStep.cs
│ │ ├── images
│ │ ├── debug-process.jpeg
│ │ ├── preview-process.jpeg
│ │ └── select-model.jpeg
│ │ └── product-documentation.process.yaml
└── other
│ └── ProductDocumentation
│ ├── Filters
│ └── ConsoleOutputFunctionInvocationFilter.cs
│ ├── ProductDocumentation.csproj
│ ├── Program.cs
│ ├── README.md
│ ├── Steps
│ ├── GenerateDocumentationStep.cs
│ ├── GetProductInfoStep.cs
│ └── PublishDocumentationStep.cs
│ ├── images
│ ├── debug-process.jpeg
│ ├── preview-process.jpeg
│ └── select-model.jpeg
│ └── product-documentation.process.yaml
├── sk-python-azure-functions-chatgpt-plugin
├── .env.example
├── .funcignore
├── .gitignore
├── .vscode
│ ├── extensions.json
│ ├── launch.json
│ ├── settings.json
│ └── tasks.json
├── .well-known
│ └── ai-plugin.json
├── README.md
├── function_app.py
├── getting_started.md
├── host.json
├── local.settings.json
├── logo.png
├── openapi.yaml
├── requirements.txt
└── skills
│ └── FunSkill
│ ├── Excuses
│ ├── config.json
│ └── skprompt.txt
│ ├── Joke
│ ├── config.json
│ └── skprompt.txt
│ └── Limerick
│ ├── config.json
│ └── skprompt.txt
├── sk-python-azure-functions
├── .env.example
├── .funcignore
├── .gitignore
├── .vscode
│ ├── extensions.json
│ ├── launch.json
│ ├── settings.json
│ └── tasks.json
├── README.md
├── function_app.py
├── getting_started.md
├── host.json
├── local.settings.json
├── requirements.txt
└── skills
│ └── FunSkill
│ ├── Excuses
│ ├── config.json
│ └── skprompt.txt
│ ├── Joke
│ ├── config.json
│ └── skprompt.txt
│ └── Limerick
│ ├── config.json
│ └── skprompt.txt
├── sk-python-flask-chatgpt-plugin
├── .env.example
├── .gitignore
├── .vscode
│ ├── extensions.json
│ ├── launch.json
│ ├── settings.json
│ └── tasks.json
├── .well-known
│ └── ai-plugin.json
├── README.md
├── logo.png
├── openapi.yaml
├── poetry.lock
├── pyproject.toml
├── sk_python_flask_chatgpt_plugin
│ ├── __init__.py
│ ├── app.py
│ ├── config.py
│ └── kernel_utils.py
└── skills
│ └── FunSkill
│ ├── Excuses
│ ├── config.json
│ └── skprompt.txt
│ ├── Joke
│ ├── config.json
│ └── skprompt.txt
│ └── Limerick
│ ├── config.json
│ └── skprompt.txt
├── sk-python-hello-world
├── .env.example
├── .gitignore
├── .vscode
│ ├── extensions.json
│ ├── launch.json
│ ├── settings.json
│ └── tasks.json
├── README.md
├── hello_world
│ ├── __init__.py
│ └── main.py
├── poetry.lock
├── pyproject.toml
└── skills
│ └── FunSkill
│ ├── Excuses
│ ├── config.json
│ └── skprompt.txt
│ ├── Joke
│ ├── config.json
│ └── skprompt.txt
│ └── Limerick
│ ├── config.json
│ └── skprompt.txt
├── sk-starters.sln
├── sk-typescript-console-chat
├── .eslintrc.json
├── .gitignore
├── consoleChat.ts
├── consoleColours.ts
├── package-lock.json
├── package.json
├── readme.md
├── sk-typescript-console-chat.csproj
└── tsconfig.json
└── sk_csharp_apim_demo
├── BearerTokenCredential.cs
├── Program.cs
├── sk_csharp_apim_demo.csproj
└── skills
└── FunSkill
├── Excuses
├── config.json
└── skprompt.txt
├── Joke
├── config.json
└── skprompt.txt
└── Limerick
├── config.json
└── skprompt.txt
/.devcontainer/devcontainer.json:
--------------------------------------------------------------------------------
1 | // For format details, see https://aka.ms/devcontainer.json. For config options, see the
2 | // README at: https://github.com/devcontainers/templates/tree/main/src/dotnet
3 | {
4 | "name": "Semantic Kernel Starters",
5 | // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
6 | "image": "mcr.microsoft.com/devcontainers/dotnet:0-6.0",
7 | "features": {
8 | "ghcr.io/devcontainers/features/python:1": {},
9 | "ghcr.io/devcontainers-contrib/features/poetry:2": {},
10 | "ghcr.io/jlaundry/devcontainer-features/azure-functions-core-tools:1": {}
11 | },
12 |
13 | // Use 'forwardPorts' to make a list of ports inside the container available locally.
14 | "forwardPorts": [7071],
15 |
16 | // Use 'postCreateCommand' to run commands after the container is created.
17 | "postCreateCommand": "bash ./.devcontainer/post-create.sh",
18 | "customizations": {
19 | "vscode": {
20 | "extensions": [
21 | "ms-semantic-kernel.semantic-kernel",
22 | "GitHub.copilot"
23 | ]
24 | }
25 | },
26 |
27 | // Configure tool-specific properties.
28 | // "customizations": {},
29 |
30 | // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
31 | // "remoteUser": "root"
32 | }
33 |
--------------------------------------------------------------------------------
/.devcontainer/post-create.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | pwd
3 |
4 | # loop through all the python directories and install the dependencies
5 | for d in */ ; do
6 | echo "Installing dependencies for $d"
7 | cd $d
8 |
9 | # Check for a requirements.txt file
10 | if [ -f "requirements.txt" ]; then
11 |
12 | # Create a virtual environment
13 | python -m venv .venv
14 |
15 | # Activate the virtual environment
16 | source .venv/bin/activate
17 |
18 | pip install -r requirements.txt
19 |
20 | # Deactivate the virtual environment
21 | deactivate
22 | fi
23 |
24 | # check for a poetry.lock file
25 | if [ -f "poetry.lock" ]; then
26 | poetry install
27 | fi
28 |
29 | cd ..
30 | done
31 |
32 | # Restore the dotnet projects
33 | dotnet restore
34 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto-detect text files, ensure they use LF.
2 | * text=auto eol=lf working-tree-encoding=UTF-8
3 |
4 | # Bash scripts
5 | *.sh text eol=lf
6 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, add screenshots to help explain your problem.
25 |
26 | **Desktop (please complete the following information):**
27 | - OS: [e.g. Windows]
28 | - IDE: [e.g. Visual Studio, VS Code]
29 | - NuGet Package Version [e.g. 0.1.0]
30 |
31 | **Additional context**
32 | Add any other context about the problem here.
33 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | ---
11 | name: Feature request
12 | about: Suggest an idea for this project
13 |
14 | ---
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/.github/ado-compliance.yml:
--------------------------------------------------------------------------------
1 | trigger:
2 | - main
3 |
4 | # no PR triggers
5 | pr: none
6 |
7 | pool:
8 | vmImage: 'windows-latest'
9 |
10 | steps:
11 | - task: CredScan@3
12 |
13 | # Uncomment this section when TS/JS is checked in
14 | # - task: ESLint@1
15 | # inputs:
16 | # Configuration: 'recommended'
17 | # TargetType: 'eslint'
18 | # ErrorLevel: 'warn'
19 |
20 | - task: UseDotNet@2
21 | displayName: 'Use .NET 7.0'
22 | inputs:
23 | packageType: 'sdk'
24 | version: '7.x'
25 |
26 | - task: Semmle@1
27 | env:
28 | SYSTEM_ACCESSTOKEN: $(System.AccessToken)
29 | inputs:
30 | sourceCodeDirectory: '$(Build.SourcesDirectory)'
31 | language: 'csharp'
32 | querySuite: 'Recommended'
33 | timeout: '1800'
34 | ram: '16384'
35 | addProjectDirToScanningExclusionList: true
36 |
37 | # Uncomment this section when Python is checked in
38 | # - task: Semmle@1
39 | # inputs:
40 | # sourceCodeDirectory: '$(Build.SourcesDirectory)'
41 | # language: 'python'
42 | # querySuite: 'Recommended'
43 | # timeout: '1800'
44 | # ram: '16384'
45 | # addProjectDirToScanningExclusionList: true
46 |
47 | # Usage of System.AccessToken is only required for uploading
48 | # results to CodeQL servers via variable LGTM.UploadSnapshot = true
49 | # If you want to analyze errors on your own or if LGTM.UploadSnapshot = false,
50 | # then passing this environment variable is not required.
51 |
52 | #######################################################
53 | # Highly Discouraged, only for backward compatibility #
54 | #######################################################
55 | # When code is hosted on GitHub and build pipeline is created on ADO then a PAT token can be used in place of AccessToken as part of environment variable
56 | # SYSTEM_ACCESSTOKEN: $(PATToken)
57 | # Where PATToken is name of the variable and value contains the actual PAT token generated by user
58 |
59 | - task: ComponentGovernanceComponentDetection@0
60 | inputs:
61 | scanType: 'Register'
62 | verbosity: 'Verbose'
63 | alertWarningLevel: 'High'
64 |
65 | - task: PublishSecurityAnalysisLogs@3
66 | inputs:
67 | ArtifactName: 'CodeAnalysisLogs'
68 | ArtifactType: 'Container'
69 | AllTools: true
70 | ToolLogsNotFoundAction: 'Standard'
71 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | # To get started with Dependabot version updates, you'll need to specify which
2 | # package ecosystems to update and where the package manifests are located.
3 | # Please see the documentation for all configuration options:
4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
5 |
6 | version: 2
7 | updates:
8 | - package-ecosystem: "nuget" # See documentation for possible values
9 | directory: "/" # Location of package manifests
10 | schedule:
11 | interval: "weekly"
12 |
13 | - package-ecosystem: "github-actions"
14 | # Workflow files stored in the
15 | # default location of `.github/workflows`
16 | directory: "/"
17 | schedule:
18 | interval: "weekly"
19 |
--------------------------------------------------------------------------------
/.github/pull_request_template.md:
--------------------------------------------------------------------------------
1 | ### Motivation and Context
2 |
9 |
10 |
11 | ### Description
12 |
14 |
15 |
16 | ### Contribution Checklist
17 |
18 | - [ ] The code builds clean without any errors or warnings
19 | - [ ] The PR follows SK Contribution Guidelines (https://github.com/microsoft/semantic-kernel-starters/blob/main/CONTRIBUTING.md)
20 | - [ ] The code follows the .NET coding conventions (https://learn.microsoft.com/dotnet/csharp/fundamentals/coding-style/coding-conventions) verified with `dotnet format`
21 | - [ ] All unit tests pass, and I have added new tests where possible
22 | - [ ] I didn't break anyone :smile:
23 |
--------------------------------------------------------------------------------
/.github/workflows/codeql-analysis.yml:
--------------------------------------------------------------------------------
1 | # CodeQL is the code analysis engine developed by GitHub to automate security checks.
2 | # The results are shown as code scanning alerts in GitHub. For more details, visit:
3 | # https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/about-code-scanning-with-codeql
4 |
5 | name: "CodeQL"
6 |
7 | on:
8 | push:
9 | branches: [ "main", "experimental*", "feature*" ]
10 | schedule:
11 | - cron: '17 11 * * 2'
12 |
13 | jobs:
14 | analyze:
15 | name: Analyze
16 | runs-on: ubuntu-latest
17 | permissions:
18 | actions: read
19 | contents: read
20 | security-events: write
21 |
22 | strategy:
23 | fail-fast: false
24 | matrix:
25 | language: [ 'csharp', 'python' ]
26 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
27 | # Use only 'java' to analyze code written in Java, Kotlin or both
28 | # Use only 'javascript' to analyze code written in JavaScript, TypeScript or both
29 | # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
30 |
31 | steps:
32 | - name: Checkout repository
33 | uses: actions/checkout@v3
34 |
35 | # Initializes the CodeQL tools for scanning.
36 | - name: Initialize CodeQL
37 | uses: github/codeql-action/init@v2
38 | with:
39 | languages: ${{ matrix.language }}
40 | # If you wish to specify custom queries, you can do so here or in a config file.
41 | # By default, queries listed here will override any specified in a config file.
42 | # Prefix the list here with "+" to use these queries and those in the config file.
43 |
44 | # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
45 | # queries: security-extended,security-and-quality
46 |
47 |
48 | # Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java).
49 | # If this step fails, then you should remove it and run the build manually (see below)
50 | - name: Autobuild
51 | uses: github/codeql-action/autobuild@v2
52 |
53 | # ℹ️ Command-line programs to run using the OS shell.
54 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
55 |
56 | # If the Autobuild fails above, remove it and uncomment the following three lines.
57 | # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
58 |
59 | # - run: |
60 | # echo "Run, Build Application using script"
61 | # ./location_of_script_within_repo/buildscript.sh
62 |
63 | - name: Perform CodeQL Analysis
64 | uses: github/codeql-action/analyze@v2
65 | with:
66 | category: "/language:${{matrix.language}}"
67 |
--------------------------------------------------------------------------------
/.github/workflows/dotnet-ci.yml:
--------------------------------------------------------------------------------
1 | #
2 | # This workflow will build and run all unit tests.
3 | #
4 |
5 | name: dotnet-ci
6 |
7 | on:
8 | workflow_dispatch:
9 | push:
10 | branches: [ "main", "feature*" ]
11 |
12 | permissions:
13 | contents: read
14 |
15 | jobs:
16 | build:
17 | strategy:
18 | matrix:
19 | os: [ubuntu-latest, windows-latest]
20 | configuration: [Release, Debug]
21 | runs-on: ${{ matrix.os }}
22 | env:
23 | NUGET_CERT_REVOCATION_MODE: offline
24 | steps:
25 | - uses: actions/checkout@v3
26 | with:
27 | clean: true
28 |
29 | - name: Setup .NET
30 | uses: actions/setup-dotnet@v3
31 | with:
32 | dotnet-version: 6.0.x
33 |
34 | - uses: actions/cache@v3
35 | with:
36 | path: ~/.nuget/packages
37 | # Look to see if there is a cache hit for the corresponding requirements file
38 | key: ${{ runner.os }}-nuget-${{ hashFiles('**/packages.lock.json') }}
39 | restore-keys: |
40 | ${{ runner.os }}-nuget
41 |
42 | - name: Find solutions
43 | shell: bash
44 | run: echo "solutions=$(find . -type f -name "*.sln" | tr '\n' ' ')" >> $GITHUB_ENV
45 |
46 | - name: Restore dependencies
47 | shell: bash
48 | run: |
49 | for solution in ${{ env.solutions }}; do
50 | dotnet restore $solution
51 | done
52 |
53 | - name: Build
54 | shell: bash
55 | run: |
56 | for solution in ${{ env.solutions }}; do
57 | dotnet build $solution --no-restore --configuration ${{ matrix.configuration }}
58 | done
59 |
60 | - name: Find unit test projects
61 | shell: bash
62 | run: echo "projects=$(find . -type f -name "*.UnitTests.csproj" | tr '\n' ' ')" >> $GITHUB_ENV
63 |
--------------------------------------------------------------------------------
/.github/workflows/dotnet-format.yml:
--------------------------------------------------------------------------------
1 | #
2 | # This workflow runs the dotnet formatter on all c-sharp code.
3 | #
4 |
5 | name: dotnet-format
6 |
7 | on:
8 | workflow_dispatch:
9 | pull_request:
10 | branches: [ "main", "feature*" ]
11 |
12 | jobs:
13 | check-format:
14 | runs-on: ubuntu-latest
15 |
16 | steps:
17 | - name: Check out code
18 | uses: actions/checkout@v3
19 | with:
20 | fetch-depth: 0
21 |
22 | - name: Get changed files
23 | id: changed-files
24 | uses: jitterbit/get-changed-files@v1
25 |
26 | - name: No C# files changed
27 | id: no-csharp
28 | if: steps.changed-files.outputs.added_modified == ''
29 | run: echo "No C# files changed"
30 |
31 | # This step will loop over the changed files and find the nearest .csproj file for each one, then store the unique csproj files in a variable
32 | - name: Find csproj files
33 | id: find-csproj
34 | if: steps.changed-files.outputs.added_modified != ''
35 | run: |
36 | csproj_files=()
37 | for file in ${{ steps.changed-files.outputs.added_modified }}; do
38 | echo "$file was changed"
39 | dir="$GITHUB_WORKSPACE/$file"
40 | while [[ $dir != "." && $dir != "/" && $dir != $GITHUB_WORKSPACE ]]; do
41 | if find "$dir" -maxdepth 1 -name "*.csproj" -print -quit | grep -q .; then
42 | csproj_files+=("$(find "$dir" -maxdepth 1 -name "*.csproj" -print -quit)")
43 | break
44 | fi
45 | dir=$(dirname $dir)
46 | done
47 | done
48 | csproj_files=($(printf "%s\n" "${csproj_files[@]}" | sort -u))
49 | echo "Found ${#csproj_files[@]} unique csproj files: ${csproj_files[*]}"
50 | echo "::set-output name=csproj_files::${csproj_files[*]}"
51 |
52 | - name: Install dotnet-format tool
53 | if: steps.changed-files.outputs.added_modified != ''
54 | run: dotnet tool install -g dotnet-format
55 |
56 | # This step will run dotnet format on each of the unique csproj files and fail if any changes are made
57 | - name: Run dotnet format
58 | if: steps.changed-files.outputs.added_modified != ''
59 | run: |
60 | for csproj in ${{ steps.find-csproj.outputs.csproj_files }}; do
61 | echo "Running dotnet format on $csproj"
62 | dotnet format $csproj --verify-no-changes --verbosity detailed
63 | done
64 |
--------------------------------------------------------------------------------
/.github/workflows/dotnet-pr.yml:
--------------------------------------------------------------------------------
1 | #
2 | # This workflow will build and run all unit tests.
3 | #
4 |
5 | name: dotnet-pr
6 |
7 | on:
8 | workflow_dispatch:
9 | pull_request:
10 | branches: [ "main", "feature*" ]
11 |
12 | permissions:
13 | contents: read
14 |
15 | jobs:
16 | build:
17 | strategy:
18 | matrix:
19 | os: [ubuntu-latest]
20 | configuration: [Release, Debug]
21 | runs-on: ${{ matrix.os }}
22 | env:
23 | NUGET_CERT_REVOCATION_MODE: offline
24 | steps:
25 | - uses: actions/checkout@v3
26 | with:
27 | clean: true
28 |
29 | - name: Setup .NET
30 | uses: actions/setup-dotnet@v3
31 | with:
32 | dotnet-version: 8.0.x
33 | env:
34 | NUGET_AUTH_TOKEN: ${{ secrets.GPR_READ_TOKEN }}
35 |
36 | - uses: actions/cache@v3
37 | with:
38 | path: ~/.nuget/packages
39 | # Look to see if there is a cache hit for the corresponding requirements file
40 | key: ${{ runner.os }}-nuget-${{ hashFiles('**/packages.lock.json') }}
41 | restore-keys: |
42 | ${{ runner.os }}-nuget
43 |
44 | - name: Find solutions
45 | shell: bash
46 | run: echo "solutions=$(find ./ -type f -name "*.sln" | tr '\n' ' ')" >> $GITHUB_ENV
47 |
48 | - name: Restore dependencies
49 | shell: bash
50 | run: |
51 | for solution in ${{ env.solutions }}; do
52 | dotnet restore $solution
53 | done
54 |
55 | - name: Build
56 | shell: bash
57 | run: |
58 | for solution in ${{ env.solutions }}; do
59 | dotnet build $solution --no-restore --configuration ${{ matrix.configuration }}
60 | done
61 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Microsoft Open Source Code of Conduct
2 |
3 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
4 |
5 | Resources:
6 |
7 | - [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/)
8 | - [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
9 | - Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns
10 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) Microsoft Corporation.
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 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## Security
4 |
5 | Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/).
6 |
7 | If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/opensource/security/definition), please report it to us as described below.
8 |
9 | ## Reporting Security Issues
10 |
11 | **Please do not report security vulnerabilities through public GitHub issues.**
12 |
13 | Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/opensource/security/create-report).
14 |
15 | If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/opensource/security/pgpkey).
16 |
17 | You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://aka.ms/opensource/security/msrc).
18 |
19 | Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:
20 |
21 | * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)
22 | * Full paths of source file(s) related to the manifestation of the issue
23 | * The location of the affected source code (tag/branch/commit or direct URL)
24 | * Any special configuration required to reproduce the issue
25 | * Step-by-step instructions to reproduce the issue
26 | * Proof-of-concept or exploit code (if possible)
27 | * Impact of the issue, including how an attacker might exploit the issue
28 |
29 | This information will help us triage your report more quickly.
30 |
31 | If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/opensource/security/bounty) page for more details about our active programs.
32 |
33 | ## Preferred Languages
34 |
35 | We prefer all communications to be in English.
36 |
37 | ## Policy
38 |
39 | Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/opensource/security/cvd).
40 |
41 |
42 |
--------------------------------------------------------------------------------
/SUPPORT.md:
--------------------------------------------------------------------------------
1 | # TODO: The maintainer of this repo has not yet edited this file
2 |
3 | **REPO OWNER**: Do you want Customer Service & Support (CSS) support for this product/project?
4 |
5 | - **No CSS support:** Fill out this template with information about how to file issues and get help.
6 | - **Yes CSS support:** Fill out an intake form at [aka.ms/onboardsupport](https://aka.ms/onboardsupport). CSS will work with/help you to determine next steps.
7 | - **Not sure?** Fill out an intake as though the answer were "Yes". CSS will help you decide.
8 |
9 | *Then remove this first heading from this SUPPORT.MD file before publishing your repo.*
10 |
11 | # Support
12 |
13 | ## How to file issues and get help
14 |
15 | This project uses GitHub Issues to track bugs and feature requests. Please search the existing
16 | issues before filing new issues to avoid duplicates. For new issues, file your bug or
17 | feature request as a new Issue.
18 |
19 | For help and questions about using this project, please **REPO MAINTAINER: INSERT INSTRUCTIONS HERE
20 | FOR HOW TO ENGAGE REPO OWNERS OR COMMUNITY FOR HELP. COULD BE A STACK OVERFLOW TAG OR OTHER
21 | CHANNEL. WHERE WILL YOU HELP PEOPLE?**.
22 |
23 | ## Microsoft Support Policy
24 |
25 | Support for this **PROJECT or PRODUCT** is limited to the resources listed above.
26 |
--------------------------------------------------------------------------------
/sk-csharp-azure-functions/.vscode/extensions.json:
--------------------------------------------------------------------------------
1 | {
2 | "recommendations": [
3 | "ms-azuretools.vscode-azurefunctions",
4 | "ms-dotnettools.csharp",
5 | "ms-semantic-kernel.semantic-kernel"
6 | ]
7 | }
--------------------------------------------------------------------------------
/sk-csharp-azure-functions/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | "name": "Attach to .NET Functions",
6 | "type": "coreclr",
7 | "request": "attach",
8 | "processId": "${command:azureFunctions.pickProcess}"
9 | }
10 | ]
11 | }
--------------------------------------------------------------------------------
/sk-csharp-azure-functions/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "azureFunctions.deploySubpath": "bin/Release/net6.0/publish",
3 | "azureFunctions.projectLanguage": "C#",
4 | "azureFunctions.projectRuntime": "~4",
5 | "debug.internalConsoleOptions": "neverOpen",
6 | "azureFunctions.preDeployTask": "publish (functions)"
7 | }
--------------------------------------------------------------------------------
/sk-csharp-azure-functions/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0.0",
3 | "tasks": [
4 | {
5 | "label": "clean (functions)",
6 | "command": "dotnet",
7 | "args": [
8 | "clean",
9 | "/property:GenerateFullPaths=true",
10 | "/consoleloggerparameters:NoSummary"
11 | ],
12 | "type": "process",
13 | "problemMatcher": "$msCompile"
14 | },
15 | {
16 | "label": "build (functions)",
17 | "command": "dotnet",
18 | "args": [
19 | "build",
20 | "/property:GenerateFullPaths=true",
21 | "/consoleloggerparameters:NoSummary"
22 | ],
23 | "type": "process",
24 | "dependsOn": "clean (functions)",
25 | "group": {
26 | "kind": "build",
27 | "isDefault": true
28 | },
29 | "problemMatcher": "$msCompile"
30 | },
31 | {
32 | "label": "clean release (functions)",
33 | "command": "dotnet",
34 | "args": [
35 | "clean",
36 | "--configuration",
37 | "Release",
38 | "/property:GenerateFullPaths=true",
39 | "/consoleloggerparameters:NoSummary"
40 | ],
41 | "type": "process",
42 | "problemMatcher": "$msCompile"
43 | },
44 | {
45 | "label": "publish (functions)",
46 | "command": "dotnet",
47 | "args": [
48 | "publish",
49 | "--configuration",
50 | "Release",
51 | "/property:GenerateFullPaths=true",
52 | "/consoleloggerparameters:NoSummary"
53 | ],
54 | "type": "process",
55 | "dependsOn": "clean release (functions)",
56 | "problemMatcher": "$msCompile"
57 | },
58 | {
59 | "type": "func",
60 | "dependsOn": "build (functions)",
61 | "options": {
62 | "cwd": "${workspaceFolder}/bin/Debug/net6.0"
63 | },
64 | "command": "host start",
65 | "isBackground": true,
66 | "problemMatcher": "$func-dotnet-watch"
67 | },
68 | {
69 | "label": "build",
70 | "command": "dotnet",
71 | "type": "process",
72 | "args": [
73 | "build",
74 | "${workspaceFolder}/sk-csharp-azure-functions.csproj",
75 | "/property:GenerateFullPaths=true",
76 | "/consoleloggerparameters:NoSummary"
77 | ],
78 | "problemMatcher": "$msCompile"
79 | },
80 | {
81 | "label": "publish",
82 | "command": "dotnet",
83 | "type": "process",
84 | "args": [
85 | "publish",
86 | "${workspaceFolder}/sk-csharp-azure-functions.csproj",
87 | "/property:GenerateFullPaths=true",
88 | "/consoleloggerparameters:NoSummary"
89 | ],
90 | "problemMatcher": "$msCompile"
91 | },
92 | {
93 | "label": "watch",
94 | "command": "dotnet",
95 | "type": "process",
96 | "args": [
97 | "watch",
98 | "run",
99 | "--project",
100 | "${workspaceFolder}/sk-csharp-azure-functions.csproj"
101 | ],
102 | "problemMatcher": "$msCompile"
103 | }
104 | ]
105 | }
--------------------------------------------------------------------------------
/sk-csharp-azure-functions/Directory.Build.props:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | true
5 | true
6 | AllEnabledByDefault
7 | latest
8 | true
9 | 11
10 | enable
11 | disable
12 | CS1591,CA1852,CA1050
13 |
14 |
15 |
16 |
17 | disable
18 |
19 |
20 |
21 | true
22 | full
23 |
24 |
25 |
26 | portable
27 |
28 |
29 |
30 | $([System.IO.Path]::GetDirectoryName($([MSBuild]::GetPathOfFileAbove('.gitignore', '$(MSBuildThisFileDirectory)'))))
31 |
32 |
33 |
--------------------------------------------------------------------------------
/sk-csharp-azure-functions/Directory.Build.targets:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | <_Parameter1 Condition="'%(InternalsVisibleTo.PublicKey)' != ''">%(InternalsVisibleTo.Identity), PublicKey="%(InternalsVisibleTo.PublicKey)
20 | <_Parameter1 Condition="'%(InternalsVisibleTo.PublicKey)' == ''">%(InternalsVisibleTo.Identity)
21 | <_Parameter1_TypeName>System.String
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/sk-csharp-azure-functions/Models/ErrorResponse.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json.Serialization;
2 | using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Attributes;
3 |
4 | namespace Models;
5 |
6 | internal class ErrorResponse
7 | {
8 | [JsonPropertyName("message")]
9 | [OpenApiProperty(Description = "The error message.")]
10 | public string Message { get; set; } = string.Empty;
11 | }
12 |
--------------------------------------------------------------------------------
/sk-csharp-azure-functions/Models/ExecuteFunctionRequest.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json.Serialization;
2 | using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Attributes;
3 |
4 | namespace Models;
5 |
6 | #pragma warning disable CA1812
7 | internal class ExecuteFunctionRequest
8 | {
9 | [JsonPropertyName("variables")]
10 | [OpenApiProperty(Description = "The variables to pass to the semantic function.")]
11 | public IEnumerable Variables { get; set; } = Enumerable.Empty();
12 | }
13 |
14 | internal class ExecuteFunctionVariable
15 | {
16 | [JsonPropertyName("key")]
17 | [OpenApiProperty(Description = "The variable key.", Default = "input")]
18 | public string Key { get; set; } = string.Empty;
19 |
20 | [JsonPropertyName("value")]
21 | [OpenApiProperty(Description = "The variable value.", Default = "Late for school")]
22 | public string Value { get; set; } = string.Empty;
23 | }
24 |
--------------------------------------------------------------------------------
/sk-csharp-azure-functions/Models/ExecuteFunctionResponse.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json.Serialization;
2 | using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Attributes;
3 |
4 | namespace Models;
5 |
6 | internal class ExecuteFunctionResponse
7 | {
8 | [JsonPropertyName("response")]
9 | [OpenApiProperty(Description = "The response from the AI.")]
10 | public string? Response { get; set; }
11 | }
12 |
--------------------------------------------------------------------------------
/sk-csharp-azure-functions/Program.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json;
2 | using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Abstractions;
3 | using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Configurations;
4 | using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Enums;
5 | using Microsoft.Extensions.Configuration;
6 | using Microsoft.Extensions.DependencyInjection;
7 | using Microsoft.Extensions.Hosting;
8 | using Microsoft.Extensions.Logging;
9 | using Microsoft.OpenApi.Models;
10 | using Microsoft.SemanticKernel;
11 |
12 | namespace KernelHttpServer;
13 |
14 | public static class Program
15 | {
16 | public static void Main()
17 | {
18 | var host = new HostBuilder()
19 | .ConfigureFunctionsWorkerDefaults()
20 | .ConfigureAppConfiguration(configuration =>
21 | {
22 | var config = configuration.SetBasePath(Directory.GetCurrentDirectory())
23 | .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true);
24 |
25 | var builtConfig = config.Build();
26 | })
27 | .ConfigureServices(services =>
28 | {
29 | services.AddSingleton(_ => s_apiConfigOptions);
30 | services.AddTransient((provider) => CreateKernel(provider));
31 |
32 |
33 | // return JSON with expected lowercase naming
34 | services.Configure(options =>
35 | {
36 | options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
37 | });
38 | })
39 | .Build();
40 |
41 | host.Run();
42 | }
43 |
44 | private static IKernel CreateKernel(IServiceProvider provider)
45 | {
46 | var kernelSettings = KernelSettings.LoadSettings();
47 |
48 | using ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
49 | {
50 | builder
51 | .SetMinimumLevel(kernelSettings.LogLevel ?? LogLevel.Warning)
52 | .AddConsole()
53 | .AddDebug();
54 | });
55 |
56 | return new KernelBuilder()
57 | .WithLogger(loggerFactory.CreateLogger())
58 | .WithCompletionService(kernelSettings)
59 | .Build();
60 | }
61 |
62 | private static readonly OpenApiConfigurationOptions s_apiConfigOptions = new()
63 | {
64 | Info = new OpenApiInfo()
65 | {
66 | Version = "1.0.0",
67 | Title = "Semantic Kernel Azure Functions Starter",
68 | Description = "Azure Functions starter application for the [Semantic Kernel](https://github.com/microsoft/semantic-kernel).",
69 | Contact = new OpenApiContact()
70 | {
71 | Name = "Issues",
72 | Url = new Uri("https://github.com/microsoft/semantic-kernel-starters/issues"),
73 | },
74 | License = new OpenApiLicense()
75 | {
76 | Name = "MIT",
77 | Url = new Uri("https://github.com/microsoft/semantic-kernel-starters/blob/main/LICENSE"),
78 | }
79 | },
80 | Servers = DefaultOpenApiConfigurationOptions.GetHostNames(),
81 | OpenApiVersion = OpenApiVersionType.V2,
82 | ForceHttps = false,
83 | ForceHttp = false,
84 | };
85 | }
86 |
--------------------------------------------------------------------------------
/sk-csharp-azure-functions/config/EndpointTypes.cs:
--------------------------------------------------------------------------------
1 | internal static class EndpointTypes
2 | {
3 | internal const string TextCompletion = "text-completion";
4 | internal const string ChatCompletion = "chat-completion";
5 | }
6 |
--------------------------------------------------------------------------------
/sk-csharp-azure-functions/config/KernelBuilderExtensions.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 |
3 | internal static class KernelBuilderExtensions
4 | {
5 | ///
6 | /// Adds a text completion service to the list. It can be either an OpenAI or Azure OpenAI backend service.
7 | ///
8 | ///
9 | ///
10 | ///
11 | internal static KernelBuilder WithCompletionService(this KernelBuilder kernelBuilder, KernelSettings kernelSettings)
12 | {
13 | switch (kernelSettings.ServiceType.ToUpperInvariant())
14 | {
15 | case ServiceTypes.AzureOpenAI when kernelSettings.EndpointType == EndpointTypes.TextCompletion:
16 | kernelBuilder.WithAzureTextCompletionService(deploymentName: kernelSettings.DeploymentOrModelId, endpoint: kernelSettings.Endpoint, apiKey: kernelSettings.ApiKey, serviceId: kernelSettings.ServiceId);
17 | break;
18 | case ServiceTypes.AzureOpenAI when kernelSettings.EndpointType == EndpointTypes.ChatCompletion:
19 | kernelBuilder.WithAzureChatCompletionService(deploymentName: kernelSettings.DeploymentOrModelId, endpoint: kernelSettings.Endpoint, apiKey: kernelSettings.ApiKey, serviceId: kernelSettings.ServiceId);
20 | break;
21 | case ServiceTypes.OpenAI when kernelSettings.EndpointType == EndpointTypes.TextCompletion:
22 | kernelBuilder.WithOpenAITextCompletionService(modelId: kernelSettings.DeploymentOrModelId, apiKey: kernelSettings.ApiKey, orgId: kernelSettings.OrgId, serviceId: kernelSettings.ServiceId);
23 | break;
24 | case ServiceTypes.OpenAI when kernelSettings.EndpointType == EndpointTypes.ChatCompletion:
25 | kernelBuilder.WithOpenAIChatCompletionService(modelId: kernelSettings.DeploymentOrModelId, apiKey: kernelSettings.ApiKey, orgId: kernelSettings.OrgId, serviceId: kernelSettings.ServiceId);
26 | break;
27 | default:
28 | throw new ArgumentException($"Invalid service type value: {kernelSettings.ServiceType}");
29 | }
30 |
31 | return kernelBuilder;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/sk-csharp-azure-functions/config/ServiceTypes.cs:
--------------------------------------------------------------------------------
1 | internal static class ServiceTypes
2 | {
3 | internal const string OpenAI = "OPENAI";
4 | internal const string AzureOpenAI = "AZUREOPENAI";
5 | }
6 |
--------------------------------------------------------------------------------
/sk-csharp-azure-functions/config/appsettings.json.azure-example:
--------------------------------------------------------------------------------
1 | {
2 | "serviceType": "AzureOpenAI",
3 | "serviceId": "text-davinci-003",
4 | "deploymentOrModelId": "text-davinci-003",
5 | "endpoint": "https:// ... your endpoint ... .openai.azure.com/",
6 | "apiKey": "... your Azure OpenAI key ..."
7 | }
--------------------------------------------------------------------------------
/sk-csharp-azure-functions/config/appsettings.json.openai-example:
--------------------------------------------------------------------------------
1 | {
2 | "serviceType": "OpenAI",
3 | "serviceId": "text-davinci-003",
4 | "deploymentOrModelId": "text-davinci-003",
5 | "apiKey": "... your OpenAI key ...",
6 | "orgId": ""
7 | }
--------------------------------------------------------------------------------
/sk-csharp-azure-functions/host.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0",
3 | "logging": {
4 | "applicationInsights": {
5 | "samplingSettings": {
6 | "isEnabled": true,
7 | "excludedTypes": "Request"
8 | }
9 | }
10 | }
11 | }
--------------------------------------------------------------------------------
/sk-csharp-azure-functions/local.settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "IsEncrypted": false,
3 | "Host": {
4 | "CORS": "*"
5 | },
6 | "Values": {
7 | "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated"
8 | }
9 | }
--------------------------------------------------------------------------------
/sk-csharp-azure-functions/sk-csharp-azure-functions.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | $([System.IO.Path]::GetDirectoryName($([MSBuild]::GetPathOfFileAbove('.gitignore', '$(MSBuildThisFileDirectory)'))))
5 | b4703849-9b3a-41c3-b1bb-5ede533963c4
6 |
7 |
8 |
9 | net8.0
10 |
11 | v4
12 | Exe
13 | 10
14 | enable
15 | enable
16 | false
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 | PreserveNewest
32 |
33 |
34 | PreserveNewest
35 | Never
36 |
37 |
38 | PreserveNewest
39 |
40 |
41 | PreserveNewest
42 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/sk-csharp-azure-functions/skills/FunSkill/Excuses/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "description": "Turn a scenario into a creative or humorous excuse to send your boss",
4 | "type": "completion",
5 | "completion": {
6 | "max_tokens": 60,
7 | "temperature": 0.5,
8 | "top_p": 0.0,
9 | "presence_penalty": 0.0,
10 | "frequency_penalty": 0.0
11 | }
12 | }
--------------------------------------------------------------------------------
/sk-csharp-azure-functions/skills/FunSkill/Excuses/skprompt.txt:
--------------------------------------------------------------------------------
1 | Generate a creative reason or excuse for the given event. Be creative and be funny. Let your imagination run wild.
2 |
3 | Event:I am running late.
4 | Excuse:I was being held ransom by giraffe gangsters.
5 |
6 | Event:{{$input}}
--------------------------------------------------------------------------------
/sk-csharp-azure-functions/skills/FunSkill/Joke/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "description": "Generate a funny joke",
4 | "type": "completion",
5 | "completion": {
6 | "max_tokens": 1000,
7 | "temperature": 0.9,
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": "Joke subject",
17 | "defaultValue": ""
18 | }
19 | ]
20 | }
21 | }
--------------------------------------------------------------------------------
/sk-csharp-azure-functions/skills/FunSkill/Joke/skprompt.txt:
--------------------------------------------------------------------------------
1 | WRITE EXACTLY ONE JOKE or HUMOROUS STORY ABOUT THE TOPIC BELOW
2 |
3 | JOKE MUST BE:
4 | - G RATED
5 | - WORKPLACE/FAMILY SAFE
6 | NO SEXISM, RACISM OR OTHER BIAS/BIGOTRY
7 |
8 | BE CREATIVE AND FUNNY. I WANT TO LAUGH.
9 | {{$style}}
10 | +++++
11 |
12 | {{$input}}
13 | +++++
14 |
--------------------------------------------------------------------------------
/sk-csharp-azure-functions/skills/FunSkill/Limerick/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "description": "Generate a funny limerick about a person",
4 | "type": "completion",
5 | "completion": {
6 | "max_tokens": 100,
7 | "temperature": 0.7,
8 | "top_p": 0.0,
9 | "presence_penalty": 0.0,
10 | "frequency_penalty": 0.0
11 | }
12 | }
--------------------------------------------------------------------------------
/sk-csharp-azure-functions/skills/FunSkill/Limerick/skprompt.txt:
--------------------------------------------------------------------------------
1 | There was a young woman named Bright,
2 | Whose speed was much faster than light.
3 | She set out one day,
4 | In a relative way,
5 | And returned on the previous night.
6 |
7 | There was an odd fellow named Gus,
8 | When traveling he made such a fuss.
9 | He was banned from the train,
10 | Not allowed on a plane,
11 | And now travels only by bus.
12 |
13 | There once was a man from Tibet,
14 | Who couldn't find a cigarette
15 | So he smoked all his socks,
16 | and got chicken-pox,
17 | and had to go to the vet.
18 |
19 | There once was a boy named Dan,
20 | who wanted to fry in a pan.
21 | He tried and he tried,
22 | and eventually died,
23 | that weird little boy named Dan.
24 |
25 | Now write a very funny limerick about {{$name}}.
26 | {{$input}}
27 | Invent new facts their life. Must be funny.
28 |
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/.gitignore:
--------------------------------------------------------------------------------
1 | **/bin
2 | **/obj
3 | !azure-function/appsettings.json
4 | azure-function/local.settings.json
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/.vscode/extensions.json:
--------------------------------------------------------------------------------
1 | {
2 | "recommendations": [
3 | "ms-azuretools.vscode-azurefunctions",
4 | "ms-dotnettools.csharp",
5 | "ms-semantic-kernel.semantic-kernel"
6 | ]
7 | }
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | "name": "Attach to .NET Functions",
6 | "type": "coreclr",
7 | "request": "attach",
8 | "processId": "${command:azureFunctions.pickProcess}"
9 | }
10 | ]
11 | }
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "azureFunctions.deploySubpath": "azure-function/bin/Release/net6.0/publish",
3 | "azureFunctions.projectLanguage": "C#",
4 | "azureFunctions.projectRuntime": "~4",
5 | "debug.internalConsoleOptions": "neverOpen",
6 | "azureFunctions.preDeployTask": "publish (functions)"
7 | }
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/README.md:
--------------------------------------------------------------------------------
1 | # Semantic Kernel ChatGPT plugin starter
2 |
3 | This project provides starter code to create a ChatGPT plugin. It includes the following components:
4 |
5 | - An endpoint that serves up an ai-plugin.json file for ChatGPT to discover the plugin
6 | - A generator that automatically converts prompts into semantic function endpoints
7 | - The ability to add additional native functions as endpoints to the plugin
8 |
9 | To learn more about using this starter, see the Semantic Kernel documentation that describes how to [create a ChatGPT plugin](https://learn.microsoft.com/en-us/semantic-kernel/ai-orchestration/chatgpt-plugins).
10 |
11 | ## Prerequisites
12 |
13 | - [.NET 6](https://dotnet.microsoft.com/download/dotnet/6.0) is required to run this starter.
14 | - [Azure Functions Core Tools](https://www.npmjs.com/package/azure-functions-core-tools) is required to run this starter.
15 | - Install the recommended extensions
16 | - [C#](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp)
17 | - [Semantic Kernel Tools](https://marketplace.visualstudio.com/items?itemName=ms-semantic-kernel.semantic-kernel)
18 |
19 | ## Configuring the starter
20 |
21 | To configure the starter, you need to provide the following information:
22 |
23 | - Define the properties of the plugin in the [appsettings.json](./azure-function/appsettings.json) file.
24 | - Enter the API key for your AI endpoint in the [local.settings.json](./azure-function/local.settings.json) file.
25 |
26 | For Debugging the console application alone, we suggest using .NET [Secret Manager](https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets) to avoid the risk of leaking secrets into the repository, branches and pull requests.
27 |
28 | ### Using appsettings.json
29 |
30 | Configure an OpenAI endpoint
31 |
32 | 1. Copy [settings.json.openai-example](./config/appsettings.json.openai-example) to `./appsettings.json`
33 | 1. Edit the `kernel` object to add your OpenAI endpoint configuration
34 | 1. Edit the `aiPlugin` object to define the properties that get exposed in the ai-plugin.json file
35 |
36 | Configure an Azure OpenAI endpoint
37 |
38 | 1. Copy [settings.json.azure-example](./config/appsettings.json.azure-example) to `./appsettings.json`
39 | 1. Edit the `kernel` object to add your Azure OpenAI endpoint configuration
40 | 1. Edit the `aiPlugin` object to define the properties that get exposed in the ai-plugin.json file
41 |
42 | ### Using local.settings.json
43 |
44 | 1. Copy [local.settings.json.example](./azure-function/local.settings.json.example) to `./azure-function/local.settings.json`
45 | 1. Edit the `Values` object to add your OpenAI endpoint configuration in the `apiKey` property
46 |
47 | ## Running the starter
48 |
49 | To run the Azure Functions application just hit `F5`.
50 |
51 | To build and run the Azure Functions application from a terminal use the following commands:
52 |
53 | ```powershell
54 | cd azure-function
55 | dotnet build
56 | cd bin/Debug/net6.0
57 | func host start
58 | ```
59 |
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/azure-function/AiPluginJson.cs:
--------------------------------------------------------------------------------
1 | using System.Net;
2 | using Microsoft.AspNetCore.Mvc;
3 | using Microsoft.Azure.Functions.Worker;
4 | using Microsoft.Azure.Functions.Worker.Http;
5 | using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Attributes;
6 | using Microsoft.Extensions.Logging;
7 | using Microsoft.OpenApi.Models;
8 | using Models;
9 |
10 | public class AIPluginJson
11 | {
12 | [Function("GetAIPluginJson")]
13 | public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = ".well-known/ai-plugin.json")] HttpRequestData req)
14 | {
15 | var currentDomain = $"{req.Url.Scheme}://{req.Url.Host}:{req.Url.Port}";
16 |
17 | HttpResponseData response = req.CreateResponse(HttpStatusCode.OK);
18 | response.Headers.Add("Content-Type", "application/json");
19 |
20 | var appSettings = AppSettings.LoadSettings();
21 |
22 | // serialize app settings to json using System.Text.Json
23 | var json = System.Text.Json.JsonSerializer.Serialize(appSettings.AIPlugin);
24 |
25 | // replace {url} with the current domain
26 | json = json.Replace("{url}", currentDomain, StringComparison.OrdinalIgnoreCase);
27 |
28 | response.WriteString(json);
29 |
30 | return response;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/azure-function/Directory.Build.props:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | true
5 | true
6 | AllEnabledByDefault
7 | latest
8 | true
9 | 11
10 | enable
11 | disable
12 | CS1591,CA1852,CA1050
13 |
14 |
15 |
16 |
17 | disable
18 |
19 |
20 |
21 | true
22 | full
23 |
24 |
25 |
26 | portable
27 |
28 |
29 |
30 | $([System.IO.Path]::GetDirectoryName($([MSBuild]::GetPathOfFileAbove('.gitignore', '$(MSBuildThisFileDirectory)'))))
31 |
32 |
33 |
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/azure-function/Directory.Build.targets:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | <_Parameter1 Condition="'%(InternalsVisibleTo.PublicKey)' != ''">%(InternalsVisibleTo.Identity), PublicKey="%(InternalsVisibleTo.PublicKey)
20 | <_Parameter1 Condition="'%(InternalsVisibleTo.PublicKey)' == ''">%(InternalsVisibleTo.Identity)
21 | <_Parameter1_TypeName>System.String
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/azure-function/Extensions/IAIPluginRunner.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 |
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 | using Microsoft.Azure.Functions.Worker.Http;
8 | using Microsoft.Extensions.Logging;
9 |
10 | namespace AIPlugins.AzureFunctions.Extensions;
11 | public interface IAIPluginRunner
12 | {
13 | public Task RunAIPluginOperationAsync(HttpRequestData req, string operationId);
14 | }
15 |
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/azure-function/Extensions/KernelBuilderExtensions.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 | using Models;
3 |
4 | internal static class KernelBuilderExtensions
5 | {
6 | ///
7 | /// Adds a chat completion service to the list. It can be either an OpenAI or Azure OpenAI backend service.
8 | ///
9 | ///
10 | ///
11 | ///
12 | internal static KernelBuilder WithChatCompletionService(this KernelBuilder kernelBuilder, KernelSettings kernelSettings)
13 | {
14 | switch (kernelSettings.ServiceType.ToUpperInvariant())
15 | {
16 | case ServiceTypes.AzureOpenAI:
17 | kernelBuilder.WithAzureChatCompletionService(deploymentName: kernelSettings.DeploymentOrModelId, endpoint: kernelSettings.Endpoint, apiKey: kernelSettings.ApiKey, serviceId: kernelSettings.ServiceId);
18 | break;
19 |
20 | case ServiceTypes.OpenAI:
21 | kernelBuilder.WithOpenAIChatCompletionService(modelId: kernelSettings.DeploymentOrModelId, apiKey: kernelSettings.ApiKey, orgId: kernelSettings.OrgId, serviceId: kernelSettings.ServiceId);
22 | break;
23 |
24 | default:
25 | throw new ArgumentException($"Invalid service type value: {kernelSettings.ServiceType}");
26 | }
27 |
28 | return kernelBuilder;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/azure-function/Extensions/KernelExtensions.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 |
3 | using System.Collections.Generic;
4 | using System.IO;
5 | using Microsoft.Extensions.Logging;
6 | using Microsoft.SemanticKernel;
7 | using Microsoft.SemanticKernel.Diagnostics;
8 | using Microsoft.SemanticKernel.SemanticFunctions;
9 | using Microsoft.SemanticKernel.SkillDefinition;
10 | using Microsoft.SemanticKernel.Text;
11 |
12 | namespace AIPlugins.AzureFunctions.Extensions;
13 |
14 | public static class KernelExtensions
15 | {
16 | public static IDictionary ImportPromptsFromDirectory(
17 | this IKernel kernel, string pluginName, string promptDirectory)
18 | {
19 | const string CONFIG_FILE = "config.json";
20 | const string PROMPT_FILE = "skprompt.txt";
21 |
22 | var plugin = new Dictionary();
23 |
24 | string[] directories = Directory.GetDirectories(promptDirectory);
25 | foreach (string dir in directories)
26 | {
27 | var functionName = Path.GetFileName(dir);
28 |
29 | // Continue only if prompt template exists
30 | var promptPath = Path.Combine(dir, PROMPT_FILE);
31 | if (!File.Exists(promptPath)) { continue; }
32 |
33 | // Load prompt configuration. Note: the configuration is optional.
34 | var config = new PromptTemplateConfig();
35 | var configPath = Path.Combine(dir, CONFIG_FILE);
36 | if (File.Exists(configPath))
37 | {
38 | config = PromptTemplateConfig.FromJson(File.ReadAllText(configPath));
39 | }
40 |
41 | // Load prompt template
42 | var template = new PromptTemplate(File.ReadAllText(promptPath), config, kernel.PromptTemplateEngine);
43 |
44 | // Prepare lambda wrapping AI logic
45 | var functionConfig = new SemanticFunctionConfig(config, template);
46 |
47 | kernel.Logger.LogTrace("Registering function {0}.{1} loaded from {2}", pluginName, functionName, dir);
48 | plugin[functionName] = kernel.RegisterSemanticFunction(pluginName, functionName, functionConfig);
49 | }
50 |
51 | return plugin;
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/azure-function/Logo.cs:
--------------------------------------------------------------------------------
1 | using System.Net;
2 | using Microsoft.Azure.Functions.Worker;
3 | using Microsoft.Azure.Functions.Worker.Http;
4 |
5 | public class Logo
6 | {
7 | [Function("GetLogo")]
8 | public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "logo.png")] HttpRequestData req)
9 | {
10 | // Return logo.png that's in the root of the project
11 | var response = req.CreateResponse(HttpStatusCode.OK);
12 | response.Headers.Add("Content-Type", "image/png");
13 |
14 | var logo = System.IO.File.ReadAllBytes("logo.png");
15 | response.Body.Write(logo);
16 |
17 | return response;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/azure-function/Models/AiPluginSettings.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | using System.Text.Json.Serialization;
3 |
4 | namespace Models;
5 |
6 | #pragma warning disable CA1056
7 | #pragma warning disable CA1034
8 |
9 | public class AIPluginSettings
10 | {
11 | [JsonPropertyName("schema_version")]
12 | public string SchemaVersion { get; set; } = "v1";
13 |
14 | [JsonPropertyName("name_for_model")]
15 | public string NameForModel { get; set; } = string.Empty;
16 |
17 | [JsonPropertyName("name_for_human")]
18 | public string NameForHuman { get; set; } = string.Empty;
19 |
20 | [JsonPropertyName("description_for_model")]
21 | public string DescriptionForModel { get; set; } = string.Empty;
22 |
23 | [JsonPropertyName("description_for_human")]
24 | public string DescriptionForHuman { get; set; } = string.Empty;
25 |
26 | [JsonPropertyName("auth")]
27 | public AuthModel Auth { get; set; } = new AuthModel();
28 |
29 | [JsonPropertyName("api")]
30 | public ApiModel Api { get; set; } = new ApiModel();
31 |
32 | [JsonPropertyName("logo_url")]
33 | public string LogoUrl { get; set; } = string.Empty;
34 |
35 | [JsonPropertyName("contact_email")]
36 | public string ContactEmail { get; set; } = string.Empty;
37 |
38 | [JsonPropertyName("legal_info_url")]
39 | public string LegalInfoUrl { get; set; } = string.Empty;
40 |
41 |
42 | public class AuthModel
43 | {
44 | [JsonPropertyName("type")]
45 | public string Type { get; set; } = string.Empty;
46 |
47 | [JsonPropertyName("authorization_url")]
48 | public string AuthorizationType { get; set; } = string.Empty;
49 | }
50 |
51 | public class ApiModel
52 | {
53 | [JsonPropertyName("type")]
54 | public string Type { get; set; } = "openapi";
55 |
56 | [JsonPropertyName("url")]
57 | public string Url { get; set; } = string.Empty;
58 |
59 | [JsonPropertyName("has_user_authentication")]
60 | public bool HasUserAuthentication { get; set; } = false;
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/azure-function/Models/AppSettings.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 |
3 | using System.Reflection;
4 | using System.Text.Json.Serialization;
5 | using Microsoft.Extensions.Configuration;
6 |
7 | namespace Models;
8 |
9 | #pragma warning disable CA1724
10 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
11 | public class AppSettings
12 | {
13 | public const string DefaultConfigFile = "appsettings.json";
14 |
15 | public KernelSettings Kernel { get; set; }
16 | public AIPluginSettings AIPlugin { get; set; }
17 |
18 | ///
19 | /// Load the kernel settings from settings.json if the file exists and if not attempt to use user secrets.
20 | ///
21 | public static AppSettings LoadSettings()
22 | {
23 | try
24 | {
25 | var appSettings = FromFile(DefaultConfigFile);
26 | appSettings.Kernel.ApiKey = GetApiKey();
27 |
28 | return appSettings;
29 | }
30 | catch (InvalidDataException ide)
31 | {
32 | Console.Error.WriteLine(
33 | "Unable to load app settings, please provide configuration settings using instructions in the README.\n" +
34 | "Please refer to: https://github.com/microsoft/semantic-kernel-starters/blob/main/sk-csharp-chatgpt-plugin/README.md#configuring-the-starter"
35 | );
36 | throw new InvalidOperationException(ide.Message);
37 | }
38 | }
39 |
40 | ///
41 | /// Load the kernel settings from the specified configuration file if it exists.
42 | ///
43 | private static AppSettings FromFile(string configFile = DefaultConfigFile)
44 | {
45 | if (!File.Exists(configFile))
46 | {
47 | throw new FileNotFoundException($"Configuration not found: {configFile}");
48 | }
49 |
50 | var configuration = new ConfigurationBuilder()
51 | .SetBasePath(System.IO.Directory.GetCurrentDirectory())
52 | .AddJsonFile(configFile, optional: true, reloadOnChange: true)
53 | .Build();
54 |
55 | return configuration.Get()
56 | ?? throw new InvalidDataException($"Invalid app settings in '{configFile}', please provide configuration settings using instructions in the README.");
57 | }
58 |
59 | ///
60 | /// Load the API key for the AI endpoint from user secrets.
61 | ///
62 | internal static string GetApiKey()
63 | {
64 | return System.Environment.GetEnvironmentVariable("apiKey", EnvironmentVariableTarget.Process)
65 | ?? throw new InvalidDataException("Invalid semantic kernel settings in user secrets, please provide configuration settings using instructions in the README.");
66 | }
67 | }
68 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
69 |
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/azure-function/Models/KernelSettings.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json.Serialization;
2 | using Microsoft.Extensions.Logging;
3 |
4 | namespace Models;
5 |
6 | #pragma warning disable CA1812
7 | public class KernelSettings
8 | {
9 | public string ServiceType { get; set; } = string.Empty;
10 | public string ServiceId { get; set; } = string.Empty;
11 | public string DeploymentOrModelId { get; set; } = string.Empty;
12 | public string Endpoint { get; set; } = string.Empty;
13 | public string OrgId { get; set; } = string.Empty;
14 | public LogLevel? LogLevel { get; set; }
15 | public string ApiKey { get; set; } = string.Empty;
16 | }
17 |
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/azure-function/Models/ServiceTypes.cs:
--------------------------------------------------------------------------------
1 | namespace Models;
2 |
3 | internal static class ServiceTypes
4 | {
5 | internal const string OpenAI = "OPENAI";
6 | internal const string AzureOpenAI = "AZUREOPENAI";
7 | }
8 |
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/azure-function/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 |
3 | using AIPlugins.AzureFunctions.Extensions;
4 | using Microsoft.Extensions.DependencyInjection;
5 | using Microsoft.Extensions.Hosting;
6 | using Microsoft.Extensions.Logging;
7 | using Microsoft.SemanticKernel;
8 | using Models;
9 |
10 | const string DefaultSemanticFunctionsFolder = "Prompts";
11 | string semanticFunctionsFolder = Environment.GetEnvironmentVariable("SEMANTIC_SKILLS_FOLDER") ?? DefaultSemanticFunctionsFolder;
12 |
13 | var host = new HostBuilder()
14 | .ConfigureFunctionsWorkerDefaults()
15 | .ConfigureServices(services =>
16 | {
17 | services
18 | .AddScoped((providers) =>
19 | {
20 | // This will be called each time a new Kernel is needed
21 |
22 | // Get a logger instance
23 | ILogger logger = providers
24 | .GetRequiredService()
25 | .CreateLogger();
26 |
27 | // Register your AI Providers...
28 | var appSettings = AppSettings.LoadSettings();
29 | IKernel kernel = new KernelBuilder()
30 | .WithChatCompletionService(appSettings.Kernel)
31 | .WithLogger(logger)
32 | .Build();
33 |
34 | // Load your semantic functions...
35 | kernel.ImportPromptsFromDirectory(appSettings.AIPlugin.NameForModel, semanticFunctionsFolder);
36 |
37 | return kernel;
38 | })
39 | .AddScoped();
40 | })
41 | .Build();
42 |
43 | host.Run();
44 |
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/azure-function/Prompts/Joke/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "description": "Generate a funny joke",
4 | "type": "completion",
5 | "completion": {
6 | "max_tokens": 1000,
7 | "temperature": 0.9,
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": "Joke subject",
17 | "defaultValue": ""
18 | }
19 | ]
20 | }
21 | }
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/azure-function/Prompts/Joke/skprompt.txt:
--------------------------------------------------------------------------------
1 | WRITE EXACTLY ONE JOKE or HUMOROUS STORY ABOUT THE TOPIC BELOW
2 |
3 | JOKE MUST BE:
4 | - G RATED
5 | - WORKPLACE/FAMILY SAFE
6 | NO SEXISM, RACISM OR OTHER BIAS/BIGOTRY
7 |
8 | BE CREATIVE AND FUNNY. I WANT TO LAUGH.
9 | +++++
10 |
11 | {{$input}}
12 | +++++
13 |
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/azure-function/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "kernel": {
3 | "serviceType": "OpenAI",
4 | "serviceId": "gpt-3.5-turbo",
5 | "deploymentOrModelId": "gpt-3.5-turbo",
6 | "endpoint": "https:// ... your endpoint ... .openai.azure.com/",
7 | "orgId": ""
8 | },
9 | "aiPlugin": {
10 | "schemaVersion": "v1",
11 | "nameForModel": "MyPlugin",
12 | "nameForHuman": "My Plugin",
13 | "descriptionForModel": "",
14 | "descriptionForHuman": "",
15 | "auth": {
16 | "type": "none"
17 | },
18 | "api": {
19 | "type": "openapi",
20 | "url": "{url}/swagger.json"
21 | },
22 | "logoUrl": "{url}/logo.png",
23 | "contactEmail": "support@example.com",
24 | "legalInfoUrl": "http://www.example.com/legal"
25 | }
26 | }
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/azure-function/config-samples/appsettings.json.azure-example:
--------------------------------------------------------------------------------
1 | {
2 | "kernel": {
3 | "serviceType": "AzureOpenAI",
4 | "serviceId": "gpt-35-turbo",
5 | "deploymentOrModelId": "gpt-35-turbo",
6 | "endpoint": "https:// ... your endpoint ... .openai.azure.com/"
7 | },
8 | "aiPlugin": {
9 | "schemaVersion": "v1",
10 | "nameForModel": "MyPlugin",
11 | "nameForHuman": "My Plugin",
12 | "descriptionForModel": "",
13 | "descriptionForHuman": "",
14 | "auth": {
15 | "type": "none"
16 | },
17 | "api": {
18 | "type": "openapi",
19 | "url": "{url}/swagger.json"
20 | },
21 | "logoUrl": "{url}/logo.png",
22 | "contactEmail": "support@example.com",
23 | "legalInfoUrl": "http://www.example.com/legal"
24 | }
25 | }
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/azure-function/config-samples/appsettings.json.openai-example:
--------------------------------------------------------------------------------
1 | {
2 | "kernel": {
3 | "serviceType": "OpenAI",
4 | "serviceId": "gpt-3.5-turbo",
5 | "deploymentOrModelId": "gpt-3.5-turbo",
6 | "orgId": ""
7 | },
8 | "aiPlugin": {
9 | "schemaVersion": "v1",
10 | "nameForModel": "MyPlugin",
11 | "nameForHuman": "My Plugin",
12 | "descriptionForModel": "",
13 | "descriptionForHuman": "",
14 | "auth": {
15 | "type": "none"
16 | },
17 | "api": {
18 | "type": "openapi",
19 | "url": "{url}/swagger.json"
20 | },
21 | "logoUrl": "{url}/logo.png",
22 | "contactEmail": "support@example.com",
23 | "legalInfoUrl": "http://www.example.com/legal"
24 | }
25 | }
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/azure-function/host.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0",
3 | "logging": {
4 | "applicationInsights": {
5 | "samplingSettings": {
6 | "isEnabled": true,
7 | "excludedTypes": "Request"
8 | }
9 | }
10 | },
11 | "extensions": {
12 | "http": {
13 | "routePrefix": ""
14 | }
15 | }
16 | }
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/azure-function/local.settings.json.example:
--------------------------------------------------------------------------------
1 | {
2 | "IsEncrypted": false,
3 | "Host": {
4 | "CORS": "*"
5 | },
6 | "Values": {
7 | "apiKey": "",
8 | "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated"
9 | }
10 | }
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/azure-function/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/semantic-kernel-starters/2df40f4c0ca9bd5a4baeefd68e17baaf7bf8e366/sk-csharp-chatgpt-plugin/azure-function/logo.png
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/azure-function/sk-chatgpt-azure-function.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | $([System.IO.Path]::GetDirectoryName($([MSBuild]::GetPathOfFileAbove('.gitignore', '$(MSBuildThisFileDirectory)'))))
5 | d733072a-9c0f-473c-a99b-6e12f7b5ef28
6 |
7 |
8 |
9 | net8.0
10 |
11 | v4
12 | <_FunctionsSkipCleanOutput>true
13 | Exe
14 | 10
15 | enable
16 | enable
17 | false
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 | .generated\%(RecursiveDir)%(Filename)%(Extension)
38 |
39 |
40 |
41 |
42 |
43 | PreserveNewest
44 |
45 |
46 | PreserveNewest
47 | Never
48 |
49 |
50 | PreserveNewest
51 |
52 |
53 | PreserveNewest
54 |
55 |
56 |
57 |
58 |
59 | PreserveNewest
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/semantic-functions-generator/Extensions/GeneratorExecutionContextExtensions.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 |
3 | using Microsoft.CodeAnalysis;
4 |
5 | namespace AIPlugins.AzureFunctions.Generator.Extensions;
6 |
7 | internal static class GeneratorExecutionContextExtensions
8 | {
9 | public static string? GetMSBuildProperty(
10 | this GeneratorExecutionContext context,
11 | string name,
12 | string defaultValue = "")
13 | {
14 | context.AnalyzerConfigOptions.GlobalOptions.TryGetValue($"build_property.{name}", out var value);
15 | return value ?? defaultValue;
16 | }
17 |
18 | public static string? GetRootNamespace(this GeneratorExecutionContext context)
19 | {
20 | return context.GetMSBuildProperty("RootNamespace");
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/semantic-functions-generator/Models/PromptConfig.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 |
3 | using System.Collections.Generic;
4 | using Newtonsoft.Json;
5 |
6 | #pragma warning disable CS8618
7 |
8 | namespace AIPlugins.AzureFunctions.Generator.Models;
9 |
10 | internal class PromptConfig
11 | {
12 | [JsonProperty("schema")]
13 | public int Schema { get; set; }
14 |
15 | [JsonProperty("type")]
16 | public string Type { get; set; }
17 |
18 | [JsonProperty("description")]
19 | public string Description { get; set; }
20 |
21 | [JsonProperty("completion")]
22 | public CompletionConfig Completion { get; set; }
23 |
24 | [JsonProperty("input")]
25 | public InputConfig? Input { get; set; }
26 |
27 | public class CompletionConfig
28 | {
29 | [JsonProperty("max_tokens")]
30 | public int MaxTokens { get; set; }
31 |
32 | [JsonProperty("temperature")]
33 | public double Temperature { get; set; }
34 |
35 | [JsonProperty("top_p")]
36 | public double TopP { get; set; }
37 |
38 | [JsonProperty("presence_penalty")]
39 | public double PresencePenalty { get; set; }
40 |
41 | [JsonProperty("frequency_penalty")]
42 | public double FrequencyPenalty { get; set; }
43 | }
44 |
45 | public class InputConfig
46 | {
47 | [JsonProperty("parameters")]
48 | public List Parameters { get; set; }
49 | }
50 |
51 | public class ParameterConfig
52 | {
53 | [JsonProperty("name")]
54 | public string Name { get; set; }
55 |
56 | [JsonProperty("description")]
57 | public string Description { get; set; }
58 |
59 | [JsonProperty("defaultValue")]
60 | public string DefaultValue { get; set; }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/sk-csharp-chatgpt-plugin/semantic-functions-generator/semantic-functions-generator.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | 10
6 | enable
7 | true
8 | RS1035
9 | AIPlugins.AzureFunctions.Generator
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | $(GetTargetPathDependsOn);GetDependencyTargetPaths
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/sk-csharp-console-chat/.gitignore:
--------------------------------------------------------------------------------
1 | appsettings.json
2 | bin
3 | obj
4 | *.ini
5 | *.cache
6 | *.log
7 | *.tmp
8 |
--------------------------------------------------------------------------------
/sk-csharp-console-chat/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | // Use IntelliSense to learn about possible attributes.
3 | // Hover to view descriptions of existing attributes.
4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5 | "version": "0.2.0",
6 | "configurations": [
7 | {
8 | "name": ".NET Core Launch (console)",
9 | "type": "coreclr",
10 | "request": "launch",
11 | "preLaunchTask": "build",
12 | "program": "${workspaceFolder}/bin/Debug/net8.0/sk-csharp-console-chat.dll",
13 | "args": [],
14 | "cwd": "${workspaceFolder}",
15 | "console": "integratedTerminal",
16 | "stopAtEntry": false
17 | },
18 | {
19 | "name": ".NET Core Attach",
20 | "type": "coreclr",
21 | "request": "attach"
22 | }
23 | ]
24 | }
--------------------------------------------------------------------------------
/sk-csharp-console-chat/.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}/sk-csharp-console-chat.csproj",
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}/sk-csharp-console-chat.csproj",
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}/sk-csharp-console-chat.csproj"
37 | ],
38 | "problemMatcher": "$msCompile"
39 | }
40 | ]
41 | }
--------------------------------------------------------------------------------
/sk-csharp-console-chat/Program.cs:
--------------------------------------------------------------------------------
1 | using System.Net;
2 | using Microsoft.Extensions.DependencyInjection;
3 | using Microsoft.Extensions.Hosting;
4 | using Microsoft.Extensions.Http.Resilience;
5 | using Microsoft.Extensions.Logging;
6 | using Microsoft.SemanticKernel;
7 | using Plugins;
8 |
9 | // Load the kernel settings
10 | var kernelSettings = KernelSettings.LoadSettings();
11 |
12 | // Create the host builder with logging configured from the kernel settings.
13 | var builder = Host.CreateDefaultBuilder(args)
14 | .ConfigureLogging(logging =>
15 | {
16 | logging.ClearProviders();
17 | logging.AddConsole();
18 | logging.SetMinimumLevel(kernelSettings.LogLevel ?? LogLevel.Warning);
19 | });
20 |
21 | // Configure the services for the host
22 | builder.ConfigureServices((context, services) =>
23 | {
24 |
25 | // Add kernel settings to the host builder
26 | services
27 | .AddSingleton(kernelSettings)
28 | .AddTransient(serviceProvider => {
29 | KernelBuilder builder = new();
30 | builder.Services.AddLogging(c => c.AddDebug().SetMinimumLevel(LogLevel.Information));
31 | builder.Services.AddChatCompletionService(kernelSettings);
32 | builder.Plugins.AddFromType();
33 |
34 | return builder.Build();
35 | })
36 | .AddHostedService();
37 | });
38 |
39 | // Build and run the host. This keeps the app running using the HostedService.
40 | var host = builder.Build();
41 | await host.RunAsync();
42 |
--------------------------------------------------------------------------------
/sk-csharp-console-chat/README.md:
--------------------------------------------------------------------------------
1 | # Semantic Kernel C# Console Chat Starter
2 |
3 | The `sk-csharp-console-chat` console application demonstrates how to use the Semantic Kernel OpenAI chat completion service.
4 |
5 | ## Prerequisites
6 |
7 | - [.NET 6](https://dotnet.microsoft.com/download/dotnet/6.0) is required to run this starter.
8 | - Install the recommended extensions
9 | - [C#](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp)
10 | - [Semantic Kernel Tools](https://marketplace.visualstudio.com/items?itemName=ms-semantic-kernel.semantic-kernel)
11 |
12 | ## Configuring the starter
13 |
14 | The starter can be configured by using either:
15 |
16 | - Enter secrets at the command line with [.NET Secret Manager](#using-net-secret-manager)
17 | - Enter secrets in [appsettings.json](#using-appsettingsjson)
18 |
19 | For Debugging the console application alone, we suggest using .NET [Secret Manager](https://learn.microsoft.com/aspnet/core/security/app-secrets) to avoid the risk of leaking secrets into the repository, branches and pull requests.
20 |
21 | ### Using .NET [Secret Manager](https://learn.microsoft.com/aspnet/core/security/app-secrets)
22 |
23 | Configure an OpenAI endpoint
24 |
25 | ```bash
26 | cd sk-csharp-console-chat
27 | dotnet user-secrets set "serviceType" "OpenAI"
28 | dotnet user-secrets set "serviceId" "gpt-3.5-turbo"
29 | dotnet user-secrets set "modelId" "gpt-3.5-turbo"
30 | dotnet user-secrets set "apiKey" "... your OpenAI key ..."
31 | ```
32 |
33 | Configure an Azure OpenAI endpoint
34 |
35 | ```bash
36 | cd sk-csharp-console-chat
37 | dotnet user-secrets set "serviceType" "AzureOpenAI"
38 | dotnet user-secrets set "serviceId" "gpt-35-turbo"
39 | dotnet user-secrets set "deploymentId" "gpt-35-turbo"
40 | dotnet user-secrets set "modelId" "gpt-3.5-turbo"
41 | dotnet user-secrets set "endpoint" "https:// ... your endpoint ... .openai.azure.com/"
42 | dotnet user-secrets set "apiKey" "... your Azure OpenAI key ..."
43 | ```
44 |
45 | Configure the Semantic Kernel logging level
46 |
47 | ```bash
48 | dotnet user-secrets set "LogLevel" 0
49 | ```
50 |
51 | Log levels:
52 |
53 | - 0 = Trace
54 | - 1 = Debug
55 | - 2 = Information
56 | - 3 = Warning
57 | - 4 = Error
58 | - 5 = Critical
59 | - 6 = None
60 |
61 | ### Using appsettings.json
62 |
63 | Configure an OpenAI endpoint
64 |
65 | 1. Copy [settings.json.openai-example](./config/appsettings.json.openai-example) to `./config/appsettings.json`
66 | 1. Edit the file to add your OpenAI endpoint configuration
67 |
68 | Configure an Azure OpenAI endpoint
69 |
70 | 1. Copy [settings.json.azure-example](./config/appsettings.json.azure-example) to `./config/appsettings.json`
71 | 1. Edit the file to add your Azure OpenAI endpoint configuration
72 |
73 | ## Running the starter
74 |
75 | To run the console application just hit `F5`.
76 |
77 | To build and run the console application from the terminal use the following commands:
78 |
79 | ```bash
80 | dotnet build
81 | dotnet run
82 | ```
83 |
--------------------------------------------------------------------------------
/sk-csharp-console-chat/config/ServiceCollectionExtensions.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Extensions.DependencyInjection;
2 | using Microsoft.SemanticKernel;
3 |
4 | internal static class ServiceCollectionExtensions
5 | {
6 | ///
7 | /// Adds a chat completion service to the list. It can be either an OpenAI or Azure OpenAI backend service.
8 | ///
9 | ///
10 | ///
11 | ///
12 | internal static IServiceCollection AddChatCompletionService(this IServiceCollection serviceCollection, KernelSettings kernelSettings)
13 | {
14 | switch (kernelSettings.ServiceType.ToUpperInvariant())
15 | {
16 | case ServiceTypes.AzureOpenAI:
17 | serviceCollection = serviceCollection.AddAzureOpenAIChatCompletion(kernelSettings.DeploymentId, kernelSettings.ModelId, endpoint: kernelSettings.Endpoint, apiKey: kernelSettings.ApiKey, serviceId: kernelSettings.ServiceId);
18 | break;
19 |
20 | case ServiceTypes.OpenAI:
21 | serviceCollection = serviceCollection.AddOpenAIChatCompletion(modelId: kernelSettings.ModelId, apiKey: kernelSettings.ApiKey, orgId: kernelSettings.OrgId, serviceId: kernelSettings.ServiceId);
22 | break;
23 |
24 | default:
25 | throw new ArgumentException($"Invalid service type value: {kernelSettings.ServiceType}");
26 | }
27 |
28 | return serviceCollection;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/sk-csharp-console-chat/config/ServiceTypes.cs:
--------------------------------------------------------------------------------
1 | internal static class ServiceTypes
2 | {
3 | internal const string OpenAI = "OPENAI";
4 | internal const string AzureOpenAI = "AZUREOPENAI";
5 | }
6 |
--------------------------------------------------------------------------------
/sk-csharp-console-chat/config/appsettings.json.azure-example:
--------------------------------------------------------------------------------
1 | {
2 | "serviceType": "AzureOpenAI",
3 | "serviceId": "gpt-35-turbo",
4 | "deploymentId": "gpt-35-turbo",
5 | "modelId": "gpt-35-turbo",
6 | "endpoint": "https:// ... your endpoint ... .openai.azure.com/",
7 | "apiKey": "... your Azure OpenAI key ..."
8 | }
--------------------------------------------------------------------------------
/sk-csharp-console-chat/config/appsettings.json.openai-example:
--------------------------------------------------------------------------------
1 | {
2 | "serviceType": "OpenAI",
3 | "serviceId": "gpt-3.5-turbo",
4 | "modelId": "gpt-3.5-turbo",
5 | "apiKey": "... your OpenAI key ...",
6 | "orgId": ""
7 | }
--------------------------------------------------------------------------------
/sk-csharp-console-chat/plugins/LightPlugin.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 | using Microsoft.SemanticKernel;
3 | using Microsoft.SemanticKernel.AI.ChatCompletion;
4 |
5 | namespace Plugins;
6 |
7 | ///
8 | /// A Sematic Kernel skill that interacts with ChatGPT
9 | ///
10 | internal class LightPlugin
11 | {
12 | public bool IsOn { get; set; } = false;
13 |
14 | [KernelFunction("GetState")]
15 | [Description("Gets the state of the light.")]
16 | public string GetState() => this.IsOn ? "on" : "off";
17 |
18 | [KernelFunction("ChangeState")]
19 | [Description("Changes the state of the light.'")]
20 | public string ChangeState(bool newState)
21 | {
22 | this.IsOn = newState;
23 | var state = this.GetState();
24 |
25 | // Print the state to the console
26 | Console.ForegroundColor = ConsoleColor.DarkBlue;
27 | Console.WriteLine($"[Light is now {state}]");
28 | Console.ResetColor();
29 |
30 | return state;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/sk-csharp-console-chat/sk-csharp-console-chat.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net8.0
6 | sk-csharp-console-chat
7 | enable
8 | enable
9 | 101d672c-bd5f-41ea-8f24-58b5cac0bc6d
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 | PreserveNewest
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/sk-csharp-console-chat/sk-csharp-console-chat.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.5.002.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "sk-csharp-console-chat", "sk-csharp-console-chat.csproj", "{69D2E23A-F81E-4558-B539-4348E44AA8C3}"
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 | {69D2E23A-F81E-4558-B539-4348E44AA8C3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {69D2E23A-F81E-4558-B539-4348E44AA8C3}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {69D2E23A-F81E-4558-B539-4348E44AA8C3}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {69D2E23A-F81E-4558-B539-4348E44AA8C3}.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 = {770A319D-2540-4F05-8B5D-0ACE7450BB8C}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/sk-csharp-hello-world/.gitignore:
--------------------------------------------------------------------------------
1 | appsettings.json
2 | bin
3 | obj
4 | *.ini
5 | *.cache
6 | *.log
7 | *.tmp
8 |
--------------------------------------------------------------------------------
/sk-csharp-hello-world/.vscode/extensions.json:
--------------------------------------------------------------------------------
1 | {
2 | "recommendations": [
3 | "ms-dotnettools.csharp",
4 | "ms-semantic-kernel.semantic-kernel"
5 | ]
6 | }
--------------------------------------------------------------------------------
/sk-csharp-hello-world/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | // Use IntelliSense to find out which attributes exist for C# debugging
6 | // Use hover for the description of the existing attributes
7 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
8 | "name": ".NET Core Launch (console)",
9 | "type": "coreclr",
10 | "request": "launch",
11 | "preLaunchTask": "build",
12 | // If you have changed target frameworks, make sure to update the program path.
13 | "program": "${workspaceFolder}/bin/Debug/net8.0/sk-csharp-hello-world.dll",
14 | "args": [],
15 | "cwd": "${workspaceFolder}",
16 | // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
17 | "console": "integratedTerminal",
18 | "stopAtEntry": false
19 | },
20 | {
21 | "name": ".NET Core Attach",
22 | "type": "coreclr",
23 | "request": "attach"
24 | }
25 | ]
26 | }
--------------------------------------------------------------------------------
/sk-csharp-hello-world/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "prettier.enable": true,
3 | "css.lint.validProperties": [
4 | "composes"
5 | ],
6 | "editor.defaultFormatter": "ms-dotnettools.csharp",
7 | "editor.formatOnType": true,
8 | "editor.formatOnSave": true,
9 | "editor.formatOnPaste": true,
10 | "editor.codeActionsOnSave": {
11 | "source.fixAll": true
12 | },
13 | "[csharp]": {
14 | "editor.defaultFormatter": "ms-dotnettools.csharp"
15 | },
16 | "editor.bracketPairColorization.enabled": true,
17 | "editor.guides.bracketPairs": "active",
18 | "python.formatting.provider": "autopep8",
19 | "python.formatting.autopep8Args": [
20 | "--max-line-length=120"
21 | ],
22 | "notebook.output.textLineLimit": 500,
23 | "python.analysis.extraPaths": [
24 | "./python/src"
25 | ],
26 | "javascript.updateImportsOnFileMove.enabled": "always",
27 | "search.exclude": {
28 | "**/node_modules": true,
29 | "**/bower_components": true,
30 | "**/build": true
31 | },
32 | "[typescript]": {
33 | "editor.defaultFormatter": "esbenp.prettier-vscode",
34 | "editor.codeActionsOnSave": {
35 | "source.organizeImports": true,
36 | "source.fixAll": true
37 | }
38 | },
39 | "[typescriptreact]": {
40 | "editor.defaultFormatter": "esbenp.prettier-vscode",
41 | "editor.codeActionsOnSave": {
42 | "source.organizeImports": true,
43 | "source.fixAll": true
44 | }
45 | },
46 | "typescript.updateImportsOnFileMove.enabled": "always",
47 | "eslint.enable": true,
48 | "eslint.validate": [
49 | "javascript",
50 | "javascriptreact",
51 | "typescript",
52 | "typescriptreact"
53 | ],
54 | "eslint.lintTask.enable": true,
55 | "eslint.workingDirectories": [
56 | {
57 | "mode": "auto"
58 | }
59 | ],
60 | "eslint.options": {
61 | "overrideConfigFile": ".eslintrc.js"
62 | },
63 | "eslint.packageManager": "yarn",
64 | "files.associations": {
65 | "*.json": "jsonc"
66 | },
67 | "files.exclude": {
68 | "**/.git": true,
69 | "**/.svn": true,
70 | "**/.hg": true,
71 | "**/CVS": true,
72 | "**/.DS_Store": true,
73 | "**/Thumbs.db": true
74 | },
75 | "cSpell.words": [
76 | "Partitioner"
77 | ]
78 | }
--------------------------------------------------------------------------------
/sk-csharp-hello-world/.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}/sk-csharp-hello-world.csproj",
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}/sk-csharp-hello-world.csproj",
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}/sk-csharp-hello-world.csproj"
37 | ],
38 | "problemMatcher": "$msCompile"
39 | }
40 | ]
41 | }
--------------------------------------------------------------------------------
/sk-csharp-hello-world/Program.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using Microsoft.Extensions.DependencyInjection;
3 | using Microsoft.Extensions.Logging;
4 | using Microsoft.SemanticKernel;
5 | using Microsoft.SemanticKernel.ChatCompletion;
6 | using Microsoft.SemanticKernel.Connectors.OpenAI;
7 | using Microsoft.SemanticKernel.PromptTemplates.Handlebars;
8 | using Plugins;
9 |
10 | var kernelSettings = KernelSettings.LoadSettings();
11 |
12 | var builder = Kernel.CreateBuilder();
13 | builder.Services.AddLogging(c => c.SetMinimumLevel(LogLevel.Information).AddDebug());
14 | builder.Services.AddChatCompletionService(kernelSettings);
15 | builder.Plugins.AddFromType();
16 |
17 | Kernel kernel = builder.Build();
18 |
19 | // Load prompt from resource
20 | using StreamReader reader = new(Assembly.GetExecutingAssembly().GetManifestResourceStream("prompts.Chat.yaml")!);
21 | KernelFunction prompt = kernel.CreateFunctionFromPromptYaml(
22 | reader.ReadToEnd(),
23 | promptTemplateFactory: new HandlebarsPromptTemplateFactory()
24 | );
25 |
26 | // Create the chat history
27 | ChatHistory chatMessages = [];
28 |
29 | // Loop till we are cancelled
30 | while (true)
31 | {
32 | // Get user input
33 | System.Console.Write("User > ");
34 | chatMessages.AddUserMessage(Console.ReadLine()!);
35 |
36 | // Get the chat completions
37 | OpenAIPromptExecutionSettings openAIPromptExecutionSettings = new()
38 | {
39 | ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions
40 | };
41 |
42 | var result = kernel.InvokeStreamingAsync(
43 | prompt,
44 | arguments: new(openAIPromptExecutionSettings) {
45 | { "messages", chatMessages }
46 | });
47 |
48 | // Print the chat completions
49 | ChatMessageContent? chatMessageContent = null;
50 | await foreach (var content in result)
51 | {
52 | System.Console.Write(content);
53 | if (chatMessageContent == null)
54 | {
55 | System.Console.Write("Assistant > ");
56 | chatMessageContent = new ChatMessageContent(
57 | content.Role ?? AuthorRole.Assistant,
58 | content.ModelId!,
59 | content.Content!,
60 | content.InnerContent,
61 | content.Encoding,
62 | content.Metadata);
63 | }
64 | else
65 | {
66 | chatMessageContent.Content += content;
67 | }
68 | }
69 | System.Console.WriteLine();
70 | if (chatMessageContent != null)
71 | {
72 | chatMessages.AddMessage(chatMessageContent.Role, chatMessageContent.Content!);
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/sk-csharp-hello-world/config/EndpointTypes.cs:
--------------------------------------------------------------------------------
1 | internal static class EndpointTypes
2 | {
3 | internal const string TextCompletion = "text-completion";
4 | internal const string ChatCompletion = "chat-completion";
5 | }
6 |
--------------------------------------------------------------------------------
/sk-csharp-hello-world/config/ServiceCollectionExtensions.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Extensions.DependencyInjection;
2 | using Microsoft.SemanticKernel;
3 |
4 | internal static class ServiceCollectionExtensions
5 | {
6 | ///
7 | /// Adds a chat completion service to the list. It can be either an OpenAI or Azure OpenAI backend service.
8 | ///
9 | ///
10 | ///
11 | ///
12 | internal static IServiceCollection AddChatCompletionService(this IServiceCollection serviceCollection, KernelSettings kernelSettings)
13 | {
14 | switch (kernelSettings.ServiceType.ToUpperInvariant())
15 | {
16 | case ServiceTypes.AzureOpenAI:
17 | serviceCollection = serviceCollection.AddAzureOpenAIChatCompletion(kernelSettings.DeploymentId, endpoint: kernelSettings.Endpoint, apiKey: kernelSettings.ApiKey, serviceId: kernelSettings.ServiceId);
18 | break;
19 |
20 | case ServiceTypes.OpenAI:
21 | serviceCollection = serviceCollection.AddOpenAIChatCompletion(modelId: kernelSettings.ModelId, apiKey: kernelSettings.ApiKey, orgId: kernelSettings.OrgId, serviceId: kernelSettings.ServiceId);
22 | break;
23 |
24 | default:
25 | throw new ArgumentException($"Invalid service type value: {kernelSettings.ServiceType}");
26 | }
27 |
28 | return serviceCollection;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/sk-csharp-hello-world/config/ServiceTypes.cs:
--------------------------------------------------------------------------------
1 | internal static class ServiceTypes
2 | {
3 | internal const string OpenAI = "OPENAI";
4 | internal const string AzureOpenAI = "AZUREOPENAI";
5 | }
6 |
--------------------------------------------------------------------------------
/sk-csharp-hello-world/config/appsettings.json.azure-example:
--------------------------------------------------------------------------------
1 | {
2 | "endpointType": "text-completion",
3 | "serviceType": "AzureOpenAI",
4 | "serviceId": "text-davinci-003",
5 | "deploymentOrModelId": "text-davinci-003",
6 | "endpoint": "https:// ... your endpoint ... .openai.azure.com/",
7 | "apiKey": "... your Azure OpenAI key ..."
8 | }
--------------------------------------------------------------------------------
/sk-csharp-hello-world/config/appsettings.json.openai-example:
--------------------------------------------------------------------------------
1 | {
2 | "endpointType": "text-completion",
3 | "serviceType": "OpenAI",
4 | "serviceId": "text-davinci-003",
5 | "deploymentOrModelId": "text-davinci-003",
6 | "apiKey": "... your OpenAI key ...",
7 | "orgId": ""
8 | }
--------------------------------------------------------------------------------
/sk-csharp-hello-world/plugins/LightPlugin.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 | using Microsoft.SemanticKernel;
3 | using Microsoft.SemanticKernel.ChatCompletion;
4 |
5 | namespace Plugins;
6 |
7 | ///
8 | /// A Sematic Kernel skill that interacts with ChatGPT
9 | ///
10 | internal class LightPlugin
11 | {
12 | public bool IsOn { get; set; } = false;
13 |
14 | [KernelFunction("GetState")]
15 | [Description("Gets the state of the light.")]
16 | public string GetState() => this.IsOn ? "on" : "off";
17 |
18 | [KernelFunction("ChangeState")]
19 | [Description("Changes the state of the light.'")]
20 | public string ChangeState(bool newState)
21 | {
22 | this.IsOn = newState;
23 | var state = this.GetState();
24 |
25 | // Print the state to the console
26 | Console.ForegroundColor = ConsoleColor.DarkBlue;
27 | Console.WriteLine($"[Light is now {state}]");
28 | Console.ResetColor();
29 |
30 | return state;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/sk-csharp-hello-world/prompts/Chat.yaml:
--------------------------------------------------------------------------------
1 | name: Chat
2 | template: |
3 | You are a helpful assistant.
4 |
5 | {{#each messages}}
6 | {{~Content~}}
7 | {{/each}}
8 | template_format: handlebars
9 | description: A function that uses the chat history to respond to the user.
10 | input_variables:
11 | - name: messages
12 | description: The history of the chat.
13 | is_required: true
14 |
--------------------------------------------------------------------------------
/sk-csharp-hello-world/sk-csharp-hello-world.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net8.0
6 |
7 | enable
8 | enable
9 | 101d672c-bd5f-41ea-8f24-58b5cac0bc6d
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 | PreserveNewest
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/sk-csharp-hello-world/sk-csharp-hello-world.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.5.002.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "sk-csharp-hello-world", "sk-csharp-hello-world.csproj", "{0EC2E9FB-726B-4D62-9E46-50D990CD5DAB}"
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 | {0EC2E9FB-726B-4D62-9E46-50D990CD5DAB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {0EC2E9FB-726B-4D62-9E46-50D990CD5DAB}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {0EC2E9FB-726B-4D62-9E46-50D990CD5DAB}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {0EC2E9FB-726B-4D62-9E46-50D990CD5DAB}.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 = {D9F27F41-C007-4175-98D1-C2FAAD0B2F0E}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/sk-java-hello-world/README.md:
--------------------------------------------------------------------------------
1 | # Semantic Kernel Java Hello World Starter
2 |
3 | The `sk-java-hello-world` console application demonstrates how to execute a semantic function.
4 |
5 | ## Prerequisites
6 |
7 | - [Java](https://learn.microsoft.com/java/openjdk/download) 11 or above.
8 | - [Maven](https://maven.apache.org/download.cgi)
9 |
10 | ## Configuring the starter
11 |
12 | The starter can be configured with a `conf.properties` file in the project which holds api keys and other secrets and configurations.
13 |
14 | Make sure you have an
15 | [Open AI API Key](https://openai.com/api/) or
16 | [Azure Open AI service key](https://learn.microsoft.com/azure/cognitive-services/openai/quickstart?pivots=rest-api).
17 |
18 | Copy the `example.conf.properties` file to a new file named `conf.properties`. Then, copy those keys into the `conf.properties` file.
19 |
20 | If you are using Open AI:
21 |
22 | ```
23 | client.openai.key=""
24 | client.openai.organizationid=""
25 | ```
26 |
27 | Or, if you are using Azure Open AI:
28 |
29 | ```
30 | client.azureopenai.key=""
31 | client.azureopenai.endpoint=""
32 | client.azureopenai.deploymentname=""
33 | ```
34 |
35 | ## Running the starter
36 |
37 | Run the starter using maven:
38 |
39 | ```
40 | mvn compile exec:java
41 | ```
42 |
--------------------------------------------------------------------------------
/sk-java-hello-world/example.conf.properties:
--------------------------------------------------------------------------------
1 | client.openai.key=""
2 | client.openai.organizationid=""
3 |
4 | client.azureopenai.key=""
5 | client.azureopenai.endpoint=""
6 | client.azureopenai.deploymentname=""
--------------------------------------------------------------------------------
/sk-java-hello-world/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | com.microsoft.semantickernel
8 | sk-java-hello-world
9 | 1.0-SNAPSHOT
10 |
11 |
12 |
13 |
14 | com.microsoft.semantic-kernel
15 | semantickernel-bom
16 | 0.2.11-alpha
17 | import
18 | pom
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 | org.codehaus.mojo
27 | exec-maven-plugin
28 | 3.1.0
29 |
30 | com.microsoft.semantickernel.helloworld.Main
31 |
32 |
33 |
34 |
35 |
36 | false
37 |
38 |
39 |
40 |
41 | com.microsoft.semantic-kernel
42 | semantickernel-api
43 |
44 |
45 | com.microsoft.semantic-kernel
46 | semantickernel-connectors-ai-openai
47 |
48 |
49 | com.microsoft.semantic-kernel
50 | semantickernel-core
51 |
52 |
53 | com.microsoft.semantic-kernel
54 | semantickernel-settings-loader
55 |
56 |
57 |
--------------------------------------------------------------------------------
/sk-java-hello-world/src/main/java/com/microsoft/semantickernel/helloworld/Main.java:
--------------------------------------------------------------------------------
1 | package com.microsoft.semantickernel.helloworld;
2 |
3 | import com.azure.ai.openai.OpenAIAsyncClient;
4 | import com.microsoft.semantickernel.Kernel;
5 | import com.microsoft.semantickernel.SKBuilders;
6 | import com.microsoft.semantickernel.connectors.ai.openai.util.OpenAIClientProvider;
7 | import com.microsoft.semantickernel.exceptions.ConfigurationException;
8 | import com.microsoft.semantickernel.orchestration.SKContext;
9 | import com.microsoft.semantickernel.textcompletion.CompletionSKFunction;
10 | import reactor.core.publisher.Mono;
11 |
12 | public class Main {
13 | public static void main(String[] args) throws ConfigurationException {
14 | // Configure OpenAI client. Load settings from conf.properties
15 | OpenAIAsyncClient client = OpenAIClientProvider.getClient();
16 |
17 | // Build Kernel with Text Completion service
18 | Kernel kernel = SKBuilders.kernel()
19 | .withDefaultAIService(SKBuilders.textCompletion()
20 | .withOpenAIClient(client)
21 | .withModelId("text-davinci-003")
22 | .build())
23 | .build();
24 |
25 | // Import semantic skill
26 | kernel.importSkillFromResources("skills", "FunSkill", "Joke");
27 |
28 | CompletionSKFunction joke = (CompletionSKFunction) kernel.getFunction("FunSkill", "Joke");
29 | // Set input variable for Joke function
30 | SKContext context = SKBuilders.context().build()
31 | .setVariable("input", "Time travel to dinosaur age")
32 | .setVariable("style", "Wacky");
33 |
34 | // Invoke function and get result
35 | Mono result = joke.invokeAsync(context);
36 |
37 | System.out.println(result.block().getResult());
38 | }
39 | }
--------------------------------------------------------------------------------
/sk-java-hello-world/src/main/resources/skills/FunSkill/Excuses/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "description": "Turn a scenario into a creative or humorous excuse to send your boss",
4 | "type": "completion",
5 | "completion": {
6 | "max_tokens": 60,
7 | "temperature": 0.5,
8 | "top_p": 0,
9 | "presence_penalty": 0,
10 | "frequency_penalty": 0
11 | },
12 | "input": {
13 | "parameters": [
14 | {
15 | "name": "input",
16 | "description": "The event to generate an excuse for",
17 | "defaultValue": ""
18 | }
19 | ]
20 | }
21 | }
--------------------------------------------------------------------------------
/sk-java-hello-world/src/main/resources/skills/FunSkill/Excuses/skprompt.txt:
--------------------------------------------------------------------------------
1 | Generate a creative reason or excuse for the given event. Be creative and be funny. Let your imagination run wild.
2 |
3 | Event:I am running late.
4 | Excuse:I was being held ransom by giraffe gangsters.
5 |
6 | Event:{{$input}}
--------------------------------------------------------------------------------
/sk-java-hello-world/src/main/resources/skills/FunSkill/Joke/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "description": "Generate a funny joke",
4 | "type": "completion",
5 | "completion": {
6 | "max_tokens": 1000,
7 | "temperature": 0.9,
8 | "top_p": 0,
9 | "presence_penalty": 0,
10 | "frequency_penalty": 0
11 | },
12 | "input": {
13 | "parameters": [
14 | {
15 | "name": "input",
16 | "description": "The subject of the joke",
17 | "defaultValue": ""
18 | },
19 | {
20 | "name": "style",
21 | "description": "The style of the joke",
22 | "defaultValue": ""
23 | }
24 | ]
25 | }
26 | }
--------------------------------------------------------------------------------
/sk-java-hello-world/src/main/resources/skills/FunSkill/Joke/skprompt.txt:
--------------------------------------------------------------------------------
1 | WRITE EXACTLY ONE JOKE or HUMOROUS STORY ABOUT THE TOPIC BELOW
2 |
3 | JOKE MUST BE:
4 | - G RATED
5 | - WORKPLACE/FAMILY SAFE
6 | NO SEXISM, RACISM OR OTHER BIAS/BIGOTRY
7 |
8 | BE CREATIVE AND FUNNY. I WANT TO LAUGH.
9 | +++++
10 | STYLE:
11 | {{$style}}
12 | +++++
13 | TOPIC:
14 | {{$input}}
15 | +++++
16 |
--------------------------------------------------------------------------------
/sk-java-hello-world/src/main/resources/skills/FunSkill/Limerick/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "schema": 1,
3 | "description": "Generate a funny limerick about a person",
4 | "type": "completion",
5 | "completion": {
6 | "max_tokens": 100,
7 | "temperature": 0.7,
8 | "top_p": 0,
9 | "presence_penalty": 0,
10 | "frequency_penalty": 0
11 | },
12 | "input": {
13 | "parameters": [
14 | {
15 | "name": "name",
16 | "description": "The name of the person who the Limerick is about",
17 | "defaultValue": ""
18 | },
19 | {
20 | "name": "input",
21 | "description": "The theme of the Limerick",
22 | "defaultValue": ""
23 | }
24 | ]
25 | }
26 | }
--------------------------------------------------------------------------------
/sk-java-hello-world/src/main/resources/skills/FunSkill/Limerick/skprompt.txt:
--------------------------------------------------------------------------------
1 | There was a young woman named Bright,
2 | Whose speed was much faster than light.
3 | She set out one day,
4 | In a relative way,
5 | And returned on the previous night.
6 |
7 | There was an odd fellow named Gus,
8 | When traveling he made such a fuss.
9 | He was banned from the train,
10 | Not allowed on a plane,
11 | And now travels only by bus.
12 |
13 | There once was a man from Tibet,
14 | Who couldn't find a cigarette
15 | So he smoked all his socks,
16 | and got chicken-pox,
17 | and had to go to the vet.
18 |
19 | There once was a boy named Dan,
20 | who wanted to fry in a pan.
21 | He tried and he tried,
22 | and eventually died,
23 | that weird little boy named Dan.
24 |
25 | Now write a very funny limerick about {{$name}}.
26 | {{$input}}
27 | Invent new facts about their life. Must be funny.
28 |
--------------------------------------------------------------------------------
/sk-process-framework/declarative/ProductDocumentation/README.md:
--------------------------------------------------------------------------------
1 | # Process Framework: Product Documentation declarative example
2 |
3 | This project example demonstrates how to define, preview, and execute a process of generating product documentation using declarative AI Agents as process steps.
4 |
5 | Note: it is recommended to work with this example using [Semantic Kernel Tools](https://marketplace.visualstudio.com/items?itemName=ms-semantic-kernel.semantic-kernel) VS Code extension.
6 |
7 | ## Getting Started
8 |
9 | 1. Open the [product-documentation.process.yaml](./product-documentation.process.yaml) file in VS Code to start working with processes.
10 |
11 | ## Features
12 |
13 | ### Select an AI Model
14 |
15 | To select an AI model:
16 | - Open the Semantic Kernel extension in the side panel of Visual Studio Code.
17 | - In the "AI Endpoints" section, choose your preferred AI provider and model.
18 |
19 | 
20 |
21 | ### Preview a Process
22 |
23 | To preview a process:
24 | - Open the [product-documentation.process.yaml](./product-documentation.process.yaml) file.
25 | - Click the **Preview Process** button in the top bar of the process file.
26 |
27 | 
28 |
29 | ### Debug a Process
30 |
31 | To debug a process:
32 | - Open the [product-documentation.process.yaml](./product-documentation.process.yaml) file.
33 | - Click the **Debug Process** button in the top bar of the process file.
34 |
35 | 
36 |
37 | ## Reporting Issues
38 |
39 | If you encounter any issues or have suggestions, please report them on our [GitHub repository](https://github.com/microsoft/semantic-kernel).
40 |
--------------------------------------------------------------------------------
/sk-process-framework/declarative/ProductDocumentation/images/debug-process.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/semantic-kernel-starters/2df40f4c0ca9bd5a4baeefd68e17baaf7bf8e366/sk-process-framework/declarative/ProductDocumentation/images/debug-process.jpeg
--------------------------------------------------------------------------------
/sk-process-framework/declarative/ProductDocumentation/images/preview-process.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/semantic-kernel-starters/2df40f4c0ca9bd5a4baeefd68e17baaf7bf8e366/sk-process-framework/declarative/ProductDocumentation/images/preview-process.jpeg
--------------------------------------------------------------------------------
/sk-process-framework/declarative/ProductDocumentation/images/select-model.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/semantic-kernel-starters/2df40f4c0ca9bd5a4baeefd68e17baaf7bf8e366/sk-process-framework/declarative/ProductDocumentation/images/select-model.jpeg
--------------------------------------------------------------------------------
/sk-process-framework/declarative/ProductDocumentation/product-documentation.process.yaml:
--------------------------------------------------------------------------------
1 | workflow:
2 | id: ProductDocumentation
3 | inputs:
4 | events:
5 | cloud_events:
6 | - type: input_message_received
7 | data_schema:
8 | type: string
9 | nodes:
10 | - id: ProductDocumentationAgent
11 | type: declarative
12 | description: Generates an information about the product
13 | agent:
14 | type: chat_completion_agent
15 | name: ProductDocumentationAgent
16 | description: Generates an information about the product
17 | instructions: Generate a short information about coffee machine product.
18 | on_complete:
19 | - on_condition:
20 | type: default
21 | emits:
22 | - event_type: GeneratedInformation.OnResult
23 | - id: SummarizationAgent
24 | type: declarative
25 | description: Summarizes the provided information
26 | agent:
27 | type: chat_completion_agent
28 | name: SummarizationAgent
29 | description: Summarizes the provided information
30 | instructions: Summarize the provided information in 3 sentences.
31 | on_complete:
32 | - on_condition:
33 | type: default
34 | emits:
35 | - event_type: ProcessCompleted
36 | orchestration:
37 | - listen_for:
38 | event: input_message_received
39 | from: _workflow_
40 | then:
41 | - node: ProductDocumentationAgent
42 | - listen_for:
43 | event: GeneratedInformation.OnResult
44 | from: ProductDocumentationAgent
45 | then:
46 | - node: SummarizationAgent
47 |
--------------------------------------------------------------------------------
/sk-process-framework/dotnet/ProductDocumentation/ProductDocumentation.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net8.0
5 | enable
6 | enable
7 | SKEXP0080
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/sk-process-framework/dotnet/ProductDocumentation/README.md:
--------------------------------------------------------------------------------
1 | # Process Framework: Product Documentation .NET example
2 |
3 | This project example demonstrates how to define, preview, and execute a process of generating product documentation using .NET classes as process steps.
4 |
5 | Note: it is recommended to work with this example using [Semantic Kernel Tools](https://marketplace.visualstudio.com/items?itemName=ms-semantic-kernel.semantic-kernel) VS Code extension.
6 |
7 | ## Prerequisites
8 |
9 | - Install [.NET 8](https://dotnet.microsoft.com/download/dotnet/8.0).
10 |
11 | ## Setup
12 |
13 | 1. Open a terminal in the project directory.
14 | 2. Run `dotnet build` command to build the logic of the process nodes.
15 |
16 | ## Getting Started
17 |
18 | 1. Open the [product-documentation.process.yaml](./product-documentation.process.yaml) file in VS Code to start working with processes.
19 |
20 | ## Features
21 |
22 | ### Select an AI Model
23 |
24 | To select an AI model:
25 | - Open the Semantic Kernel extension in the side panel of Visual Studio Code.
26 | - In the "AI Endpoints" section, choose your preferred AI provider and model.
27 |
28 | 
29 |
30 | ### Preview a Process
31 |
32 | To preview a process:
33 | - Open the [product-documentation.process.yaml](./product-documentation.process.yaml) file.
34 | - Click the **Preview Process** button in the top bar of the process file.
35 |
36 | 
37 |
38 | ### Debug a Process
39 |
40 | To debug a process:
41 | - Open the [product-documentation.process.yaml](./product-documentation.process.yaml) file.
42 | - Click the **Debug Process** button in the top bar of the process file.
43 |
44 | 
45 |
46 | ### Process Node Logic
47 |
48 | - The source code for each process node's logic is located in the [Steps](./Steps/) folder.
49 | - Explore this folder to review or modify the logic for individual process steps.
50 |
51 | ## Reporting Issues
52 |
53 | If you encounter any issues or have suggestions, please report them on our [GitHub repository](https://github.com/microsoft/semantic-kernel).
54 |
--------------------------------------------------------------------------------
/sk-process-framework/dotnet/ProductDocumentation/Steps/GenerateDocumentationStep.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 | using Microsoft.SemanticKernel.ChatCompletion;
3 |
4 | namespace Steps;
5 |
6 | public sealed class GenerateDocumentationStep : KernelProcessStep
7 | {
8 | private GeneratedDocumentationState _state = new();
9 |
10 | private const string SystemPrompt =
11 | """
12 | Your job is to write high quality and engaging customer facing documentation for a new product from Contoso. You will be provide with information
13 | about the product in the form of internal documentation, specs, and troubleshooting guides and you must use this information and
14 | nothing else to generate the documentation. If suggestions are provided on the documentation you create, take the suggestions into account and
15 | rewrite the documentation. Make sure the product sounds amazing.
16 | """;
17 |
18 | public override ValueTask ActivateAsync(KernelProcessStepState state)
19 | {
20 | this._state = state.State!;
21 | this._state.ChatHistory ??= new ChatHistory(SystemPrompt);
22 |
23 | return base.ActivateAsync(state);
24 | }
25 |
26 | [KernelFunction]
27 | public async Task GenerateDocumentationAsync(Kernel kernel, string productInfo)
28 | {
29 | // Add the new product info to the chat history
30 | this._state.ChatHistory!.AddUserMessage($"Product Info:\n\n{productInfo}");
31 |
32 | // Get a response from the LLM
33 | IChatCompletionService chatCompletionService = kernel.GetRequiredService();
34 | var generatedDocumentationResponse = await chatCompletionService.GetChatMessageContentAsync(this._state.ChatHistory!);
35 |
36 | var documentationString = generatedDocumentationResponse.Content!.ToString();
37 |
38 | return documentationString;
39 | }
40 | }
41 |
42 | public class GeneratedDocumentationState
43 | {
44 | public ChatHistory? ChatHistory { get; set; }
45 | }
46 |
--------------------------------------------------------------------------------
/sk-process-framework/dotnet/ProductDocumentation/Steps/GetProductInfoStep.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 |
3 | namespace Steps;
4 |
5 | public sealed class GetProductInfoStep : KernelProcessStep
6 | {
7 | [KernelFunction]
8 | public string GetProductInfo()
9 | {
10 | return
11 | """
12 | Product Description:
13 | GlowBrew is a revolutionary AI driven coffee machine with industry leading number of LEDs and programmable light shows. The machine is also capable of brewing coffee and has a built in grinder.
14 |
15 | Product Features:
16 | 1. **Luminous Brew Technology**: Customize your morning ambiance with programmable LED lights that sync with your brewing process.
17 | 2. **AI Taste Assistant**: Learns your taste preferences over time and suggests new brew combinations to explore.
18 | 3. **Gourmet Aroma Diffusion**: Built-in aroma diffusers enhance your coffee's scent profile, energizing your senses before the first sip.
19 |
20 | Troubleshooting:
21 | - **Issue**: LED Lights Malfunctioning
22 | - **Solution**: Reset the lighting settings via the app. Ensure the LED connections inside the GlowBrew are secure. Perform a factory reset if necessary.
23 | """;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/sk-process-framework/dotnet/ProductDocumentation/Steps/PublishDocumentationStep.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 |
3 | namespace Steps;
4 |
5 | public sealed class PublishDocumentationStep : KernelProcessStep
6 | {
7 | [KernelFunction]
8 | public string PublishDocumentation()
9 | {
10 | return "Publishing product documentation...";
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/sk-process-framework/dotnet/ProductDocumentation/images/debug-process.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/semantic-kernel-starters/2df40f4c0ca9bd5a4baeefd68e17baaf7bf8e366/sk-process-framework/dotnet/ProductDocumentation/images/debug-process.jpeg
--------------------------------------------------------------------------------
/sk-process-framework/dotnet/ProductDocumentation/images/preview-process.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/semantic-kernel-starters/2df40f4c0ca9bd5a4baeefd68e17baaf7bf8e366/sk-process-framework/dotnet/ProductDocumentation/images/preview-process.jpeg
--------------------------------------------------------------------------------
/sk-process-framework/dotnet/ProductDocumentation/images/select-model.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/semantic-kernel-starters/2df40f4c0ca9bd5a4baeefd68e17baaf7bf8e366/sk-process-framework/dotnet/ProductDocumentation/images/select-model.jpeg
--------------------------------------------------------------------------------
/sk-process-framework/dotnet/ProductDocumentation/product-documentation.process.yaml:
--------------------------------------------------------------------------------
1 | workflow:
2 | id: ProductDocumentation
3 | inputs:
4 | events:
5 | cloud_events:
6 | - type: input_message_received
7 | data_schema:
8 | type: string
9 | nodes:
10 | - id: GetProductInfoStep
11 | type: dotnet
12 | description: Gather information about the product
13 | agent:
14 | type: Steps.GetProductInfoStep, ProductDocumentation
15 | on_complete:
16 | - on_condition:
17 | type: default
18 | emits:
19 | - event_type: GetProductInfo.OnResult
20 | - id: GenerateDocumentationStep
21 | type: dotnet
22 | description: Generate documentation for the product with LLM
23 | agent:
24 | type: Steps.GenerateDocumentationStep, ProductDocumentation
25 | on_complete:
26 | - on_condition:
27 | type: default
28 | emits:
29 | - event_type: GenerateDocumentation.OnResult
30 | - id: PublishDocumentationStep
31 | type: dotnet
32 | description: Publish the documentation
33 | agent:
34 | type: Steps.PublishDocumentationStep, ProductDocumentation
35 | on_complete:
36 | - on_condition:
37 | type: default
38 | emits:
39 | - event_type: ProcessCompleted
40 | orchestration:
41 | - listen_for:
42 | event: input_message_received
43 | from: _workflow_
44 | then:
45 | - node: GetProductInfoStep
46 | - listen_for:
47 | event: GetProductInfo.OnResult
48 | from: GetProductInfoStep
49 | then:
50 | - node: GenerateDocumentationStep
51 | - listen_for:
52 | event: GenerateDocumentation.OnResult
53 | from: GenerateDocumentationStep
54 | then:
55 | - node: PublishDocumentationStep
56 |
--------------------------------------------------------------------------------
/sk-process-framework/other/ProductDocumentation/Filters/ConsoleOutputFunctionInvocationFilter.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json;
2 | using Microsoft.SemanticKernel;
3 |
4 | namespace Filters;
5 |
6 | public sealed class ConsoleOutputFunctionInvocationFilter : IFunctionInvocationFilter
7 | {
8 | public async Task OnFunctionInvocationAsync(FunctionInvocationContext context, Func next)
9 | {
10 | Console.WriteLine($"\nNode: {context.Function.PluginName}");
11 |
12 | await next(context);
13 |
14 | Console.WriteLine($"\nResult:");
15 |
16 | object? result = context.Result.GetValue