├── .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 | ![Select AI Model](images/select-model.jpeg) 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 | ![Preview Process](images/preview-process.jpeg) 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 | ![Debug Process](images/debug-process.jpeg) 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 | ![Select AI Model](images/select-model.jpeg) 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 | ![Preview Process](images/preview-process.jpeg) 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 | ![Debug Process](images/debug-process.jpeg) 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(); 17 | 18 | if (result is string resultString) 19 | { 20 | Console.WriteLine(resultString); 21 | } 22 | else if (result is not null) 23 | { 24 | Console.WriteLine(JsonSerializer.Serialize(result)); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /sk-process-framework/other/ProductDocumentation/ProductDocumentation.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | SKEXP0080 9 | 0d0e74cd-2b8a-4173-ac6e-fbfcfbdaf12f 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | PreserveNewest 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /sk-process-framework/other/ProductDocumentation/README.md: -------------------------------------------------------------------------------- 1 | # Process Framework: Product Documentation .NET and declarative example 2 | 3 | This project example demonstrates how to define, preview, and execute a process of generating product documentation using .NET classes and 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 | ## 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 | 3. Run `dotnet user-secrets set "AZUREOPENAI_DEPLOYMENT_NAME" "YOUR_DEPLOYMENT_NAME"` to configure Azure OpenAI deployment name. 16 | 4. Run `dotnet user-secrets set "AZUREOPENAI_ENDPOINT" "YOUR_ENDPOINT"` to configure Azure OpenAI endpoint. 17 | 5. Run `az login` to authenticate using Azure CLI and get an access to Azure OpenAI deployment. 18 | 19 | ## Getting Started 20 | 21 | 1. Open the [product-documentation.process.yaml](./product-documentation.process.yaml) file in VS Code to start working with processes. 22 | 2. Open the [Program.cs](./Program.cs) file in VS Code to learn about imperative and declarative process approaches. 23 | 24 | ## Features 25 | 26 | ### Select an AI Model 27 | 28 | To select an AI model: 29 | - Open the Semantic Kernel extension in the side panel of Visual Studio Code. 30 | - In the "AI Endpoints" section, choose your preferred AI provider and model. 31 | 32 | ![Select AI Model](images/select-model.jpeg) 33 | 34 | ### Preview a Process 35 | 36 | To preview a process: 37 | - Open the [product-documentation.process.yaml](./product-documentation.process.yaml) file. 38 | - Click the **Preview Process** button in the top bar of the process file. 39 | 40 | ![Preview Process](images/preview-process.jpeg) 41 | 42 | ### Debug a Process 43 | 44 | To debug a process: 45 | - Open the [product-documentation.process.yaml](./product-documentation.process.yaml) file. 46 | - Click the **Debug Process** button in the top bar of the process file. 47 | 48 | ![Debug Process](images/debug-process.jpeg) 49 | 50 | ### Process Node Logic 51 | 52 | - The source code for each process node's logic is located in the [Steps](./Steps/) folder. 53 | - Explore this folder to review or modify the logic for individual process steps. 54 | 55 | ## Reporting Issues 56 | 57 | If you encounter any issues or have suggestions, please report them on our [GitHub repository](https://github.com/microsoft/semantic-kernel). 58 | -------------------------------------------------------------------------------- /sk-process-framework/other/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/other/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/other/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/other/ProductDocumentation/images/debug-process.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/semantic-kernel-starters/2df40f4c0ca9bd5a4baeefd68e17baaf7bf8e366/sk-process-framework/other/ProductDocumentation/images/debug-process.jpeg -------------------------------------------------------------------------------- /sk-process-framework/other/ProductDocumentation/images/preview-process.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/semantic-kernel-starters/2df40f4c0ca9bd5a4baeefd68e17baaf7bf8e366/sk-process-framework/other/ProductDocumentation/images/preview-process.jpeg -------------------------------------------------------------------------------- /sk-process-framework/other/ProductDocumentation/images/select-model.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/semantic-kernel-starters/2df40f4c0ca9bd5a4baeefd68e17baaf7bf8e366/sk-process-framework/other/ProductDocumentation/images/select-model.jpeg -------------------------------------------------------------------------------- /sk-process-framework/other/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: GenerateDocumentationAgent 21 | type: declarative 22 | description: Generates a documentation for provided product 23 | agent: 24 | type: chat_completion_agent 25 | name: GenerateDocumentationAgent 26 | description: Generates a documentation for provided product 27 | instructions: | 28 | Your job is to write high quality and engaging customer facing documentation for a new product from Contoso. You will be provide with information 29 | about the product in the form of internal documentation, specs, and troubleshooting guides and you must use this information and 30 | nothing else to generate the documentation. If suggestions are provided on the documentation you create, take the suggestions into account and 31 | rewrite the documentation. Make sure the product sounds amazing. 32 | on_complete: 33 | - on_condition: 34 | type: default 35 | emits: 36 | - event_type: GenerateDocumentation.OnResult 37 | - id: PublishDocumentationStep 38 | type: dotnet 39 | description: Publish the documentation 40 | agent: 41 | type: Steps.PublishDocumentationStep, ProductDocumentation 42 | on_complete: 43 | - on_condition: 44 | type: default 45 | emits: 46 | - event_type: ProcessCompleted 47 | orchestration: 48 | - listen_for: 49 | event: input_message_received 50 | from: _workflow_ 51 | then: 52 | - node: GetProductInfoStep 53 | - listen_for: 54 | event: GetProductInfo.OnResult 55 | from: GetProductInfoStep 56 | then: 57 | - node: GenerateDocumentationAgent 58 | - listen_for: 59 | event: GenerateDocumentation.OnResult 60 | from: GenerateDocumentationAgent 61 | then: 62 | - node: PublishDocumentationStep 63 | -------------------------------------------------------------------------------- /sk-python-azure-functions-chatgpt-plugin/.env.example: -------------------------------------------------------------------------------- 1 | OPENAI_API_KEY="" 2 | OPENAI_ORG_ID="" 3 | AZURE_OPENAI_DEPLOYMENT_NAME="" 4 | AZURE_OPENAI_ENDPOINT="" 5 | AZURE_OPENAI_API_KEY="" 6 | -------------------------------------------------------------------------------- /sk-python-azure-functions-chatgpt-plugin/.funcignore: -------------------------------------------------------------------------------- 1 | .git* 2 | .vscode 3 | __azurite_db*__.json 4 | __blobstorage__ 5 | __queuestorage__ 6 | local.settings.json 7 | test 8 | .venv -------------------------------------------------------------------------------- /sk-python-azure-functions-chatgpt-plugin/.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | 53 | # Translations 54 | *.mo 55 | *.pot 56 | 57 | # Django stuff: 58 | *.log 59 | local_settings.py 60 | db.sqlite3 61 | 62 | # Flask stuff: 63 | instance/ 64 | .webassets-cache 65 | 66 | # Scrapy stuff: 67 | .scrapy 68 | 69 | # Sphinx documentation 70 | docs/_build/ 71 | 72 | # PyBuilder 73 | target/ 74 | 75 | # Jupyter Notebook 76 | .ipynb_checkpoints 77 | 78 | # IPython 79 | profile_default/ 80 | ipython_config.py 81 | 82 | # pyenv 83 | .python-version 84 | 85 | # pipenv 86 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 87 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 88 | # having no cross-platform support, pipenv may install dependencies that don’t work, or not 89 | # install all needed dependencies. 90 | #Pipfile.lock 91 | 92 | # celery beat schedule file 93 | celerybeat-schedule 94 | 95 | # SageMath parsed files 96 | *.sage.py 97 | 98 | # Environments 99 | .env 100 | .venv 101 | env/ 102 | venv/ 103 | ENV/ 104 | env.bak/ 105 | venv.bak/ 106 | 107 | # Spyder project settings 108 | .spyderproject 109 | .spyproject 110 | 111 | # Rope project settings 112 | .ropeproject 113 | 114 | # mkdocs documentation 115 | /site 116 | 117 | # mypy 118 | .mypy_cache/ 119 | .dmypy.json 120 | dmypy.json 121 | 122 | # Pyre type checker 123 | .pyre/ 124 | 125 | # Azure Functions artifacts 126 | bin 127 | obj 128 | appsettings.json 129 | 130 | # Azurite artifacts 131 | __blobstorage__ 132 | __queuestorage__ 133 | __azurite_db*__.json 134 | .python_packages -------------------------------------------------------------------------------- /sk-python-azure-functions-chatgpt-plugin/.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "ms-azuretools.vscode-azurefunctions", 4 | "ms-python.python", 5 | "azurite.azurite", 6 | "ms-semantic-kernel.semantic-kernel", 7 | ] 8 | } -------------------------------------------------------------------------------- /sk-python-azure-functions-chatgpt-plugin/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "Attach to Python Functions", 6 | "type": "python", 7 | "request": "attach", 8 | "port": 9091, 9 | "preLaunchTask": "func: host start" 10 | } 11 | ] 12 | } -------------------------------------------------------------------------------- /sk-python-azure-functions-chatgpt-plugin/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "azureFunctions.deploySubpath": ".", 3 | "azureFunctions.scmDoBuildDuringDeployment": true, 4 | "azureFunctions.pythonVenv": ".venv", 5 | "azureFunctions.projectLanguage": "Python", 6 | "azureFunctions.projectRuntime": "~4", 7 | "debug.internalConsoleOptions": "neverOpen", 8 | "azureFunctions.projectLanguageModel": 2 9 | } -------------------------------------------------------------------------------- /sk-python-azure-functions-chatgpt-plugin/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "type": "func", 6 | "label": "func: host start", 7 | "command": "host start", 8 | "problemMatcher": "$func-python-watch", 9 | "isBackground": true, 10 | "dependsOn": "pip install (functions)" 11 | }, 12 | { 13 | "label": "create venv", 14 | "type": "shell", 15 | "command": "python -m venv .venv || echo 0", 16 | "group": { 17 | "kind": "build", 18 | "isDefault": true 19 | } 20 | }, 21 | { 22 | "label": "pip install (functions)", 23 | "type": "shell", 24 | "osx": { 25 | "command": "${config:azureFunctions.pythonVenv}/bin/python -m pip install -r requirements.txt" 26 | }, 27 | "windows": { 28 | "command": "${config:azureFunctions.pythonVenv}\\Scripts\\python -m pip install -r requirements.txt" 29 | }, 30 | "linux": { 31 | "command": "${config:azureFunctions.pythonVenv}/bin/python -m pip install -r requirements.txt" 32 | }, 33 | "problemMatcher": [], 34 | "dependsOn": "create venv" 35 | } 36 | ] 37 | } -------------------------------------------------------------------------------- /sk-python-azure-functions-chatgpt-plugin/.well-known/ai-plugin.json: -------------------------------------------------------------------------------- 1 | { 2 | "schema_version": "v1", 3 | "name_for_human": "Fun Plugin", 4 | "name_for_model": "FunPlugin", 5 | "description_for_human": "Execute fun skills such as jokes, excuses and limericks.", 6 | "description_for_model": "A plugin for using semantic kernel fun skills.", 7 | "auth": { 8 | "type": "none" 9 | }, 10 | "api": { 11 | "type": "openapi", 12 | "url": "http://localhost:7071/openapi.yaml" 13 | }, 14 | "logo_url": "http://localhost:7071/logo.png", 15 | "contact_email": "legal@example.com", 16 | "legal_info_url": "http://example.com/legal" 17 | } -------------------------------------------------------------------------------- /sk-python-azure-functions-chatgpt-plugin/README.md: -------------------------------------------------------------------------------- 1 | # Semantic Kernel Python Azure Functions Starter 2 | 3 | The `sk-python-azure-functions` application demonstrates how to execute a semantic function within an Azure Function. 4 | 5 | ## Prerequisites 6 | 7 | - [Python](https://www.python.org/downloads/) >=3.8 and <3.11 8 | - [Azure Functions](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azurefunctions) 9 | - [Azurite](https://marketplace.visualstudio.com/items?itemName=Azurite.azurite). Run the services from the VS Code status bar. 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 with a `.env` file in the project which holds api keys and other secrets and configurations. 15 | 16 | Make sure you have an 17 | [Open AI API Key](https://openai.com/api/) or 18 | [Azure Open AI service key](https://learn.microsoft.com/azure/cognitive-services/openai/quickstart?pivots=rest-api) 19 | 20 | Copy the `.env.example` file to a new file named `.env`. Then, copy those keys into the `.env` file: 21 | 22 | ``` 23 | OPENAI_API_KEY="" 24 | OPENAI_ORG_ID="" 25 | AZURE_OPENAI_DEPLOYMENT_NAME="" 26 | AZURE_OPENAI_ENDPOINT="" 27 | AZURE_OPENAI_API_KEY="" 28 | ``` 29 | 30 | ## Running the starter 31 | 32 | To run the console application within Visual Studio Code, run Azurite from the status bar or command pallette, then just hit `F5`. 33 | As configured in `launch.json` and `tasks.json`, Visual Studio Code will create a virtual environment at `.venv` and run `pip install requirements.txt`. 34 | 35 | To run from command line, run the following: 36 | 37 | ``` 38 | python -m venv .venv 39 | .venv\Scripts\python -m pip install -r requirements.txt # Location of python within venv depends on OS 40 | .venv\Scripts\activate 41 | func host start 42 | ``` 43 | 44 | ## Using the starter 45 | 46 | In your browser, visit `http://localhost:7071/api/skills/{skill_name/functions/{function_name}` to execute a skill. 47 | For example, `http://localhost:7071/api/skills/FunSkill/functions/Joke` will execute the example Joke function in the FunSkill skill. 48 | 49 | To provide input, send a POST request with a JSON body, e.g. provide this as input to the Joke function: 50 | `{"input": "time traveling to dinosaur age", "style": "deadpan"}` 51 | -------------------------------------------------------------------------------- /sk-python-azure-functions-chatgpt-plugin/host.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0", 3 | "logging": { 4 | "applicationInsights": { 5 | "samplingSettings": { 6 | "isEnabled": true, 7 | "excludedTypes": "Request" 8 | } 9 | } 10 | }, 11 | "extensionBundle": { 12 | "id": "Microsoft.Azure.Functions.ExtensionBundle", 13 | "version": "[4.*, 5.0.0)" 14 | }, 15 | "extensions": { 16 | "http": { 17 | "routePrefix": "" 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /sk-python-azure-functions-chatgpt-plugin/local.settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "IsEncrypted": false, 3 | "Values": { 4 | "FUNCTIONS_WORKER_RUNTIME": "python", 5 | "AzureWebJobsStorage": "UseDevelopmentStorage=true", 6 | "AzureWebJobsFeatureFlags": "EnableWorkerIndexing" 7 | } 8 | } -------------------------------------------------------------------------------- /sk-python-azure-functions-chatgpt-plugin/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/semantic-kernel-starters/2df40f4c0ca9bd5a4baeefd68e17baaf7bf8e366/sk-python-azure-functions-chatgpt-plugin/logo.png -------------------------------------------------------------------------------- /sk-python-azure-functions-chatgpt-plugin/openapi.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.1.0 2 | info: 3 | title: Semantic Kernel Plugin 4 | description: A plugin that allows the user to call Semantic Kernel Functions. 5 | version: 'v1' 6 | servers: 7 | - url: http://localhost:7071 8 | paths: 9 | /skills/FunSkill/functions/Joke: 10 | post: 11 | operationId: executeJokeFunction 12 | description: | 13 | Execute the joke semantic function; submit the input and style as a JSON object in the payload input, e.g. {"input": "", "style": ""} 14 | requestBody: 15 | required: true 16 | content: 17 | application/json: 18 | schema: 19 | $ref: '#/components/schemas/executeJokeFunctionRequest' 20 | responses: 21 | "200": 22 | description: OK 23 | content: 24 | text/plain: 25 | schema: 26 | type: string 27 | /hello: 28 | get: 29 | operationId: hello 30 | description: | 31 | Execute a simple hello native function. 32 | parameters: 33 | - name: name 34 | in: query 35 | description: The name to say hello to. 36 | required: true 37 | schema: 38 | type: string 39 | responses: 40 | "200": 41 | description: OK 42 | content: 43 | text/plain: 44 | schema: 45 | type: string 46 | components: 47 | schemas: 48 | executeJokeFunctionRequest: 49 | type: object 50 | properties: 51 | input: 52 | type: string 53 | style: 54 | type: string 55 | required: 56 | - input -------------------------------------------------------------------------------- /sk-python-azure-functions-chatgpt-plugin/requirements.txt: -------------------------------------------------------------------------------- 1 | # DO NOT include azure-functions-worker in this file 2 | # The Python Worker is managed by Azure Functions platform 3 | # Manually managing azure-functions-worker may cause unexpected issues 4 | 5 | azure-functions 6 | semantic-kernel -------------------------------------------------------------------------------- /sk-python-azure-functions-chatgpt-plugin/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-python-azure-functions-chatgpt-plugin/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-python-azure-functions-chatgpt-plugin/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-python-azure-functions-chatgpt-plugin/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 | WRITE THE JOKE IN THE STYLE PROVIDED 10 | +++++ 11 | STYLE: 12 | {{$style}} 13 | +++++ 14 | TOPIC: 15 | {{$input}} 16 | +++++ 17 | -------------------------------------------------------------------------------- /sk-python-azure-functions-chatgpt-plugin/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-python-azure-functions-chatgpt-plugin/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-python-azure-functions/.env.example: -------------------------------------------------------------------------------- 1 | OPENAI_API_KEY="" 2 | OPENAI_ORG_ID="" 3 | AZURE_OPENAI_DEPLOYMENT_NAME="" 4 | AZURE_OPENAI_ENDPOINT="" 5 | AZURE_OPENAI_API_KEY="" 6 | -------------------------------------------------------------------------------- /sk-python-azure-functions/.funcignore: -------------------------------------------------------------------------------- 1 | .git* 2 | .vscode 3 | __azurite_db*__.json 4 | __blobstorage__ 5 | __queuestorage__ 6 | local.settings.json 7 | test 8 | .venv -------------------------------------------------------------------------------- /sk-python-azure-functions/.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | 53 | # Translations 54 | *.mo 55 | *.pot 56 | 57 | # Django stuff: 58 | *.log 59 | local_settings.py 60 | db.sqlite3 61 | 62 | # Flask stuff: 63 | instance/ 64 | .webassets-cache 65 | 66 | # Scrapy stuff: 67 | .scrapy 68 | 69 | # Sphinx documentation 70 | docs/_build/ 71 | 72 | # PyBuilder 73 | target/ 74 | 75 | # Jupyter Notebook 76 | .ipynb_checkpoints 77 | 78 | # IPython 79 | profile_default/ 80 | ipython_config.py 81 | 82 | # pyenv 83 | .python-version 84 | 85 | # pipenv 86 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 87 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 88 | # having no cross-platform support, pipenv may install dependencies that don’t work, or not 89 | # install all needed dependencies. 90 | #Pipfile.lock 91 | 92 | # celery beat schedule file 93 | celerybeat-schedule 94 | 95 | # SageMath parsed files 96 | *.sage.py 97 | 98 | # Environments 99 | .env 100 | .venv 101 | env/ 102 | venv/ 103 | ENV/ 104 | env.bak/ 105 | venv.bak/ 106 | 107 | # Spyder project settings 108 | .spyderproject 109 | .spyproject 110 | 111 | # Rope project settings 112 | .ropeproject 113 | 114 | # mkdocs documentation 115 | /site 116 | 117 | # mypy 118 | .mypy_cache/ 119 | .dmypy.json 120 | dmypy.json 121 | 122 | # Pyre type checker 123 | .pyre/ 124 | 125 | # Azure Functions artifacts 126 | bin 127 | obj 128 | appsettings.json 129 | 130 | # Azurite artifacts 131 | __blobstorage__ 132 | __queuestorage__ 133 | __azurite_db*__.json 134 | .python_packages -------------------------------------------------------------------------------- /sk-python-azure-functions/.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "ms-azuretools.vscode-azurefunctions", 4 | "ms-python.python", 5 | "azurite.azurite", 6 | "ms-semantic-kernel.semantic-kernel", 7 | ] 8 | } -------------------------------------------------------------------------------- /sk-python-azure-functions/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "Attach to Python Functions", 6 | "type": "python", 7 | "request": "attach", 8 | "port": 9091, 9 | "preLaunchTask": "func: host start" 10 | } 11 | ] 12 | } -------------------------------------------------------------------------------- /sk-python-azure-functions/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "azureFunctions.deploySubpath": ".", 3 | "azureFunctions.scmDoBuildDuringDeployment": true, 4 | "azureFunctions.pythonVenv": ".venv", 5 | "azureFunctions.projectLanguage": "Python", 6 | "azureFunctions.projectRuntime": "~4", 7 | "debug.internalConsoleOptions": "neverOpen", 8 | "azureFunctions.projectLanguageModel": 2 9 | } -------------------------------------------------------------------------------- /sk-python-azure-functions/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "type": "func", 6 | "label": "func: host start", 7 | "command": "host start", 8 | "problemMatcher": "$func-python-watch", 9 | "isBackground": true, 10 | "dependsOn": "pip install (functions)" 11 | }, 12 | { 13 | "label": "create venv", 14 | "type": "shell", 15 | "command": "python -m venv .venv || echo 0", 16 | "group": { 17 | "kind": "build", 18 | "isDefault": true 19 | } 20 | }, 21 | { 22 | "label": "pip install (functions)", 23 | "type": "shell", 24 | "osx": { 25 | "command": "${config:azureFunctions.pythonVenv}/bin/python -m pip install -r requirements.txt" 26 | }, 27 | "windows": { 28 | "command": "${config:azureFunctions.pythonVenv}\\Scripts\\python -m pip install -r requirements.txt" 29 | }, 30 | "linux": { 31 | "command": "${config:azureFunctions.pythonVenv}/bin/python -m pip install -r requirements.txt" 32 | }, 33 | "problemMatcher": [], 34 | "dependsOn": "create venv" 35 | } 36 | ] 37 | } -------------------------------------------------------------------------------- /sk-python-azure-functions/README.md: -------------------------------------------------------------------------------- 1 | # Semantic Kernel Python Azure Functions Starter 2 | 3 | The `sk-python-azure-functions` application demonstrates how to execute a semantic function within an Azure Function. 4 | 5 | ## Prerequisites 6 | 7 | - [Python](https://www.python.org/downloads/) >=3.8 and <3.11 8 | - [Azure Functions](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azurefunctions) 9 | - [Azurite](https://marketplace.visualstudio.com/items?itemName=Azurite.azurite). Run the services from the VS Code status bar. 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 with a `.env` file in the project which holds api keys and other secrets and configurations. 15 | 16 | Make sure you have an 17 | [Open AI API Key](https://openai.com/api/) or 18 | [Azure Open AI service key](https://learn.microsoft.com/azure/cognitive-services/openai/quickstart?pivots=rest-api) 19 | 20 | Copy the `.env.example` file to a new file named `.env`. Then, copy those keys into the `.env` file: 21 | 22 | ``` 23 | OPENAI_API_KEY="" 24 | OPENAI_ORG_ID="" 25 | AZURE_OPENAI_DEPLOYMENT_NAME="" 26 | AZURE_OPENAI_ENDPOINT="" 27 | AZURE_OPENAI_API_KEY="" 28 | ``` 29 | 30 | ## Running the starter 31 | 32 | To run the console application within Visual Studio Code, run Azurite from the status bar or command pallette, then just hit `F5`. 33 | As configured in `launch.json` and `tasks.json`, Visual Studio Code will create a virtual environment at `.venv` and run `pip install requirements.txt`. 34 | 35 | To run from command line, run the following: 36 | 37 | ``` 38 | python -m venv .venv 39 | .venv\Scripts\python -m pip install -r requirements.txt # Location of python within venv depends on OS 40 | .venv\Scripts\activate 41 | func host start 42 | ``` 43 | 44 | ## Using the starter 45 | 46 | In your browser, visit `http://localhost:7071/api/skills/{skill_name/functions/{function_name}` to execute a skill. 47 | For example, `http://localhost:7071/api/skills/FunSkill/functions/Joke` will execute the example Joke function in the FunSkill skill. 48 | 49 | To provide input, send a POST request with a JSON body, e.g. provide this as input to the Joke function: 50 | `{"input": "time traveling to dinosaur age", "style": "deadpan"}` 51 | -------------------------------------------------------------------------------- /sk-python-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 | "extensionBundle": { 12 | "id": "Microsoft.Azure.Functions.ExtensionBundle", 13 | "version": "[4.*, 5.0.0)" 14 | } 15 | } -------------------------------------------------------------------------------- /sk-python-azure-functions/local.settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "IsEncrypted": false, 3 | "Values": { 4 | "FUNCTIONS_WORKER_RUNTIME": "python", 5 | "AzureWebJobsStorage": "UseDevelopmentStorage=true", 6 | "AzureWebJobsFeatureFlags": "EnableWorkerIndexing" 7 | } 8 | } -------------------------------------------------------------------------------- /sk-python-azure-functions/requirements.txt: -------------------------------------------------------------------------------- 1 | # DO NOT include azure-functions-worker in this file 2 | # The Python Worker is managed by Azure Functions platform 3 | # Manually managing azure-functions-worker may cause unexpected issues 4 | 5 | azure-functions 6 | semantic-kernel -------------------------------------------------------------------------------- /sk-python-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, 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-python-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-python-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, 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-python-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 | WRITE THE JOKE IN THE STYLE PROVIDED 10 | +++++ 11 | STYLE: 12 | {{$style}} 13 | +++++ 14 | TOPIC: 15 | {{$input}} 16 | +++++ 17 | -------------------------------------------------------------------------------- /sk-python-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, 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-python-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 about their life. Must be funny. 28 | -------------------------------------------------------------------------------- /sk-python-flask-chatgpt-plugin/.env.example: -------------------------------------------------------------------------------- 1 | OPENAI_API_KEY="" 2 | OPENAI_ORG_ID="" 3 | AZURE_OPENAI_DEPLOYMENT_NAME="" 4 | AZURE_OPENAI_ENDPOINT="" 5 | AZURE_OPENAI_API_KEY="" 6 | -------------------------------------------------------------------------------- /sk-python-flask-chatgpt-plugin/.gitignore: -------------------------------------------------------------------------------- 1 | .env 2 | .venv -------------------------------------------------------------------------------- /sk-python-flask-chatgpt-plugin/.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "ms-python.python", 4 | "ms-semantic-kernel.semantic-kernel" 5 | ] 6 | } -------------------------------------------------------------------------------- /sk-python-flask-chatgpt-plugin/.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 | // launch flask 8 | { 9 | "name": "Python: Flask", 10 | "type": "python", 11 | "request": "launch", 12 | "module": "flask", 13 | "env": { 14 | "FLASK_APP": "sk_python_flask_chatgpt_plugin/app.py", 15 | "FLASK_DEBUG": "1" 16 | }, 17 | "args": [ 18 | "run", 19 | "-p 5050" 20 | ], 21 | "jinja": true, 22 | "justMyCode": true, 23 | "preLaunchTask": "install" 24 | } 25 | ] 26 | } -------------------------------------------------------------------------------- /sk-python-flask-chatgpt-plugin/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.analysis.extraPaths": [ 3 | "./src" 4 | ], 5 | "explorer.compactFolders": false, 6 | "editor.formatOnType": true, 7 | "editor.formatOnSave": true, 8 | "editor.formatOnPaste": true, 9 | "python.formatting.provider": "black", 10 | "python.formatting.autopep8Args": [ 11 | "--max-line-length=160" 12 | ] 13 | } -------------------------------------------------------------------------------- /sk-python-flask-chatgpt-plugin/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | // Create a task to run poetry install 2 | { 3 | "version": "2.0.0", 4 | "tasks": [ 5 | { 6 | "label": "install", 7 | "type": "shell", 8 | "command": "poetry", 9 | "args": [ 10 | "install" 11 | ], 12 | "group": { 13 | "kind": "build", 14 | "isDefault": true 15 | } 16 | } 17 | ] 18 | } -------------------------------------------------------------------------------- /sk-python-flask-chatgpt-plugin/.well-known/ai-plugin.json: -------------------------------------------------------------------------------- 1 | { 2 | "schema_version": "v1", 3 | "name_for_human": "SemanticKernel", 4 | "name_for_model": "SemanticKernel", 5 | "description_for_human": "Make requests to use semantic kernel functions.", 6 | "description_for_model": "Plugin for using the semantic kernel functions.", 7 | "auth": { 8 | "type": "none" 9 | }, 10 | "api": { 11 | "type": "openapi", 12 | "url": "http://localhost:5050/openapi.yaml" 13 | }, 14 | "logo_url": "http://localhost:5050/logo.png", 15 | "contact_email": "legal@example.com", 16 | "legal_info_url": "http://example.com/legal" 17 | } -------------------------------------------------------------------------------- /sk-python-flask-chatgpt-plugin/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/semantic-kernel-starters/2df40f4c0ca9bd5a4baeefd68e17baaf7bf8e366/sk-python-flask-chatgpt-plugin/logo.png -------------------------------------------------------------------------------- /sk-python-flask-chatgpt-plugin/openapi.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.1.0 2 | info: 3 | title: Semantic Kernel Plugin 4 | description: A plugin that allows the user to call Semantic Kernel Functions. 5 | version: 'v1' 6 | servers: 7 | - url: http://localhost:5050 8 | paths: 9 | /skills/FunSkill/functions/Joke: 10 | post: 11 | operationId: executeJokeFunction 12 | description: | 13 | Execute the joke semantic function; submit the input and style as a JSON object in the payload input, e.g. {"input": "", "style": ""} 14 | requestBody: 15 | required: True 16 | content: 17 | application/json: 18 | schema: 19 | $ref: '#/components/schemas/executeJokeFunctionRequest' 20 | responses: 21 | "200": 22 | description: OK 23 | content: 24 | text/plain: 25 | schema: 26 | type: string 27 | components: 28 | schemas: 29 | executeJokeFunctionRequest: 30 | type: object 31 | properties: 32 | input: 33 | type: string 34 | style: 35 | type: string 36 | required: 37 | - input 38 | -------------------------------------------------------------------------------- /sk-python-flask-chatgpt-plugin/pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "sk-python-flask-chatgpt-plugin" 3 | version = "0.1.0" 4 | description = "A starter application using the semantic kernel in a Flask backend that can be imported as a ChatGPT plugin" 5 | authors = ["Microsoft "] 6 | readme = "README.md" 7 | packages = [{include = "sk_python_flask_chatgpt_plugin"}] 8 | 9 | [tool.poetry.dependencies] 10 | python = "^3.8" 11 | semantic-kernel = "^0.3.4.dev0" 12 | flask = "^2.3.2" 13 | flask-cors = "^4.0.0" 14 | 15 | [tool.poetry.group.dev.dependencies] 16 | black = "^23.3.0" 17 | ruff = "0.0.275" 18 | 19 | [build-system] 20 | requires = ["poetry-core"] 21 | build-backend = "poetry.core.masonry.api" 22 | -------------------------------------------------------------------------------- /sk-python-flask-chatgpt-plugin/sk_python_flask_chatgpt_plugin/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/semantic-kernel-starters/2df40f4c0ca9bd5a4baeefd68e17baaf7bf8e366/sk-python-flask-chatgpt-plugin/sk_python_flask_chatgpt_plugin/__init__.py -------------------------------------------------------------------------------- /sk-python-flask-chatgpt-plugin/sk_python_flask_chatgpt_plugin/app.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from flask import Flask, request, Response, send_file 3 | from flask_cors import CORS 4 | from semantic_kernel.kernel_exception import KernelException 5 | 6 | from sk_python_flask_chatgpt_plugin.kernel_utils import ( 7 | create_kernel_for_request, 8 | create_context_variables_from_request, 9 | ) 10 | 11 | 12 | app = Flask(__name__) 13 | CORS(app) 14 | 15 | 16 | @app.route("/skills//functions/", methods=["POST"]) 17 | def execute_semantic_function(skill_name, function_name): 18 | logging.info( 19 | f"Received request for skill {skill_name} and function {function_name}" 20 | ) 21 | 22 | kernel, error = create_kernel_for_request(request.headers, skill_name) 23 | if error: 24 | return error 25 | try: 26 | sk_func = kernel.skills.get_function(skill_name, function_name) 27 | except KernelException: 28 | logging.exception( 29 | f"Could not find function {function_name} in skill {skill_name}" 30 | ) 31 | return f"Could not find function {function_name} in skill {skill_name}", 404 32 | 33 | context_variables = create_context_variables_from_request(request) 34 | 35 | result = sk_func(variables=context_variables) 36 | 37 | logging.info(f"Result: {result}") 38 | return str(result) 39 | 40 | @app.route("/joke", methods=["POST"]) 41 | def execute_joke(): 42 | return execute_semantic_function("FunSkill", "Joke") 43 | 44 | @app.route("/.well-known/ai-plugin.json", methods=["GET"]) 45 | def get_ai_plugin(): 46 | with open("./.well-known/ai-plugin.json", "r") as f: 47 | text = f.read() 48 | return Response(text, status=200, mimetype="text/json") 49 | 50 | 51 | @app.route("/logo.png") 52 | def get_logo(): 53 | return send_file("../logo.png", mimetype="image/png") 54 | 55 | 56 | @app.route("/openapi.yaml", methods=["GET"]) 57 | def get_openapi(): 58 | with open("./openapi.yaml", "r") as f: 59 | text = f.read() 60 | return Response(text, status=200, mimetype="text/yaml") 61 | -------------------------------------------------------------------------------- /sk-python-flask-chatgpt-plugin/sk_python_flask_chatgpt_plugin/config.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | 3 | from enum import Enum 4 | 5 | import semantic_kernel as sk 6 | 7 | DEFAULT_OPENAI_MODEL = "text-davinci-003" 8 | 9 | 10 | class AIService(Enum): 11 | AZURE_OPENAI = "AZURE_OPENAI" 12 | OPENAI = "OPENAI" 13 | 14 | 15 | class SKHttpHeaders(Enum): 16 | COMPLETION_MODEL = "x-ms-sk-completion-model" 17 | COMPLETION_ENDPOINT = "x-ms-sk-completion-endpoint" 18 | COMPLETION_SERVICE = "x-ms-sk-completion-backend" 19 | COMPLETION_KEY = "x-ms-sk-completion-key" 20 | 21 | 22 | @dataclass 23 | class AIServiceConfig: 24 | deployment_model_id: str 25 | endpoint: str 26 | key: str 27 | serviceid: str 28 | org_id: str = None 29 | 30 | 31 | def headers_to_config(headers: dict) -> AIServiceConfig: 32 | if SKHttpHeaders.COMPLETION_MODEL.value in headers: 33 | return AIServiceConfig( 34 | deployment_model_id=headers[SKHttpHeaders.COMPLETION_MODEL.value], 35 | endpoint=headers[SKHttpHeaders.COMPLETION_ENDPOINT.value], 36 | key=headers[SKHttpHeaders.COMPLETION_KEY.value], 37 | serviceid=headers[SKHttpHeaders.COMPLETION_SERVICE.value], 38 | ) 39 | raise ValueError("No valid headers found") 40 | 41 | 42 | def dotenv_to_config(use_azure_openai=True): 43 | if use_azure_openai: 44 | deployment_model_id, api_key, endpoint = sk.azure_openai_settings_from_dot_env() 45 | return AIServiceConfig( 46 | deployment_model_id=deployment_model_id, 47 | endpoint=endpoint, 48 | key=api_key, 49 | serviceid=AIService.AZURE_OPENAI.value, 50 | ) 51 | else: 52 | api_key, org_id = sk.openai_settings_from_dot_env() 53 | return AIServiceConfig( 54 | deployment_model_id=DEFAULT_OPENAI_MODEL, 55 | endpoint=None, 56 | key=api_key, 57 | serviceid=AIService.OPENAI.value, 58 | org_id=org_id, 59 | ) 60 | -------------------------------------------------------------------------------- /sk-python-flask-chatgpt-plugin/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-python-flask-chatgpt-plugin/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-python-flask-chatgpt-plugin/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-python-flask-chatgpt-plugin/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-python-flask-chatgpt-plugin/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-python-flask-chatgpt-plugin/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-python-hello-world/.env.example: -------------------------------------------------------------------------------- 1 | OPENAI_API_KEY="" 2 | OPENAI_ORG_ID="" 3 | AZURE_OPENAI_DEPLOYMENT_NAME="" 4 | AZURE_OPENAI_ENDPOINT="" 5 | AZURE_OPENAI_API_KEY="" 6 | -------------------------------------------------------------------------------- /sk-python-hello-world/.gitignore: -------------------------------------------------------------------------------- 1 | .env 2 | .venv -------------------------------------------------------------------------------- /sk-python-hello-world/.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "ms-python.python", 4 | "ms-semantic-kernel.semantic-kernel" 5 | ] 6 | } -------------------------------------------------------------------------------- /sk-python-hello-world/.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": "Python: Current File", 9 | "type": "python", 10 | "request": "launch", 11 | "cwd": "${workspaceFolder}", 12 | "program": "hello_world/main.py", // or ${file} for the current file 13 | "console": "integratedTerminal", 14 | "justMyCode": true, 15 | "preLaunchTask": "install" 16 | } 17 | ] 18 | } -------------------------------------------------------------------------------- /sk-python-hello-world/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.analysis.extraPaths": [ 3 | "./src" 4 | ], 5 | "explorer.compactFolders": false, 6 | "editor.formatOnType": true, 7 | "editor.formatOnSave": true, 8 | "editor.formatOnPaste": true, 9 | "python.formatting.provider": "black", 10 | "python.formatting.autopep8Args": [ 11 | "--max-line-length=160" 12 | ] 13 | } -------------------------------------------------------------------------------- /sk-python-hello-world/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | // Create a task to run poetry install 2 | { 3 | "version": "2.0.0", 4 | "tasks": [ 5 | { 6 | "label": "install", 7 | "type": "shell", 8 | "command": "poetry", 9 | "args": [ 10 | "install" 11 | ], 12 | "group": { 13 | "kind": "build", 14 | "isDefault": true 15 | } 16 | } 17 | ] 18 | } -------------------------------------------------------------------------------- /sk-python-hello-world/README.md: -------------------------------------------------------------------------------- 1 | # Semantic Kernel Python Hello World Starter 2 | 3 | The `sk-python-hello-world` console application demonstrates how to execute a semantic function. 4 | 5 | ## Prerequisites 6 | 7 | - [Python](https://www.python.org/downloads/) 3.8 and above 8 | - [Poetry](https://python-poetry.org/) is used for packaging and dependency management 9 | - [Semantic Kernel Tools](https://marketplace.visualstudio.com/items?itemName=ms-semantic-kernel.semantic-kernel) 10 | 11 | ## Configuring the starter 12 | 13 | The starter can be configured with a `.env` file in the project which holds api keys and other secrets and configurations. 14 | 15 | Make sure you have an 16 | [Open AI API Key](https://openai.com/api/) or 17 | [Azure Open AI service key](https://learn.microsoft.com/azure/cognitive-services/openai/quickstart?pivots=rest-api) 18 | 19 | Copy the `.env.example` file to a new file named `.env`. Then, copy those keys into the `.env` file: 20 | 21 | ``` 22 | OPENAI_API_KEY="" 23 | OPENAI_ORG_ID="" 24 | AZURE_OPENAI_DEPLOYMENT_NAME="" 25 | AZURE_OPENAI_ENDPOINT="" 26 | AZURE_OPENAI_API_KEY="" 27 | ``` 28 | 29 | ## Running the starter 30 | 31 | To run the console application within Visual Studio Code, just hit `F5`. 32 | As configured in `launch.json` and `tasks.json`, Visual Studio Code will run `poetry install` followed by `python hello_world/main.py` 33 | 34 | To build and run the console application from the terminal use the following commands: 35 | 36 | ```powershell 37 | poetry install 38 | poetry run python hello_world/main.py 39 | ``` 40 | -------------------------------------------------------------------------------- /sk-python-hello-world/hello_world/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/semantic-kernel-starters/2df40f4c0ca9bd5a4baeefd68e17baaf7bf8e366/sk-python-hello-world/hello_world/__init__.py -------------------------------------------------------------------------------- /sk-python-hello-world/hello_world/main.py: -------------------------------------------------------------------------------- 1 | import semantic_kernel as sk 2 | from semantic_kernel.connectors.ai.open_ai import ( 3 | AzureTextCompletion, 4 | OpenAITextCompletion, 5 | ) 6 | from semantic_kernel.orchestration.context_variables import ContextVariables 7 | 8 | useAzureOpenAI = False 9 | 10 | 11 | def main(): 12 | kernel = sk.Kernel() 13 | 14 | # Configure AI service used by the kernel. Load settings from the .env file. 15 | if useAzureOpenAI: 16 | deployment, api_key, endpoint = sk.azure_openai_settings_from_dot_env() 17 | kernel.add_text_completion_service( 18 | "dv", AzureTextCompletion(deployment, endpoint, api_key) 19 | ) 20 | else: 21 | api_key, org_id = sk.openai_settings_from_dot_env() 22 | kernel.add_text_completion_service( 23 | "dv", OpenAITextCompletion("text-davinci-003", api_key, org_id) 24 | ) 25 | 26 | skills_directory = "skills" 27 | 28 | fun_skill = kernel.import_semantic_skill_from_directory( 29 | skills_directory, "FunSkill" 30 | ) 31 | 32 | joke_function = fun_skill["Joke"] 33 | 34 | # The "input" variable in the prompt is set by "content" in the ContextVariables object. 35 | context_variables = ContextVariables( 36 | content="time travel to dinosaur age", variables={"style": "standup comedy"} 37 | ) 38 | result = joke_function(variables=context_variables) 39 | 40 | print(result) 41 | 42 | # You can also invoke functions like this 43 | # result = await jokeFunction.invoke_async("time travel to dinosaur age") 44 | # print(result) 45 | 46 | 47 | if __name__ == "__main__": 48 | main() 49 | -------------------------------------------------------------------------------- /sk-python-hello-world/pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "sk-python-hello-world" 3 | version = "0.1.0" 4 | description = "A starter application using the semantic kernel" 5 | authors = ["Microsoft "] 6 | readme = "README.md" 7 | packages = [{include = "hello_world"}] 8 | 9 | [tool.poetry.dependencies] 10 | python = "^3.8" 11 | semantic-kernel = "^0.2.7.dev0" 12 | 13 | [tool.poetry.group.dev.dependencies] 14 | black = "^23.3.0" 15 | 16 | [build-system] 17 | requires = ["poetry-core"] 18 | build-backend = "poetry.core.masonry.api" 19 | -------------------------------------------------------------------------------- /sk-python-hello-world/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-python-hello-world/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-python-hello-world/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-python-hello-world/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-python-hello-world/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-python-hello-world/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-typescript-console-chat/.eslintrc.json: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | { 5 | "parser": "@typescript-eslint/parser", 6 | "parserOptions": { 7 | "ecmaVersion": "latest", 8 | "sourceType": "module" 9 | }, 10 | "plugins": [ "@typescript-eslint" ], 11 | "root": true, 12 | "rules": { 13 | // Add rules here 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /sk-typescript-console-chat/.gitignore: -------------------------------------------------------------------------------- 1 | **/bin 2 | **/obj 3 | **/pkg 4 | *.js 5 | *.map -------------------------------------------------------------------------------- /sk-typescript-console-chat/consoleChat.ts: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | import "./bin/Microsoft.SemanticKernel.Core.js"; 5 | import "./bin/Microsoft.SemanticKernel.Connectors.AI.OpenAI.js"; 6 | import dotnet from "node-api-dotnet"; 7 | import readline from "node:readline"; 8 | import { consoleColours } from "./consoleColours.js"; 9 | 10 | const SK = dotnet.Microsoft.SemanticKernel; 11 | 12 | // The JS marshaller does not yet support extension methods. 13 | const kernelBuilder = SK.OpenAIKernelBuilderExtensions.WithAzureChatCompletionService( 14 | SK.Kernel.Builder, 15 | process.env['OPENAI_DEPLOYMENT'] || '', 16 | process.env['OPENAI_ENDPOINT'] || '', 17 | process.env['OPENAI_KEY'] || '', 18 | ); 19 | 20 | const kernel = kernelBuilder 21 | .Build(); 22 | 23 | const r1 = readline.createInterface({ 24 | input: process.stdin, 25 | output: process.stdout, 26 | prompt: 'SK> Hello. Ask me a question or say goodbye to exit.' 27 | }); 28 | 29 | let chatHistory: string[] = []; 30 | 31 | r1.prompt(); 32 | console.log(""); 33 | r1.on('line', async (userInput: string) => { 34 | if (userInput.toLowerCase() === 'goodbye') { 35 | console.log('SK> Goodbye!'); 36 | process.exit(0); 37 | } else { 38 | chatHistory.push(userInput); 39 | // The JS marshaller does not yet support extension methods. 40 | const chatFunction = SK.InlineFunctionsDefinitionExtension 41 | .CreateSemanticFunction(kernel, chatHistory.join("")); 42 | 43 | const reply = await kernel.RunAsync("", [chatFunction]); 44 | 45 | chatHistory.push(`${reply}`); 46 | console.log(consoleColours.green, `Answer> ${reply}`); 47 | console.log(consoleColours.white, `SK> Ask me another question or say goodbye to exit.`); 48 | } 49 | }).on('close', () => { 50 | console.log(consoleColours.white, 'SK> Goodbye!'); 51 | process.exit(0); 52 | }); 53 | -------------------------------------------------------------------------------- /sk-typescript-console-chat/consoleColours.ts: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | export const consoleColours = { 5 | green: "\x1b[32m", 6 | white: "\x1b[37m", 7 | }; 8 | -------------------------------------------------------------------------------- /sk-typescript-console-chat/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "sk-typescript-console-chat", 3 | "lockfileVersion": 2, 4 | "requires": true, 5 | "packages": { 6 | "": { 7 | "dependencies": { 8 | "node-api-dotnet": "^0.4.4", 9 | "typescript": "^5.2.2" 10 | }, 11 | "devDependencies": { 12 | "@types/node": "^20.6.0" 13 | } 14 | }, 15 | "node_modules/@types/node": { 16 | "version": "20.6.0", 17 | "resolved": "https://registry.npmjs.org/@types/node/-/node-20.6.0.tgz", 18 | "integrity": "sha512-najjVq5KN2vsH2U/xyh2opaSEz6cZMR2SetLIlxlj08nOcmPOemJmUK2o4kUzfLqfrWE0PIrNeE16XhYDd3nqg==", 19 | "dev": true 20 | }, 21 | "node_modules/node-api-dotnet": { 22 | "version": "0.4.4", 23 | "resolved": "https://registry.npmjs.org/node-api-dotnet/-/node-api-dotnet-0.4.4.tgz", 24 | "integrity": "sha512-wrDOZ0xKVtTcXGjT2CCqkLPAdmNJcfw/lXeb43m+WVivLN8hMBvkxtiNNzd5/Fns+RPhnzw1x296Ol8mZcfacg==" 25 | }, 26 | "node_modules/typescript": { 27 | "version": "5.2.2", 28 | "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.2.2.tgz", 29 | "integrity": "sha512-mI4WrpHsbCIcwT9cF4FZvr80QUeKvsUsUvKDoR+X/7XHQH98xYD8YHZg7ANtz2GtZt/CBq2QJ0thkGJMHfqc1w==", 30 | "bin": { 31 | "tsc": "bin/tsc", 32 | "tsserver": "bin/tsserver" 33 | }, 34 | "engines": { 35 | "node": ">=14.17" 36 | } 37 | } 38 | }, 39 | "dependencies": { 40 | "@types/node": { 41 | "version": "20.6.0", 42 | "resolved": "https://registry.npmjs.org/@types/node/-/node-20.6.0.tgz", 43 | "integrity": "sha512-najjVq5KN2vsH2U/xyh2opaSEz6cZMR2SetLIlxlj08nOcmPOemJmUK2o4kUzfLqfrWE0PIrNeE16XhYDd3nqg==", 44 | "dev": true 45 | }, 46 | "node-api-dotnet": { 47 | "version": "0.4.4", 48 | "resolved": "https://registry.npmjs.org/node-api-dotnet/-/node-api-dotnet-0.4.4.tgz", 49 | "integrity": "sha512-wrDOZ0xKVtTcXGjT2CCqkLPAdmNJcfw/lXeb43m+WVivLN8hMBvkxtiNNzd5/Fns+RPhnzw1x296Ol8mZcfacg==" 50 | }, 51 | "typescript": { 52 | "version": "5.2.2", 53 | "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.2.2.tgz", 54 | "integrity": "sha512-mI4WrpHsbCIcwT9cF4FZvr80QUeKvsUsUvKDoR+X/7XHQH98xYD8YHZg7ANtz2GtZt/CBq2QJ0thkGJMHfqc1w==" 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /sk-typescript-console-chat/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "module", 3 | "scripts": { 4 | "build": "tsc --build" 5 | }, 6 | "dependencies": { 7 | "node-api-dotnet": "^0.4.4", 8 | "typescript": "^5.2.2" 9 | }, 10 | "devDependencies": { 11 | "@types/node": "^20.6.0" 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /sk-typescript-console-chat/readme.md: -------------------------------------------------------------------------------- 1 |  2 | ## Example: Using .NET Semantic Kernel to call Azure OpenAI 3 | The `consoleChat.js` script dynamically loads the [`Microsoft.SemanticKernel`](https://github.com/microsoft/semantic-kernel) .NET assembly and uses it 4 | to call Azure OpenAI. 5 | 6 | This application allows you to have a conversation with Azure OpenAI. It will ask you to enter your question 7 | and return the response. You can continue the conversation by entering another question. When finished, type `goodbye` 8 | to end the conversation. 9 | 10 | To run this example, first set the following environment variables, as System variables, referencing your 11 | [Azure OpenAI deployment](https://learn.microsoft.com/en-us/azure/cognitive-services/openai/quickstart): 12 | - `OPENAI_ENDPOINT` 13 | - `OPENAI_DEPLOYMENT` 14 | - `OPENAI_KEY` 15 | 16 | Then run the following commands in sequence: 17 | 18 | | Command | Explanation 19 | |----------------------------------|-------------------------------------------------- 20 | | `dotnet build` | Install [`SemanticKernel`](https://www.nuget.org/packages/Microsoft.SemanticKernel) nuget packages into the project and generate type definitions. 21 | | `npm install` | Install [`node-api-dotnet`](https://www.npmjs.com/package/node-api-dotnet) npm package into the project. 22 | | `npm run build` | Transpile the typescript to javascript. 23 | | `node consoleChat.js` | Run consoleChat JS code that uses the above packages to call the Azure OpenAI service. 24 | -------------------------------------------------------------------------------- /sk-typescript-console-chat/sk-typescript-console-chat.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | bin 6 | esm 7 | true 8 | $(MSBuildThisFileDirectory)/pkg 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /sk-typescript-console-chat/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig to read more about this file */ 4 | /* Language and Environment */ 5 | "target": "es2017", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ 6 | /* Modules */ 7 | "module": "ESNext", /* Specify what module code is generated. */ 8 | "types": [ "node" ], /* Specify type package names to be included without being referenced in a source file. */ 9 | /* Emit */ 10 | "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 11 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ 12 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ 13 | /* Type Checking */ 14 | "strict": true, /* Enable all strict type-checking options. */ 15 | /* Completeness */ 16 | "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 17 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 18 | }, 19 | "exclude": ["./bin/*.d.ts"] // Don't typecheck the type files for the SemanticKernel assemblies because some of the types used are not supported by node-dotnet-api conversion. Specifically the c# record type. 20 | } 21 | -------------------------------------------------------------------------------- /sk_csharp_apim_demo/BearerTokenCredential.cs: -------------------------------------------------------------------------------- 1 | using Azure.Core; 2 | 3 | #pragma warning disable IDE0009 4 | public class BearerTokenCredential : TokenCredential 5 | { 6 | private readonly AccessToken _accessToken; 7 | 8 | // Constructor that takes a Bearer token string and its expiration date 9 | public BearerTokenCredential(AccessToken accessToken) 10 | { 11 | this._accessToken = accessToken; 12 | } 13 | 14 | public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken) 15 | { 16 | return this._accessToken; 17 | } 18 | 19 | public override ValueTask GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken) 20 | { 21 | return new ValueTask(this._accessToken); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /sk_csharp_apim_demo/Program.cs: -------------------------------------------------------------------------------- 1 | using Azure.Core; 2 | using Azure.Identity; 3 | using Microsoft.Extensions.Logging; 4 | using Microsoft.SemanticKernel; 5 | using Microsoft.SemanticKernel.Orchestration; 6 | 7 | string[] scopes = new string[] { "https://cognitiveservices.azure.com/.default" }; 8 | var credential = new InteractiveBrowserCredential(); 9 | var requestContext = new TokenRequestContext(scopes); 10 | var accessToken = await credential.GetTokenAsync(requestContext); 11 | 12 | using ILoggerFactory loggerFactory = LoggerFactory.Create(builder => 13 | { 14 | builder 15 | .SetMinimumLevel(LogLevel.Warning) 16 | .AddConsole() 17 | .AddDebug(); 18 | }); 19 | 20 | var httpClient = new HttpClient(); 21 | httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", ""); 22 | 23 | IKernel kernel = new KernelBuilder() 24 | .WithLogger(loggerFactory.CreateLogger()) 25 | .WithAzureTextCompletionService( 26 | "text-davinci-003", 27 | "https://apim...azure-api.net/", 28 | new BearerTokenCredential(accessToken), 29 | "text-davinci-003", 30 | false, 31 | httpClient 32 | ) 33 | .Build(); 34 | 35 | var skillsDirectory = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "skills"); 36 | var skill = kernel.ImportSemanticSkillFromDirectory(skillsDirectory, "FunSkill"); 37 | 38 | var context = new ContextVariables(); 39 | context.Set("input", "Time travel to dinosaur age"); 40 | context.Set("style", "Wacky"); 41 | 42 | var result = await kernel.RunAsync(context, skill["Joke"]); 43 | 44 | Console.WriteLine(result); 45 | 46 | httpClient.Dispose(); 47 | -------------------------------------------------------------------------------- /sk_csharp_apim_demo/sk_csharp_apim_demo.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | PreserveNewest 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /sk_csharp_apim_demo/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_csharp_apim_demo/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_apim_demo/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_csharp_apim_demo/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_apim_demo/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_csharp_apim_demo/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 | --------------------------------------------------------------------------------