import requests
import json
response = requests.post(
'https://api.droxy.ai/v1/chatbot/chat-stream',
headers={
'accept': 'application/json',
'content-type': 'application/json',
'x-api-key': '<API_KEY>'
},
data=json.dumps({
'chatbotId': '<CHATBOT_ID>',
'conversation': [{'fromUser': True, 'text': 'Hello!'}]
}),
stream=True
)
# Raise an error if the response status isn't successful.
if response.status_code != 201:
error = response.json()
raise Exception(error.get('message', 'Request failed'))
else:
try:
# Process each chunk event in the response stream. Due to buffering, more than one chunk may be available at a time.
for chunk in response.iter_lines():
if chunk:
# Decode the line
decoded_event = chunk.decode('utf-8')
# Load the line as JSON and process the message
event = json.loads(decoded_event)
# Get the event type
event_type = event.get("type")
# Handle the partial response here.
if event_type == 'partialResponse':
print('Partial response:', event)
# Handle the end of the stream here.
elif event_type == 'streamEnd':
print('Stream ended:', event)
break
# Handle any errors while streaming here.
elif event_type == 'error':
raise Exception(f"Error from stream: {event.get('message')}")
except Exception as e:
print(f'Error processing stream: {e}')