-
-
Save dpricha89/38958cb8d305fe746f0c458b7a560579 to your computer and use it in GitHub Desktop.
Using SSE with GPT API
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
# listen.py | |
# | |
import requests | |
import json | |
import pprint | |
# pip install sseclient-py | |
import sseclient | |
API_KEY = '<INSERT_API_KEY>' | |
def with_requests(url, headers, body): | |
"""Get a streaming response for the given event feed using requests.""" | |
import requests | |
return requests.post(url, stream=True, headers=headers, json=body) | |
if __name__ == '__main__': | |
url = 'https://api.openai.com/v1/completions' | |
headers = { | |
'Accept': 'text/event-stream', | |
'Authorization': 'Bearer ' + API_KEY | |
} | |
body = { | |
"model": "text-davinci-003", | |
"prompt": "Say this is a test", | |
"max_tokens": 7, | |
"temperature": 0, | |
"stream": True | |
} | |
request = with_requests(url, headers, body) | |
client = sseclient.SSEClient(request) | |
for event in client.events(): | |
if event.data != '[DONE]': | |
print(json.loads(event.data)['choices'][0]['text']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment