Skip to content

Instantly share code, notes, and snippets.

@david-strejc
Created April 16, 2023 18:15
Show Gist options
  • Save david-strejc/072e089a9e3dfdfc6cab91a2912ae9ec to your computer and use it in GitHub Desktop.
Save david-strejc/072e089a9e3dfdfc6cab91a2912ae9ec to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import requests
import json
# Define your API key here. Replace "your-api-key" with your actual API key.
api_key = "your-api-key"
# Define the ChatGPT API endpoint.
url = "https://api.openai.com/v1/engines/davinci-codex/completions"
# Define the context as an array of dictionaries with role and content fields.
context = [
{"role": "system", "content": "You are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible.\nKnowledge cutoff: 2021-09-01\nCurrent date: 2023-03-02"},
{"role": "user", "content": "How are you?"},
{"role": "assistant", "content": "I am doing well"},
{"role": "user", "content": "When was the last Formula One championship in South Africa?"},
{"role": "assistant", "content": "The last Formula One championship race held in South Africa was on October 17, 1993."},
{"role": "user", "content": "Who won the race in South Africa?"},
]
# Convert the context array to a text format suitable for passing to the API.
context_text = ""
for entry in context:
context_text += f"{entry['role']}: {entry['content']}\n"
# Define a function to send a message to the ChatGPT API.
def send_message_to_chatgpt(prompt):
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}",
}
data = {
"prompt": f"{context_text}user: {prompt}\nassistant:",
"max_tokens": 150,
"n": 1,
"stop": None,
"temperature": 0.7,
}
response = requests.post(url, headers=headers, data=json.dumps(data))
if response.status_code == 200:
result = response.json()
return result["choices"][0]["text"].strip()
else:
print(f"Error {response.status_code}: {response.text}")
return None
# Example usage:
prompt = "What is the top speed of a Formula One car?"
response_text = send_message_to_chatgpt(prompt)
print(response_text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment