Spaces:
Running
Running
File size: 1,243 Bytes
0c94c61 22be37d 98eaa40 22be37d 0c94c61 22be37d 0c94c61 98eaa40 22be37d |
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 |
"""
GPT Related Functions
"""
from typing import List, Dict, Generator
import cohere
from utils.format import format_chat_history_cohere
def test_api_key(api_key: str):
"""Function to test Cohere API is working"""
try:
# try to just generate 3 tokens
co = cohere.Client(
api_key=api_key,
)
response = co.generate(prompt="sample prompt", max_tokens=3)
return True
except:
return False
def stream(
background_info: str, chat_history: List[Dict[str, str]] = [], api_key: str = ""
) -> Generator:
"""Get response from Cohere and stream response"""
co = cohere.Client(
api_key=api_key,
)
cohere_history = format_chat_history_cohere(chat_history, background_info)
stream = co.chat_stream(
chat_history=cohere_history[:-1], message=cohere_history[-1]["message"]
)
for event in stream:
if event.event_type == "text-generation":
yield event.text
def gpt_response(prompt: str, api_key: str) -> str:
"""Get response from Cohere, with option to get output in json format"""
co = cohere.Client(
api_key=api_key,
)
response = co.chat(message=prompt)
return response.text
|