-
Notifications
You must be signed in to change notification settings - Fork 204
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit d692793
Showing
17 changed files
with
858 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
#include <iostream> | ||
#include <string> | ||
#include <curl/curl.h> | ||
|
||
// Define the API endpoint and authorization token | ||
const std::string API_ENDPOINT = "https://api.openai.com/v1/engines/davinci-codex/completions"; | ||
const std::string AUTH_TOKEN = "<YOUR_AUTH_TOKEN>"; | ||
|
||
// Define a function that sends a question to ChatGPT and receives an answer | ||
std::string ask_question(const std::string& question) { | ||
// Create a cURL handle | ||
CURL* curl = curl_easy_init(); | ||
|
||
// Set the API endpoint URL | ||
curl_easy_setopt(curl, CURLOPT_URL, API_ENDPOINT.c_str()); | ||
|
||
// Set the request headers | ||
struct curl_slist* headers = NULL; | ||
headers = curl_slist_append(headers, "Content-Type: application/json"); | ||
headers = curl_slist_append(headers, ("Authorization: Bearer " + AUTH_TOKEN).c_str()); | ||
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); | ||
|
||
// Set the request data | ||
std::string request_data = "{ \"prompt\": \"" + question + "\", \"max_tokens\": 100, \"temperature\": 0.7 }"; | ||
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request_data.c_str()); | ||
|
||
// Set the response buffer | ||
std::string response_buffer; | ||
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, [](char* ptr, size_t size, size_t nmemb, void* userdata) -> size_t { | ||
size_t bytes = size * nmemb; | ||
std::string* buffer = static_cast<std::string*>(userdata); | ||
buffer->append(ptr, bytes); | ||
return bytes; | ||
}); | ||
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_buffer); | ||
|
||
// Send the HTTP request | ||
CURLcode result = curl_easy_perform(curl); | ||
|
||
// Clean up the cURL handle and headers | ||
curl_easy_cleanup(curl); | ||
curl_slist_free_all(headers); | ||
|
||
// Check if the request was successful | ||
if (result != CURLE_OK) { | ||
std::cerr << "Error sending HTTP request: " << curl_easy_strerror(result) << std::endl; | ||
return ""; | ||
} | ||
|
||
// Parse the response JSON to extract the answer | ||
std::string answer; | ||
size_t answer_start_pos = response_buffer.find("\"text\": \"") + 9; | ||
size_t answer_end_pos = response_buffer.find("\"", answer_start_pos); | ||
if (answer_start_pos != std::string::npos && answer_end_pos != std::string::npos) { | ||
answer = response_buffer.substr(answer_start_pos, answer_end_pos - answer_start_pos); | ||
} | ||
|
||
return answer; | ||
} | ||
|
||
int main() { | ||
// Ask a question and print the answer | ||
std::string question = "What is the capital of France?"; | ||
std::string answer = ask_question(question); | ||
std::cout << "Question: " << question << std::endl; | ||
std::cout << "Answer: " << answer << std::endl; | ||
|
||
return 0; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
using System; | ||
using System.Net.Http; | ||
using System.Text; | ||
using System.Threading.Tasks; | ||
|
||
namespace ChatGptDemo | ||
{ | ||
class Program | ||
{ | ||
// Set up your OpenAI API key | ||
private const string API_KEY = "YOUR_OPENAI_API_KEY"; | ||
|
||
// Define the URL for the OpenAI API | ||
private const string OPENAI_URL = "https://api.openai.com/v1/engines/text-davinci-002/completions"; | ||
|
||
// Define the prompt for the conversation | ||
private const string PROMPT = "Hello, I'm ChatGPT. How can I help you today?"; | ||
|
||
// Define a function to get a response from ChatGPT | ||
static async Task<string> GetResponse(string prompt) | ||
{ | ||
// Create an HTTP client | ||
var client = new HttpClient(); | ||
|
||
// Create a JSON payload | ||
var payload = $"{{\"prompt\": \"{prompt}\", \"temperature\": 0.5, \"max_tokens\": 1024}}"; | ||
|
||
// Create an HTTP request | ||
var request = new HttpRequestMessage | ||
{ | ||
RequestUri = new Uri(OPENAI_URL), | ||
Method = HttpMethod.Post, | ||
Headers = | ||
{ | ||
{ "Content-Type", "application/json" }, | ||
{ "Authorization", $"Bearer {API_KEY}" } | ||
}, | ||
Content = new StringContent(payload, Encoding.UTF8, "application/json") | ||
}; | ||
|
||
// Send the HTTP request and get the response | ||
var response = await client.SendAsync(request); | ||
var responseContent = await response.Content.ReadAsStringAsync(); | ||
|
||
// Decode the response JSON to get the response text | ||
var responseText = responseContent.Split("\"text\": \"")[1].Split("\"}")[0]; | ||
|
||
// Return the response text | ||
return responseText; | ||
} | ||
|
||
static void Main(string[] args) | ||
{ | ||
// Start the conversation | ||
while (true) | ||
{ | ||
// Prompt the user for input | ||
Console.Write("You: "); | ||
var userInput = Console.ReadLine(); | ||
|
||
// Generate a response from ChatGPT | ||
var response = GetResponse($"{PROMPT}\n\nUser: {userInput}").Result; | ||
|
||
// Print the response | ||
Console.WriteLine($"ChatGPT: {response.Trim()}"); | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
package main | ||
|
||
import ( | ||
"bytes" | ||
"encoding/json" | ||
"fmt" | ||
"net/http" | ||
"os" | ||
"strings" | ||
) | ||
|
||
// Set up your OpenAI API key | ||
const apiKey = "YOUR_OPENAI_API_KEY" | ||
|
||
// Define the URL for the OpenAI API | ||
const openaiUrl = "https://api.openai.com/v1/engines/text-davinci-002/completions" | ||
|
||
// Define the prompt for the conversation | ||
const prompt = "Hello, I'm ChatGPT. How can I help you today?" | ||
|
||
// Define a struct to hold the response from ChatGPT | ||
type ChatGptResponse struct { | ||
Text string `json:"text"` | ||
} | ||
|
||
// Define a function to get a response from ChatGPT | ||
func getResponse(prompt string) (string, error) { | ||
// Create an HTTP client | ||
client := &http.Client{} | ||
|
||
// Create a JSON payload | ||
payload := map[string]interface{}{ | ||
"prompt": prompt, | ||
"temperature": 0.5, | ||
"max_tokens": 1024, | ||
} | ||
|
||
// Encode the payload as JSON | ||
payloadJson, err := json.Marshal(payload) | ||
if err != nil { | ||
return "", err | ||
} | ||
|
||
// Create an HTTP request | ||
req, err := http.NewRequest("POST", openaiUrl, bytes.NewBuffer(payloadJson)) | ||
if err != nil { | ||
return "", err | ||
} | ||
|
||
// Set the HTTP headers | ||
req.Header.Set("Content-Type", "application/json") | ||
req.Header.Set("Authorization", "Bearer "+apiKey) | ||
|
||
// Send the HTTP request | ||
res, err := client.Do(req) | ||
if err != nil { | ||
return "", err | ||
} | ||
defer res.Body.Close() | ||
|
||
// Decode the HTTP response | ||
var response struct { | ||
Choices []ChatGptResponse `json:"choices"` | ||
} | ||
if err := json.NewDecoder(res.Body).Decode(&response); err != nil { | ||
return "", err | ||
} | ||
|
||
// Return the response text | ||
return response.Choices[0].Text, nil | ||
} | ||
|
||
func main() { | ||
// Start the conversation | ||
for { | ||
// Prompt the user for input | ||
fmt.Print("You: ") | ||
var userInput string | ||
fmt.Scanln(&userInput) | ||
|
||
// Generate a response from ChatGPT | ||
response, err := getResponse(prompt + "\n\nUser: " + userInput) | ||
if err != nil { | ||
fmt.Fprintln(os.Stderr, "Error:", err) | ||
continue | ||
} | ||
|
||
// Print the response | ||
fmt.Println("ChatGPT:", strings.TrimSpace(response)) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
import java.io.IOException; | ||
import java.net.URI; | ||
import java.net.http.HttpClient; | ||
import java.net.http.HttpRequest; | ||
import java.net.http.HttpResponse; | ||
import java.nio.charset.StandardCharsets; | ||
import java.util.Arrays; | ||
|
||
public class ChatGptDemo { | ||
|
||
// Set up your OpenAI API key | ||
private static final String API_KEY = "YOUR_OPENAI_API_KEY"; | ||
|
||
// Define the URL for the OpenAI API | ||
private static final String OPENAI_URL = "https://api.openai.com/v1/engines/text-davinci-002/completions"; | ||
|
||
// Define the prompt for the conversation | ||
private static final String PROMPT = "Hello, I'm ChatGPT. How can I help you today?"; | ||
|
||
// Define a function to get a response from ChatGPT | ||
public static String getResponse(String prompt) throws IOException, InterruptedException { | ||
// Create an HTTP client | ||
HttpClient client = HttpClient.newHttpClient(); | ||
|
||
// Create a JSON payload | ||
String payload = String.format("{\"prompt\": \"%s\", \"temperature\": 0.5, \"max_tokens\": 1024}", prompt); | ||
|
||
// Create an HTTP request | ||
HttpRequest request = HttpRequest.newBuilder() | ||
.uri(URI.create(OPENAI_URL)) | ||
.header("Content-Type", "application/json") | ||
.header("Authorization", "Bearer " + API_KEY) | ||
.POST(HttpRequest.BodyPublishers.ofString(payload, StandardCharsets.UTF_8)) | ||
.build(); | ||
|
||
// Send the HTTP request | ||
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); | ||
|
||
// Decode the HTTP response | ||
String[] responseParts = response.body().split("\"text\": \""); | ||
String[] responseParts2 = responseParts[1].split("\"}"); | ||
String responseText = responseParts2[0]; | ||
|
||
// Return the response text | ||
return responseText; | ||
} | ||
|
||
public static void main(String[] args) throws IOException, InterruptedException { | ||
// Start the conversation | ||
while (true) { | ||
// Prompt the user for input | ||
System.out.print("You: "); | ||
String userInput = System.console().readLine(); | ||
|
||
// Generate a response from ChatGPT | ||
String response = getResponse(PROMPT + "\n\nUser: " + userInput); | ||
|
||
// Print the response | ||
System.out.println("ChatGPT: " + response.trim()); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
import java.net.URI | ||
import java.net.http.HttpClient | ||
import java.net.http.HttpRequest | ||
import java.net.http.HttpResponse | ||
import java.nio.charset.StandardCharsets | ||
|
||
object ChatGptDemo { | ||
|
||
// Set up your OpenAI API key | ||
private const val API_KEY = "YOUR_OPENAI_API_KEY" | ||
|
||
// Define the URL for the OpenAI API | ||
private const val OPENAI_URL = "https://api.openai.com/v1/engines/text-davinci-002/completions" | ||
|
||
// Define the prompt for the conversation | ||
private const val PROMPT = "Hello, I'm ChatGPT. How can I help you today?" | ||
|
||
// Define a function to get a response from ChatGPT | ||
fun getResponse(prompt: String): String { | ||
// Create an HTTP client | ||
val client = HttpClient.newBuilder().build() | ||
|
||
// Create a JSON payload | ||
val payload = "{\"prompt\": \"$prompt\", \"temperature\": 0.5, \"max_tokens\": 1024}" | ||
|
||
// Create an HTTP request | ||
val request = HttpRequest.newBuilder() | ||
.uri(URI.create(OPENAI_URL)) | ||
.header("Content-Type", "application/json") | ||
.header("Authorization", "Bearer $API_KEY") | ||
.POST(HttpRequest.BodyPublishers.ofString(payload, StandardCharsets.UTF_8)) | ||
.build() | ||
|
||
// Send the HTTP request | ||
val response = client.send(request, HttpResponse.BodyHandlers.ofString()) | ||
|
||
// Decode the HTTP response | ||
val responseParts = response.body().split("\"text\": \"") | ||
val responseParts2 = responseParts[1].split("\"}") | ||
val responseText = responseParts2[0] | ||
|
||
// Return the response text | ||
return responseText | ||
} | ||
|
||
@JvmStatic | ||
fun main(args: Array<String>) { | ||
// Start the conversation | ||
while (true) { | ||
// Prompt the user for input | ||
print("You: ") | ||
val userInput = readLine()!! | ||
|
||
// Generate a response from ChatGPT | ||
val response = getResponse("$PROMPT\n\nUser: $userInput") | ||
|
||
// Print the response | ||
println("ChatGPT: ${response.trim()}") | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
use LWP::UserAgent; | ||
use JSON::XS; | ||
|
||
# Define the API endpoint and authorization token | ||
my $apiEndpoint = 'https://api.openai.com/v1/engines/davinci-codex/completions'; | ||
my $authToken = '<YOUR_AUTH_TOKEN>'; | ||
|
||
# Define a function that sends a question to ChatGPT and receives an answer | ||
sub askQuestion { | ||
my ($question) = @_; | ||
|
||
my $ua = LWP::UserAgent->new; | ||
my $response = $ua->post( | ||
$apiEndpoint, | ||
Content_Type => 'application/json', | ||
Authorization => "Bearer $authToken", | ||
Content => encode_json({ | ||
prompt => $question, | ||
max_tokens => 100, | ||
temperature => 0.7 | ||
}) | ||
); | ||
|
||
if ($response->is_error) { | ||
print "Error asking question: " . $response->status_line . "\n"; | ||
return ''; | ||
} else { | ||
my $answer = decode_json($response->decoded_content)->{choices}->[0]->{text}; | ||
$answer =~ s/\s+$//; # Remove any trailing whitespace | ||
return $answer; | ||
} | ||
} | ||
|
||
# Example usage | ||
my $question = 'What is the capital of France?'; | ||
my $answer = askQuestion($question); | ||
print "Question: $question\n"; | ||
print "Answer: $answer\n"; |
Oops, something went wrong.