├── C++ └── CHAT-GPT-C++.cpp ├── CSharp └── CHAT-GPT-CSharp.cs ├── GO └── CHAT-GPT-GO.go ├── JAVA └── CHAT-GPT-JAVA.java ├── Kotlin └── CHAT-GPT-KOTLIN.kt ├── LICENSE ├── NodeJs └── CHATGPT-NODEJS.js ├── PHP └── CHAT-GPT-PHP.php ├── Perl └── CHAT-GPT-PERL.pl ├── Python └── CHAT-GPT-PYTHON.py ├── R └── CHAT-GPT-R.r ├── README.md ├── Ruby └── CHAT-GPT-RUBY.rb ├── Rust └── CHAT-GPT-RUST.rs ├── Scala └── CHAT-GPT-SCALA.sc ├── Swift └── CHAT-GPT-SWIFT.swift └── TypeScript └── CHAT-GPT-TYPESCRIPT.ts /C++/CHAT-GPT-C++.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // Define the API endpoint and authorization token 6 | const std::string API_ENDPOINT = "https://api.openai.com/v1/engines/davinci-codex/completions"; 7 | const std::string AUTH_TOKEN = ""; 8 | 9 | // Define a function that sends a question to ChatGPT and receives an answer 10 | std::string ask_question(const std::string& question) { 11 | // Create a cURL handle 12 | CURL* curl = curl_easy_init(); 13 | 14 | // Set the API endpoint URL 15 | curl_easy_setopt(curl, CURLOPT_URL, API_ENDPOINT.c_str()); 16 | 17 | // Set the request headers 18 | struct curl_slist* headers = NULL; 19 | headers = curl_slist_append(headers, "Content-Type: application/json"); 20 | headers = curl_slist_append(headers, ("Authorization: Bearer " + AUTH_TOKEN).c_str()); 21 | curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); 22 | 23 | // Set the request data 24 | std::string request_data = "{ \"prompt\": \"" + question + "\", \"max_tokens\": 100, \"temperature\": 0.7 }"; 25 | curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request_data.c_str()); 26 | 27 | // Set the response buffer 28 | std::string response_buffer; 29 | curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, [](char* ptr, size_t size, size_t nmemb, void* userdata) -> size_t { 30 | size_t bytes = size * nmemb; 31 | std::string* buffer = static_cast(userdata); 32 | buffer->append(ptr, bytes); 33 | return bytes; 34 | }); 35 | curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_buffer); 36 | 37 | // Send the HTTP request 38 | CURLcode result = curl_easy_perform(curl); 39 | 40 | // Clean up the cURL handle and headers 41 | curl_easy_cleanup(curl); 42 | curl_slist_free_all(headers); 43 | 44 | // Check if the request was successful 45 | if (result != CURLE_OK) { 46 | std::cerr << "Error sending HTTP request: " << curl_easy_strerror(result) << std::endl; 47 | return ""; 48 | } 49 | 50 | // Parse the response JSON to extract the answer 51 | std::string answer; 52 | size_t answer_start_pos = response_buffer.find("\"text\": \"") + 9; 53 | size_t answer_end_pos = response_buffer.find("\"", answer_start_pos); 54 | if (answer_start_pos != std::string::npos && answer_end_pos != std::string::npos) { 55 | answer = response_buffer.substr(answer_start_pos, answer_end_pos - answer_start_pos); 56 | } 57 | 58 | return answer; 59 | } 60 | 61 | int main() { 62 | // Ask a question and print the answer 63 | std::string question = "What is the capital of France?"; 64 | std::string answer = ask_question(question); 65 | std::cout << "Question: " << question << std::endl; 66 | std::cout << "Answer: " << answer << std::endl; 67 | 68 | return 0; 69 | } 70 | -------------------------------------------------------------------------------- /CSharp/CHAT-GPT-CSharp.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.Http; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace ChatGptDemo 7 | { 8 | class Program 9 | { 10 | // Set up your OpenAI API key 11 | private const string API_KEY = "YOUR_OPENAI_API_KEY"; 12 | 13 | // Define the URL for the OpenAI API 14 | private const string OPENAI_URL = "https://api.openai.com/v1/engines/text-davinci-002/completions"; 15 | 16 | // Define the prompt for the conversation 17 | private const string PROMPT = "Hello, I'm ChatGPT. How can I help you today?"; 18 | 19 | // Define a function to get a response from ChatGPT 20 | static async Task GetResponse(string prompt) 21 | { 22 | // Create an HTTP client 23 | var client = new HttpClient(); 24 | 25 | // Create a JSON payload 26 | var payload = $"{{\"prompt\": \"{prompt}\", \"temperature\": 0.5, \"max_tokens\": 1024}}"; 27 | 28 | // Create an HTTP request 29 | var request = new HttpRequestMessage 30 | { 31 | RequestUri = new Uri(OPENAI_URL), 32 | Method = HttpMethod.Post, 33 | Headers = 34 | { 35 | { "Content-Type", "application/json" }, 36 | { "Authorization", $"Bearer {API_KEY}" } 37 | }, 38 | Content = new StringContent(payload, Encoding.UTF8, "application/json") 39 | }; 40 | 41 | // Send the HTTP request and get the response 42 | var response = await client.SendAsync(request); 43 | var responseContent = await response.Content.ReadAsStringAsync(); 44 | 45 | // Decode the response JSON to get the response text 46 | var responseText = responseContent.Split("\"text\": \"")[1].Split("\"}")[0]; 47 | 48 | // Return the response text 49 | return responseText; 50 | } 51 | 52 | static void Main(string[] args) 53 | { 54 | // Start the conversation 55 | while (true) 56 | { 57 | // Prompt the user for input 58 | Console.Write("You: "); 59 | var userInput = Console.ReadLine(); 60 | 61 | // Generate a response from ChatGPT 62 | var response = GetResponse($"{PROMPT}\n\nUser: {userInput}").Result; 63 | 64 | // Print the response 65 | Console.WriteLine($"ChatGPT: {response.Trim()}"); 66 | } 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /GO/CHAT-GPT-GO.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "net/http" 8 | "os" 9 | "strings" 10 | ) 11 | 12 | // Set up your OpenAI API key 13 | const apiKey = "YOUR_OPENAI_API_KEY" 14 | 15 | // Define the URL for the OpenAI API 16 | const openaiUrl = "https://api.openai.com/v1/engines/text-davinci-002/completions" 17 | 18 | // Define the prompt for the conversation 19 | const prompt = "Hello, I'm ChatGPT. How can I help you today?" 20 | 21 | // Define a struct to hold the response from ChatGPT 22 | type ChatGptResponse struct { 23 | Text string `json:"text"` 24 | } 25 | 26 | // Define a function to get a response from ChatGPT 27 | func getResponse(prompt string) (string, error) { 28 | // Create an HTTP client 29 | client := &http.Client{} 30 | 31 | // Create a JSON payload 32 | payload := map[string]interface{}{ 33 | "prompt": prompt, 34 | "temperature": 0.5, 35 | "max_tokens": 1024, 36 | } 37 | 38 | // Encode the payload as JSON 39 | payloadJson, err := json.Marshal(payload) 40 | if err != nil { 41 | return "", err 42 | } 43 | 44 | // Create an HTTP request 45 | req, err := http.NewRequest("POST", openaiUrl, bytes.NewBuffer(payloadJson)) 46 | if err != nil { 47 | return "", err 48 | } 49 | 50 | // Set the HTTP headers 51 | req.Header.Set("Content-Type", "application/json") 52 | req.Header.Set("Authorization", "Bearer "+apiKey) 53 | 54 | // Send the HTTP request 55 | res, err := client.Do(req) 56 | if err != nil { 57 | return "", err 58 | } 59 | defer res.Body.Close() 60 | 61 | // Decode the HTTP response 62 | var response struct { 63 | Choices []ChatGptResponse `json:"choices"` 64 | } 65 | if err := json.NewDecoder(res.Body).Decode(&response); err != nil { 66 | return "", err 67 | } 68 | 69 | // Return the response text 70 | return response.Choices[0].Text, nil 71 | } 72 | 73 | func main() { 74 | // Start the conversation 75 | for { 76 | // Prompt the user for input 77 | fmt.Print("You: ") 78 | var userInput string 79 | fmt.Scanln(&userInput) 80 | 81 | // Generate a response from ChatGPT 82 | response, err := getResponse(prompt + "\n\nUser: " + userInput) 83 | if err != nil { 84 | fmt.Fprintln(os.Stderr, "Error:", err) 85 | continue 86 | } 87 | 88 | // Print the response 89 | fmt.Println("ChatGPT:", strings.TrimSpace(response)) 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /JAVA/CHAT-GPT-JAVA.java: -------------------------------------------------------------------------------- 1 | import java.io.IOException; 2 | import java.net.URI; 3 | import java.net.http.HttpClient; 4 | import java.net.http.HttpRequest; 5 | import java.net.http.HttpResponse; 6 | import java.nio.charset.StandardCharsets; 7 | import java.util.Arrays; 8 | 9 | public class ChatGptDemo { 10 | 11 | // Set up your OpenAI API key 12 | private static final String API_KEY = "YOUR_OPENAI_API_KEY"; 13 | 14 | // Define the URL for the OpenAI API 15 | private static final String OPENAI_URL = "https://api.openai.com/v1/engines/text-davinci-002/completions"; 16 | 17 | // Define the prompt for the conversation 18 | private static final String PROMPT = "Hello, I'm ChatGPT. How can I help you today?"; 19 | 20 | // Define a function to get a response from ChatGPT 21 | public static String getResponse(String prompt) throws IOException, InterruptedException { 22 | // Create an HTTP client 23 | HttpClient client = HttpClient.newHttpClient(); 24 | 25 | // Create a JSON payload 26 | String payload = String.format("{\"prompt\": \"%s\", \"temperature\": 0.5, \"max_tokens\": 1024}", prompt); 27 | 28 | // Create an HTTP request 29 | HttpRequest request = HttpRequest.newBuilder() 30 | .uri(URI.create(OPENAI_URL)) 31 | .header("Content-Type", "application/json") 32 | .header("Authorization", "Bearer " + API_KEY) 33 | .POST(HttpRequest.BodyPublishers.ofString(payload, StandardCharsets.UTF_8)) 34 | .build(); 35 | 36 | // Send the HTTP request 37 | HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); 38 | 39 | // Decode the HTTP response 40 | String[] responseParts = response.body().split("\"text\": \""); 41 | String[] responseParts2 = responseParts[1].split("\"}"); 42 | String responseText = responseParts2[0]; 43 | 44 | // Return the response text 45 | return responseText; 46 | } 47 | 48 | public static void main(String[] args) throws IOException, InterruptedException { 49 | // Start the conversation 50 | while (true) { 51 | // Prompt the user for input 52 | System.out.print("You: "); 53 | String userInput = System.console().readLine(); 54 | 55 | // Generate a response from ChatGPT 56 | String response = getResponse(PROMPT + "\n\nUser: " + userInput); 57 | 58 | // Print the response 59 | System.out.println("ChatGPT: " + response.trim()); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Kotlin/CHAT-GPT-KOTLIN.kt: -------------------------------------------------------------------------------- 1 | import java.net.URI 2 | import java.net.http.HttpClient 3 | import java.net.http.HttpRequest 4 | import java.net.http.HttpResponse 5 | import java.nio.charset.StandardCharsets 6 | 7 | object ChatGptDemo { 8 | 9 | // Set up your OpenAI API key 10 | private const val API_KEY = "YOUR_OPENAI_API_KEY" 11 | 12 | // Define the URL for the OpenAI API 13 | private const val OPENAI_URL = "https://api.openai.com/v1/engines/text-davinci-002/completions" 14 | 15 | // Define the prompt for the conversation 16 | private const val PROMPT = "Hello, I'm ChatGPT. How can I help you today?" 17 | 18 | // Define a function to get a response from ChatGPT 19 | fun getResponse(prompt: String): String { 20 | // Create an HTTP client 21 | val client = HttpClient.newBuilder().build() 22 | 23 | // Create a JSON payload 24 | val payload = "{\"prompt\": \"$prompt\", \"temperature\": 0.5, \"max_tokens\": 1024}" 25 | 26 | // Create an HTTP request 27 | val request = HttpRequest.newBuilder() 28 | .uri(URI.create(OPENAI_URL)) 29 | .header("Content-Type", "application/json") 30 | .header("Authorization", "Bearer $API_KEY") 31 | .POST(HttpRequest.BodyPublishers.ofString(payload, StandardCharsets.UTF_8)) 32 | .build() 33 | 34 | // Send the HTTP request 35 | val response = client.send(request, HttpResponse.BodyHandlers.ofString()) 36 | 37 | // Decode the HTTP response 38 | val responseParts = response.body().split("\"text\": \"") 39 | val responseParts2 = responseParts[1].split("\"}") 40 | val responseText = responseParts2[0] 41 | 42 | // Return the response text 43 | return responseText 44 | } 45 | 46 | @JvmStatic 47 | fun main(args: Array) { 48 | // Start the conversation 49 | while (true) { 50 | // Prompt the user for input 51 | print("You: ") 52 | val userInput = readLine()!! 53 | 54 | // Generate a response from ChatGPT 55 | val response = getResponse("$PROMPT\n\nUser: $userInput") 56 | 57 | // Print the response 58 | println("ChatGPT: ${response.trim()}") 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Laqira Protocol 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 | -------------------------------------------------------------------------------- /NodeJs/CHATGPT-NODEJS.js: -------------------------------------------------------------------------------- 1 | const readline = require("readline"); 2 | const axios = require("axios"); 3 | 4 | // Set up your OpenAI API key 5 | const API_KEY = "YOUR_OPENAI_API_KEY"; 6 | const MODEL = "text-davinci-002"; 7 | 8 | // Define the prompt for the conversation 9 | const prompt = "Hello, I'm ChatGPT. How can I help you today?"; 10 | 11 | // Define a function to get a response from ChatGPT 12 | async function getResponse(prompt, model, apiKey, temperature = 0.5) { 13 | const response = await axios({ 14 | method: "post", 15 | url: `https://api.openai.com/v1/engines/${model}/completions`, 16 | headers: { 17 | "Content-Type": "application/json", 18 | Authorization: `Bearer ${apiKey}`, 19 | }, 20 | data: { 21 | prompt, 22 | temperature, 23 | max_tokens: 1024, 24 | }, 25 | }); 26 | return response.data.choices[0].text.trim(); 27 | } 28 | 29 | // Start the conversation 30 | const rl = readline.createInterface({ 31 | input: process.stdin, 32 | output: process.stdout, 33 | }); 34 | 35 | rl.on("line", async (input) => { 36 | // Generate a response from ChatGPT 37 | const response = await getResponse( 38 | prompt + "\n\nUser: " + input, 39 | MODEL, 40 | API_KEY 41 | ); 42 | 43 | // Print the response 44 | console.log("ChatGPT:", response); 45 | }); 46 | 47 | // Prompt the user for input 48 | rl.prompt(); 49 | -------------------------------------------------------------------------------- /PHP/CHAT-GPT-PHP.php: -------------------------------------------------------------------------------- 1 | $prompt, 19 | "temperature" => $temperature, 20 | "max_tokens" => 1024, 21 | ]; 22 | $curl = curl_init($url); 23 | curl_setopt($curl, CURLOPT_POST, true); 24 | curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); 25 | curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); 26 | curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 27 | $response = curl_exec($curl); 28 | curl_close($curl); 29 | return json_decode($response, true)["choices"][0]["text"]; 30 | } 31 | 32 | // Start the conversation 33 | while (true) { 34 | // Get user input 35 | $user_input = readline("You: "); 36 | 37 | // Generate a response from ChatGPT 38 | $response = get_response($prompt . "\n\nUser: " . $user_input, $model, $api_key); 39 | 40 | // Print the response 41 | echo "ChatGPT: " . $response . "\n"; 42 | } 43 | -------------------------------------------------------------------------------- /Perl/CHAT-GPT-PERL.pl: -------------------------------------------------------------------------------- 1 | use LWP::UserAgent; 2 | use JSON::XS; 3 | 4 | # Define the API endpoint and authorization token 5 | my $apiEndpoint = 'https://api.openai.com/v1/engines/davinci-codex/completions'; 6 | my $authToken = ''; 7 | 8 | # Define a function that sends a question to ChatGPT and receives an answer 9 | sub askQuestion { 10 | my ($question) = @_; 11 | 12 | my $ua = LWP::UserAgent->new; 13 | my $response = $ua->post( 14 | $apiEndpoint, 15 | Content_Type => 'application/json', 16 | Authorization => "Bearer $authToken", 17 | Content => encode_json({ 18 | prompt => $question, 19 | max_tokens => 100, 20 | temperature => 0.7 21 | }) 22 | ); 23 | 24 | if ($response->is_error) { 25 | print "Error asking question: " . $response->status_line . "\n"; 26 | return ''; 27 | } else { 28 | my $answer = decode_json($response->decoded_content)->{choices}->[0]->{text}; 29 | $answer =~ s/\s+$//; # Remove any trailing whitespace 30 | return $answer; 31 | } 32 | } 33 | 34 | # Example usage 35 | my $question = 'What is the capital of France?'; 36 | my $answer = askQuestion($question); 37 | print "Question: $question\n"; 38 | print "Answer: $answer\n"; 39 | -------------------------------------------------------------------------------- /Python/CHAT-GPT-PYTHON.py: -------------------------------------------------------------------------------- 1 | import openai 2 | import os 3 | 4 | # Set up your OpenAI API key 5 | openai.api_key = os.environ["OPENAI_API_KEY"] 6 | 7 | # Define the prompt for the conversation 8 | prompt = "Hello, I'm ChatGPT. How can I help you today?" 9 | 10 | # Define a function to get a response from ChatGPT 11 | def get_response(prompt, model, temperature=0.5): 12 | response = openai.Completion.create( 13 | engine=model, 14 | prompt=prompt, 15 | max_tokens=1024, 16 | temperature=temperature, 17 | ) 18 | return response.choices[0].text.strip() 19 | 20 | # Start the conversation 21 | while True: 22 | # Get user input 23 | user_input = input("You: ") 24 | 25 | # Generate a response from ChatGPT 26 | response = get_response(prompt + "\n\nUser: " + user_input, "text-davinci-002") 27 | 28 | # Print the response 29 | print("ChatGPT:", response) 30 | -------------------------------------------------------------------------------- /R/CHAT-GPT-R.r: -------------------------------------------------------------------------------- 1 | library(httr) 2 | 3 | # Set up your OpenAI API key 4 | apiKey <- "YOUR_OPENAI_API_KEY" 5 | 6 | # Define the URL for the OpenAI API 7 | openaiURL <- "https://api.openai.com/v1/engines/text-davinci-002/completions" 8 | 9 | # Define the prompt for the conversation 10 | prompt <- "Hello, I'm ChatGPT. How can I help you today?" 11 | 12 | # Define a function to get a response from ChatGPT 13 | getResponse <- function(prompt) { 14 | # Create a JSON payload 15 | payload <- list( 16 | prompt = paste(prompt, "\n\nUser:"), 17 | temperature = 0.5, 18 | max_tokens = 1024 19 | ) 20 | 21 | # Create an HTTP request 22 | response <- POST( 23 | openaiURL, 24 | add_headers(Authorization = paste("Bearer", apiKey)), 25 | body = toJSON(payload), 26 | encode = "json" 27 | ) 28 | 29 | # Handle any errors 30 | stop_for_status(response) 31 | 32 | # Parse the response JSON to get the response text 33 | responseJSON <- content(response, "text") 34 | responseDict <- fromJSON(responseJSON, simplifyVector = TRUE) 35 | choices <- responseDict$choices[[1]] 36 | text <- choices$text 37 | 38 | return(text) 39 | } 40 | 41 | # Start the conversation 42 | while (TRUE) { 43 | # Prompt the user for input 44 | userInput <- readline(prompt = "You: ") 45 | 46 | # Generate a response from ChatGPT 47 | response <- getResponse(paste(prompt, userInput)) 48 | 49 | # Print the response 50 | cat("ChatGPT: ", trimws(response), "\n") 51 | } 52 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ChatGPT-with-15-language 2 | 3 | Development of artificial intelligence infrastructure for all people. Collective cooperation. 4 | 5 | The initial version of GPT chat artificial intelligence in 15 programming languages 6 | 7 | - Go 8 | 9 | - C# 10 | 11 | - C++ 12 | 13 | - Java 14 | 15 | - Kotlin 16 | 17 | - Perl 18 | 19 | - PHP 20 | 21 | - NodeJS 22 | 23 | - TypeScript 24 | 25 | - Ruby 26 | 27 | - R 28 | 29 | - Rust 30 | 31 | - Python 32 | 33 | - Swift 34 | 35 | - Scala 36 | 37 | ### Support us and tell us which language to develop more and add new parts to it. 38 | -------------------------------------------------------------------------------- /Ruby/CHAT-GPT-RUBY.rb: -------------------------------------------------------------------------------- 1 | require "json" 2 | require "net/http" 3 | 4 | # Set up your OpenAI API key 5 | API_KEY = "YOUR_OPENAI_API_KEY" 6 | MODEL = "text-davinci-002" 7 | 8 | # Define the prompt for the conversation 9 | PROMPT = "Hello, I'm ChatGPT. How can I help you today?" 10 | 11 | # Define a function to get a response from ChatGPT 12 | def get_response(prompt, model, api_key, temperature = 0.5) 13 | uri = URI("https://api.openai.com/v1/engines/#{model}/completions") 14 | headers = { 15 | "Content-Type" => "application/json", 16 | "Authorization" => "Bearer #{api_key}" 17 | } 18 | data = { 19 | prompt: prompt, 20 | temperature: temperature, 21 | max_tokens: 1024 22 | } 23 | response = Net::HTTP.post(uri, data.to_json, headers) 24 | JSON.parse(response.body)["choices"][0]["text"].strip 25 | end 26 | 27 | # Start the conversation 28 | loop do 29 | # Prompt the user for input 30 | print "You: " 31 | user_input = gets.chomp 32 | 33 | # Generate a response from ChatGPT 34 | response = get_response(PROMPT + "\n\nUser: #{user_input}", MODEL, API_KEY) 35 | 36 | # Print the response 37 | puts "ChatGPT: #{response}" 38 | end 39 | -------------------------------------------------------------------------------- /Rust/CHAT-GPT-RUST.rs: -------------------------------------------------------------------------------- 1 | use reqwest::header::{HeaderMap, AUTHORIZATION, CONTENT_TYPE}; 2 | use serde::{Deserialize, Serialize}; 3 | use std::io::{stdin, stdout, Write}; 4 | 5 | // Set up your OpenAI API key 6 | const API_KEY: &str = "YOUR_OPENAI_API_KEY"; 7 | const MODEL: &str = "text-davinci-002"; 8 | 9 | // Define the prompt for the conversation 10 | const PROMPT: &str = "Hello, I'm ChatGPT. How can I help you today?"; 11 | 12 | // Define a struct to hold the response from ChatGPT 13 | #[derive(Debug, Deserialize)] 14 | struct ChatGptResponse { 15 | text: String, 16 | } 17 | 18 | // Define a function to get a response from ChatGPT 19 | async fn get_response(prompt: &str, model: &str, api_key: &str, temperature: f64) -> String { 20 | let client = reqwest::Client::new(); 21 | let mut headers = HeaderMap::new(); 22 | headers.insert(CONTENT_TYPE, "application/json".parse().unwrap()); 23 | headers.insert(AUTHORIZATION, format!("Bearer {}", api_key).parse().unwrap()); 24 | let data = format!( 25 | r#"{{"prompt":"{}","temperature":{},"max_tokens":1024}}"#, 26 | prompt, temperature 27 | ); 28 | let response = client 29 | .post(&format!( 30 | "https://api.openai.com/v1/engines/{}/completions", 31 | model 32 | )) 33 | .headers(headers) 34 | .body(data) 35 | .send() 36 | .await 37 | .unwrap() 38 | .json::>() 39 | .await 40 | .unwrap(); 41 | response[0].text.trim().to_string() 42 | } 43 | 44 | #[tokio::main] 45 | async fn main() { 46 | // Start the conversation 47 | loop { 48 | // Prompt the user for input 49 | print!("You: "); 50 | stdout().flush().unwrap(); 51 | let mut user_input = String::new(); 52 | stdin().read_line(&mut user_input).unwrap(); 53 | 54 | // Generate a response from ChatGPT 55 | let response = get_response( 56 | &(PROMPT.to_owned() + "\n\nUser: " + &user_input), 57 | MODEL, 58 | API_KEY, 59 | 0.5, 60 | ) 61 | .await; 62 | 63 | // Print the response 64 | println!("ChatGPT: {}", response); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Scala/CHAT-GPT-SCALA.sc: -------------------------------------------------------------------------------- 1 | import scalaj.http._ 2 | 3 | // Define the API endpoint and authorization token 4 | val apiEndpoint = "https://api.openai.com/v1/engines/davinci-codex/completions" 5 | val authToken = "" 6 | 7 | // Define a function that sends a question to ChatGPT and receives an answer 8 | def askQuestion(question: String): String = { 9 | val request = Http(apiEndpoint) 10 | .header("Content-Type", "application/json") 11 | .header("Authorization", s"Bearer $authToken") 12 | .postData(s"""{"prompt": "$question", "max_tokens": 100, "temperature": 0.7}""") 13 | val response = request.asString 14 | 15 | if (response.isError) { 16 | println(s"Error asking question: ${response.body}") 17 | "" 18 | } else { 19 | val answer = response.body.replaceAll("\\s+$", "") 20 | answer 21 | } 22 | } 23 | 24 | // Example usage 25 | val question = "What is the capital of France?" 26 | val answer = askQuestion(question) 27 | println(s"Question: $question") 28 | println(s"Answer: $answer") 29 | -------------------------------------------------------------------------------- /Swift/CHAT-GPT-SWIFT.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | // Set up your OpenAI API key 4 | let apiKey = "YOUR_OPENAI_API_KEY" 5 | 6 | // Define the URL for the OpenAI API 7 | let openaiURL = URL(string: "https://api.openai.com/v1/engines/text-davinci-002/completions")! 8 | 9 | // Define the prompt for the conversation 10 | let prompt = "Hello, I'm ChatGPT. How can I help you today?" 11 | 12 | // Define a function to get a response from ChatGPT 13 | func getResponse(prompt: String, completionHandler: @escaping (String?, Error?) -> Void) { 14 | // Create a JSON payload 15 | let payload = """ 16 | { 17 | "prompt": "\(prompt)\n\nUser:", 18 | "temperature": 0.5, 19 | "max_tokens": 1024 20 | } 21 | """ 22 | 23 | // Create an HTTP request 24 | var request = URLRequest(url: openaiURL) 25 | request.httpMethod = "POST" 26 | request.addValue("application/json", forHTTPHeaderField: "Content-Type") 27 | request.addValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization") 28 | request.httpBody = payload.data(using: .utf8) 29 | 30 | // Send the HTTP request and get the response 31 | let session = URLSession.shared 32 | let task = session.dataTask(with: request) { data, response, error in 33 | // Handle any errors 34 | guard error == nil else { 35 | completionHandler(nil, error) 36 | return 37 | } 38 | 39 | // Parse the response JSON to get the response text 40 | if let data = data, 41 | let responseJSON = try? JSONSerialization.jsonObject(with: data, options: []), 42 | let responseDict = responseJSON as? [String: Any], 43 | let choices = responseDict["choices"] as? [[String: Any]], 44 | let text = choices.first?["text"] as? String { 45 | completionHandler(text, nil) 46 | } else { 47 | completionHandler(nil, NSError(domain: "ChatGPTError", code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed to parse response."])) 48 | } 49 | } 50 | task.resume() 51 | } 52 | 53 | // Start the conversation 54 | while true { 55 | // Prompt the user for input 56 | print("You: ", terminator: "") 57 | let userInput = readLine() ?? "" 58 | 59 | // Generate a response from ChatGPT 60 | getResponse(prompt: "\(prompt)\n\nUser: \(userInput)") { response, error in 61 | // Handle any errors 62 | if let error = error { 63 | print("Error: \(error.localizedDescription)") 64 | return 65 | } 66 | 67 | // Print the response 68 | print("ChatGPT: \(response?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "")") 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /TypeScript/CHAT-GPT-TYPESCRIPT.ts: -------------------------------------------------------------------------------- 1 | import axios from 'axios'; 2 | 3 | // Define the API endpoint and authorization token 4 | const API_ENDPOINT = 'https://api.openai.com/v1/engines/davinci-codex/completions'; 5 | const AUTH_TOKEN = ''; 6 | 7 | // Define a function that sends a question to ChatGPT and receives an answer 8 | async function askQuestion(question: string): Promise { 9 | try { 10 | // Send the HTTP request to the OpenAI API 11 | const response = await axios.post(API_ENDPOINT, { 12 | prompt: question, 13 | max_tokens: 100, 14 | temperature: 0.7 15 | }, { 16 | headers: { 17 | 'Content-Type': 'application/json', 18 | 'Authorization': `Bearer ${AUTH_TOKEN}` 19 | } 20 | }); 21 | 22 | // Extract the answer from the response data 23 | const answer = response.data.choices[0].text.trim(); 24 | 25 | return answer; 26 | } catch (error) { 27 | console.error(`Error asking question: ${error.message}`); 28 | return ''; 29 | } 30 | } 31 | 32 | // Example usage 33 | (async () => { 34 | const question = 'What is the capital of France?'; 35 | const answer = await askQuestion(question); 36 | console.log(`Question: ${question}`); 37 | console.log(`Answer: ${answer}`); 38 | })(); 39 | --------------------------------------------------------------------------------