Created
May 2, 2023 09:45
-
-
Save Kotrotsos/42f4567735f44e81e77cc63c0f93e33c to your computer and use it in GitHub Desktop.
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
import json | |
# pip install sseclient-py, openai | |
import sseclient | |
import requests | |
import openai | |
import os | |
# add your env var. export OPENAI_API_KEY=<yourkeyhere> | |
openai.api_key = os.getenv("OPENAI_API_KEY") | |
def stream(): | |
req = 'https://api.openai.com/v1/completions' | |
headers = { | |
'Accept': 'text/event-stream', | |
'Authorization': 'Bearer ' + openai.api_key | |
} | |
prompt = input("#PROMPT: ") | |
body = { | |
"model": "text-davinci-003", | |
"prompt": prompt, | |
"max_tokens": 100, | |
"temperature": 0, | |
"stream": True | |
} | |
request = requests.post(req, stream=True, headers=headers, json=body) | |
client = sseclient.SSEClient(request) | |
try: | |
for event in client.events(): | |
if event.data != '[DONE]': | |
print(json.loads(event.data)['choices'][0]['text'], end="", flush=True) | |
except KeyboardInterrupt: | |
pass | |
if __name__ == '__main__': | |
stream() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment