Skip to content

Commit

Permalink
Streaming example for the updated OpenAI API (#7508)
Browse files Browse the repository at this point in the history
* Changes for updated OpenAI api

* Update guides/04_chatbots/01_creating-a-chatbot-fast.md

---------

Co-authored-by: Abubakar Abid <abubakar@huggingface.co>
  • Loading branch information
triakshunn and abidlabs committed Feb 22, 2024
1 parent 33f68cb commit 8f050ee
Showing 1 changed file with 11 additions and 12 deletions.
23 changes: 11 additions & 12 deletions guides/04_chatbots/01_creating-a-chatbot-fast.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,30 +198,29 @@ gr.ChatInterface(predict).launch()
Of course, we could also use the `openai` library directy. Here a similar example, but this time with streaming results as well:

```python
import openai
from openai import OpenAI
import gradio as gr

openai.api_key = "sk-..." # Replace with your key
api_key = "sk-..." # Replace with your key
client = OpenAI(api_key=api_key)

def predict(message, history):
history_openai_format = []
for human, assistant in history:
history_openai_format.append({"role": "user", "content": human })
history_openai_format.append({"role": "assistant", "content":assistant})
history_openai_format.append({"role": "user", "content": message})

response = openai.ChatCompletion.create(
model='gpt-3.5-turbo',
messages= history_openai_format,
temperature=1.0,
stream=True
)

response = client.chat.completions.create(model='gpt-3.5-turbo',
messages= history_openai_format,
temperature=1.0,
stream=True)

partial_message = ""
for chunk in response:
if len(chunk['choices'][0]['delta']) != 0:
partial_message = partial_message + chunk['choices'][0]['delta']['content']
yield partial_message
if chunk.choices[0].delta.content is not None:
partial_message = partial_message + chunk.choices[0].delta.content
yield partial_message

gr.ChatInterface(predict).launch()
```
Expand Down

0 comments on commit 8f050ee

Please sign in to comment.