{"id":20765795,"url":"https://github.com/rkrehn/csharpchatgpt","last_synced_at":"2025-12-16T10:58:40.793Z","repository":{"id":195057523,"uuid":"692152571","full_name":"rkrehn/csharpchatgpt","owner":"rkrehn","description":"How to use ChatGPT in C#","archived":false,"fork":false,"pushed_at":"2024-01-17T00:49:28.000Z","size":23,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-11T18:53:57.579Z","etag":null,"topics":["chatgpt","chatgpt-api","chatgpt-app","chatgpt-bot","chatgpt3","csharp","csharp-code","openai","openai-api","openai-chatgpt","tutorial"],"latest_commit_sha":null,"homepage":"https://www.krehnsolutions.com","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"cc0-1.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rkrehn.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-09-15T17:16:40.000Z","updated_at":"2024-01-17T02:48:59.000Z","dependencies_parsed_at":"2024-11-17T23:35:20.362Z","dependency_job_id":null,"html_url":"https://github.com/rkrehn/csharpchatgpt","commit_stats":null,"previous_names":["rkrehn/csharpchatgpt"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/rkrehn/csharpchatgpt","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rkrehn%2Fcsharpchatgpt","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rkrehn%2Fcsharpchatgpt/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rkrehn%2Fcsharpchatgpt/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rkrehn%2Fcsharpchatgpt/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rkrehn","download_url":"https://codeload.github.com/rkrehn/csharpchatgpt/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rkrehn%2Fcsharpchatgpt/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":27735649,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-12-14T02:00:11.348Z","response_time":56,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["chatgpt","chatgpt-api","chatgpt-app","chatgpt-bot","chatgpt3","csharp","csharp-code","openai","openai-api","openai-chatgpt","tutorial"],"created_at":"2024-11-17T11:19:00.299Z","updated_at":"2025-12-16T10:58:40.776Z","avatar_url":"https://github.com/rkrehn.png","language":null,"readme":"# About\nI see there are quite a few NuGet packages for Visual Studio to implement ChatGPT. The reality is that it's a lot easier than people may realize. This guide is designed to teach people how to use it using a basic \"I want one response\". This code is used in my [OutlookGPT](https://github.com/rkrehn/OutlookGPT) plugin.\n\n# Requirements (from NuGet)\n\n* Microsoft.AspNet.WebApi.Client\n* System.Text.Json\n* Newtonsoft.Json (not required, but recommended)\n\n# Setup\n\n1. First add the following lines at the top of your project where declare 'using\":\n\n```C\nusing System.Net.Http;\nusing System.Net;\nusing System.Text;\nusing Newtonsoft.Json;\n```\n\n2. Declare your API key (insert your [OpenAI API key](https://platform.openai.com/account/api-keys) in the quotes)\n\n```C\nstring apiKey = \"[api key]\";\n```\n\n# Calling the Chat\n\nSetting the TLS to 1.2 will ensure a secure connection. The next part is calling the API from the Chat Completions. Finally, we'll create the client and add a header with your API key from above.\n\n```C\nServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;\nstring requestUrl = $\"https://api.openai.com/v1/chat/completions\";\nHttpClient client = new HttpClient();\nclient.DefaultRequestHeaders.Add(\"Authorization\", $\"Bearer {apikey}\");\n```\n\n# Setting up the request\n\nThe following code creates the JSON request to OpenAI. You can review all the options you can include here: [https://platform.openai.com/docs/api-reference/chat/create](https://platform.openai.com/docs/api-reference/chat/create).\n\nIt's worth noting that only the \"model\" and the \"messages\" are required in the body. There are [many models](https://platform.openai.com/docs/models), but I'm using **gpt-3.5-turbo** in this example. Likewise, there are a few roles you can use such as system, user, assistance, or function. Typically, the **system** role defines what you want to accomplish. In our example, we'll tell ChatGPT **sytem** role that is acting as a travel agent (used on my [ReisPlan](https://www.reisplan.net) site).\n\nI'm using max_tokens at 1024 to prevent a high cost. The **gpt-3.5-turbo** model can only support 4,096 tokens. I also use a [temperature](https://platform.openai.com/docs/guides/gpt/how-should-i-set-the-temperature-parameter) of 0.7, which gives a good sense of creativity, without being too consistent. Generally, temperature should be between 0.05 and 1, where 1 is very creative and 0.05 is very consistent.\n\n```C\n  var requestJson = new\n  {\n      messages = new[]\n      {\n          new\n          {\n              role = \"system\",\n              content = \"You are a travel agent. Please provide a detailed itinerary based on the user's input.\"\n          },\n          new\n          {\n              role = \"user\",\n              content = \"I am traveling to Denver, CO for three days and I like beer.\"\n          }\n      },\n      max_tokens = 1024,\n      temperature = 0.7,\n      model = \"gpt-3.5-turbo\"\n  };\n```\n\nNext, build a **HTTP content** using the serialized **requestJson** variable that we created above:\n\n```C\nStringContent content = new StringContent(JsonConvert.SerializeObject(requestJson), Encoding.UTF8, \"application/json\");\n```\n\n# Receiving the response\n\nThis next part is sending the message over to OpenAI and retrieving a JSON response.\n\n```C\n// Send the request and receive the response\nHttpResponseMessage response = client.PostAsync(requestUrl, content).Result;\nstring responseJson = response.Content.ReadAsStringAsync().Result;\n```\n\nThen, we'll deserialize the response into a readable format.\n\n```C\n// Extract the completed text from the response\ndynamic responseObject = JsonConvert.DeserializeObject(responseJson);\n```\n\nYou will receive a JSON response like this in the responseObject (don't copy this):\n\n```JSON\n{\n  \"id\": \"chatcmpl-123\",\n  \"object\": \"chat.completion\",\n  \"created\": 1677652288,\n  \"model\": \"gpt-3.5-turbo-0613\",\n  \"choices\": [{\n    \"index\": 0,\n    \"message\": {\n      \"role\": \"assistant\",\n      \"content\": \"\\n\\nSure, I can recommend you check out Livin the Dream brewery in Littleton and Denver Beer Co in Englewood.\",\n    },\n    \"finish_reason\": \"stop\"\n  }],\n  \"usage\": {\n    \"prompt_tokens\": 9,\n    \"completion_tokens\": 12,\n    \"total_tokens\": 21\n  }\n}\n```\n\n* choices[0] is the first response\n* message is the node within the choices[0]\n* content is the response you're looking for\n\nThe **completedText** string below is created from those three nodes above in the responseObject:\n\n```C\nstring completedText = responseObject.choices[0].message.content;\n```\n\n**completedText** will look like:\n\n\u003e Sure, I can recommend you check out Livin the Dream brewery in Littleton and Denver Beer Co in Englewood.\n\n# Everything together\n\nNow, put it together in all its glory:\n\n```C\n// setup variables and HTTPClient\nstring apiKey = \"[api key]\";\nServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;\nstring requestUrl = $\"https://api.openai.com/v1/chat/completions\";\nHttpClient client = new HttpClient();\nclient.DefaultRequestHeaders.Add(\"Authorization\", $\"Bearer {apikey}\");\n\n// build JSON request\n  var requestJson = new\n  {\n      messages = new[]\n      {\n          new\n          {\n              role = \"system\",\n              content = \"You are a travel agent. Please provide a detailed itinerary based on the user's input.\"\n          },\n          new\n          {\n              role = \"user\",\n              content = \"I am traveling to Denver, CO for three days and I like beer.\"\n          }\n      },\n      max_tokens = 1024,\n      temperature = 0.7,\n      model = \"gpt-3.5-turbo\"\n  };\n\nStringContent content = new StringContent(JsonConvert.SerializeObject(requestJson), Encoding.UTF8, \"application/json\");\n\n// Send the request and receive the response\nHttpResponseMessage response = client.PostAsync(requestUrl, content).Result;\nstring responseJson = response.Content.ReadAsStringAsync().Result;\n\n// Extract the completed text from the response\ndynamic responseObject = JsonConvert.DeserializeObject(responseJson);\nstring completedText = responseObject.choices[0].message.content;\n```\n\n\u003e Sure, I can recommend you check out Livin the Dream brewery in Littleton and Denver Beer Co in Englewood.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frkrehn%2Fcsharpchatgpt","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frkrehn%2Fcsharpchatgpt","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frkrehn%2Fcsharpchatgpt/lists"}