-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcohere_coral_chat.py
97 lines (82 loc) · 3.9 KB
/
cohere_coral_chat.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import os
import gradio as gr
import cohere
from cohere.responses.classify import Example
from dotenv import load_dotenv, find_dotenv
# read local .env file
_ = load_dotenv(find_dotenv())
COHERE_API_KEY = os.environ["COHERE_API_KEY"]
chat_history = []
async def chat_stream(question, history, model, citation_quality, prompt_truncation, randomness):
if question is None or len(question) == 0:
return
history = chat_history
async with cohere.AsyncClient(api_key=COHERE_API_KEY) as aio_co:
streaming_chat = await aio_co.chat(
message=question,
chat_history=history,
model=model,
stream=True,
citation_quality=citation_quality,
prompt_truncation=prompt_truncation,
temperature=randomness
)
completion = ""
async for token in streaming_chat:
# print(f"chat_stream token: {token}")
# print(f"chat_stream type(token): {type(token)}")
if isinstance(token, cohere.responses.chat.StreamTextGeneration):
completion += token.text
yield completion
if len(chat_history) == 10:
chat_history.pop(0)
user_message = {"user_name": "User", "text": question}
bot_message = {"user_name": "Chatbot", "text": completion}
chat_history.append(user_message)
chat_history.append(bot_message)
model_text = gr.Dropdown(label="Model",
choices=["command", "command-nightly",
"command-light", "command-light-nightly"],
value="command",
)
citation_quality_text = gr.Dropdown(label="Citation Quality",
choices=["accurate", "fast"],
value="accurate",
interactive=True
)
prompt_truncation_text = gr.Dropdown(label="Prompt Truncation",
choices=["auto", "off"],
value="auto",
interactive=True
)
randomness_text = gr.Slider(label="Randomness(Temperature)",
minimum=0,
maximum=2,
step=0.1,
value=0.3,
interactive=True
)
coral_chat = gr.ChatInterface(fn=chat_stream,
additional_inputs=[model_text,
citation_quality_text,
prompt_truncation_text,
randomness_text
],
additional_inputs_accordion_name="Additional Inputs",
examples=[
["Can you give me a global market overview of the solar panels?", "command",
"accurate",
"auto", 0.3],
["Gather business intelligence on the Chinese markets", "command-nightly", "accurate",
"auto", 0.3],
["Summarize recent news about the North American tech job market", "command-light",
"fast",
"off", 0.9],
["Give me a rundown of AI startups in the productivity space",
"command-light-nightly",
"fast",
"off", 2]],
title="(Unofficial) Chat with Cohere Coral")
coral_chat.queue()
if __name__ == "__main__":
coral_chat.launch()