Spaces:
Runtime error
Runtime error
File size: 13,884 Bytes
b69c947 | 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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 | from typing import List
from langchain_core.callbacks import CallbackManagerForRetrieverRun
from langchain_core.documents import Document
from langchain_core.retrievers import BaseRetriever
from extract import extract_list
from openai import OpenAI
from pinecone import Pinecone
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain.chains.question_answering import load_qa_chain
from langchain.memory import ConversationBufferMemory
from langchain.prompts import PromptTemplate
import os, json, random
from dotenv import load_dotenv
import gradio as gr
load_dotenv()
openai_api_key = os.getenv("OPENAI_API_KEY")
pinecone_index = os.getenv("PINECONE_INDEX")
pinecone_api_key = os.getenv("PINECONE_API_KEY")
openai_client = OpenAI(api_key=openai_api_key)
practice_list = ', '.join(extract_list())
description = "Extract mediator's practice field that user want to search. Available mediator practice fields are " + practice_list
metadata_list = ['fullname', 'mediator profile on mediate.com', 'mediator Biography', 'mediator state']
metadata_value = ['Name', "Profile", "Biography", "State"]
class MediatorRetriever(BaseRetriever):
def getMetadata(self, message):
tools = [
{
"type": "function",
"name": "get_info",
"description": "Extract the information of mediator.",
"parameters": {
"type": "object",
"properties": {
"mediator country": {
"type": "string",
"description": "Extract mediator's country that user wants to search."
},
"mediator city": {
"type": "string",
"description": "Extract mediator's city that user wants to search."
},
"mediator state": {
"type": "string",
"description": "Extract mediator's state that user wants to search. If both mediator city and mediator state are possible, please extract as mediator state."
},
"mediator areas of practice": {
"type": "array",
"description": description,
"enum": extract_list()
}
}
}
}
]
response = openai_client.chat.completions.create(
model="gpt-4-1106-preview",
messages=[
{"role": "system", "content": "You are a professional mediation field searcher. Your role is to extract information about mediators from user's message. but you have to provide several mediators not one. If there are no mediators in the specific city, then it should return mediators from the state."},
{"role": "user", "content": message}
],
functions=tools,
stream=True
)
new_message = ""
for chunk in response:
delta = chunk.choices[0].delta
if delta and delta.content:
yield {"search_status" : False, "data" : delta.content}
elif delta and delta.function_call:
new_message += delta.function_call.arguments
if new_message:
yield {"search_status" : True, "data" : new_message}
def _get_relevant_documents(self, query: str, *, run_manager: CallbackManagerForRetrieverRun) -> List[Document]:
"""Sync implementations for retriever."""
matching_documents = []
message = ""
metaData = self.getMetadata(query)
for data in metaData:
if data['data'] is None:
break
search_status = data['search_status']
if search_status == True:
metadata = json.loads(data['data'])
practice_data = ""
try:
if 'mediator areas of practice' in metadata:
practice_data = metadata['mediator areas of practice']
del metadata['mediator areas of practice']
elif 'mediator practice field' in metadata:
practice_data = metadata['mediator practice field']
del metadata['mediator practice field']
except:
practice_data = ""
if "mediator city" in metadata:
try:
del metadata['mediator state']
del metadata['mediator country']
except:
pass
if not practice_data:
response = openai_client.chat.completions.create(
model="gpt-4-1106-preview",
messages=[
{"role": "system", "content": "Generate a message asking the user about the conflict to better match them with a mediator."},
{"role": "user", "content": query}
],
stream=True
)
for chunk in response:
delta = chunk.choices[0].delta
if delta and delta.content:
message += delta.content
yield {"message": message}
elif not any(k in metadata for k in ['mediator country', 'mediator state', 'mediator city']):
response = openai_client.chat.completions.create(
model="gpt-4-1106-preview",
messages=[
{"role": "system", "content": "Generate a message asking the user for their location to find mediators in their area."},
{"role": "user", "content": query}
],
stream=True
)
for chunk in response:
delta = chunk.choices[0].delta
if delta and delta.content:
message += delta.content
yield {"message": message}
else:
tools = [
{
"type": "function",
"name": "mediator_search",
"description": "Extract how many mediators the user wants to search.",
"parameters": {
"type": "object",
"properties": {
"mediator": {
"type": "number",
"description": "The number of mediators that the user wants to search. If the user asks for a list of mediators, it means the user wants to search at least 3 mediators. If the user's message doesn't have information about the number of mediators, you have to respond with at least 3.",
"default": 3
}
},
"required": ["mediator"]
}
}
]
response = openai_client.chat.completions.create(
model="gpt-4-1106-preview",
messages=[
{"role": "system", "content": "Please extract how many mediators users want to search."},
{"role": "user", "content": query}
],
functions=tools,
stream=True
)
try:
number_str = response.choices[0].message.tool_calls[0].function.arguments
mediator_num = max(int(json.loads(number_str)['mediator']), 3)
except:
mediator_num = 3
template = """"""
prompt = "You are a professional mediator information analyzer. You have to analyze the following mediators based on the user's message. You shouldn't write the mediator's information again. You shouldn't write the mediators in context as the excellent choice or ideal candidate. You have to analyze the mediators at once. Please respond with no more than 300 characters."
end = """Context: {context}
Chat history: {chat_history}
Human: {human_input}
Your Response as Chatbot:"""
template += prompt + end
prompt = PromptTemplate(
input_variables=["chat_history", "human_input", "context"],
template=template
)
pc = Pinecone(api_key=pinecone_api_key)
embeddings = OpenAIEmbeddings(api_key=openai_api_key)
index = pc.Index(pinecone_index)
results = index.query(
vector=embeddings.embed_query(query),
top_k=5,
filter=metadata,
include_metadata=True
)
if (not results['matches']) and 'mediator state' in metadata:
del metadata['mediator city']
results = index.query(
vector=embeddings.embed_query(query),
top_k=5,
filter=metadata,
include_metadata=True
)
new_data = []
for result in results['matches']:
data = {}
for metadata_key in metadata_list:
data[metadata_key] = result['metadata'].get(metadata_key, "N/A")
if practice_data in result['metadata'].get('mediator areas of practice', []):
new_data.append(data)
random.shuffle(new_data)
if new_data:
if practice_data and mediator_num == 1:
message += f"I have located a mediator who specializes in {practice_data}. Here are their details:\n\n"
elif practice_data and mediator_num > 1:
message += f"I have located mediators who specialize in {practice_data}. Here are their details:\n\n"
elif not practice_data and mediator_num == 1:
message += f"I have located a mediator. Here are their details:\n\n"
elif not practice_data and mediator_num > 1:
message += f"I have located mediators. Here are their details:\n\n"
for index, new_datum in enumerate(new_data):
if index < mediator_num:
content = ""
for metadata_index, metadata_key in enumerate(metadata_list):
value = new_datum[metadata_key]
content += f"<b>{metadata_value[metadata_index]}</b>: {value if value else 'N/A'} \n"
message += f"<b>{metadata_value[metadata_index]}</b>: {value if value else 'N/A'} \n"
message += "\n\n"
new_doc = Document(page_content=content)
matching_documents.append(new_doc)
else:
break
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
chat_openai = ChatOpenAI(temperature=0, openai_api_key=openai_api_key)
chain = load_qa_chain(chat_openai, chain_type="stuff", memory=memory, prompt=prompt)
search_result = chain.run(input_documents=matching_documents, human_input=query)
message += search_result
yield {"documents": matching_documents, "message": message}
else:
message += data['data']
yield {"documents": matching_documents, "message": message}
retriever = MediatorRetriever()
def search(query, history):
try:
response = retriever.stream({"input": query, "chat_history": history})
for chunks in response:
for chunk in chunks:
if 'documents' in chunk:
history.extend([{"role": "user", "content": query}, {"role": "assistant", "content": chunk['message']}])
yield chunk['message']
except StopAsyncIteration:
print("Async iteration ended unexpectedly")
except Exception as e:
print(f"An error occurred: {e}")
yield f"An error occurred: {e}"
with gr.Blocks() as demo:
chatbot = gr.Chatbot()
msg = gr.Textbox()
clear = gr.Button("Clear")
history = gr.State([])
def respond(message, chat_history):
chat_history = chat_history or []
bot_message = search(message, chat_history)
chat_history.append((message, bot_message))
return "", chat_history
msg.submit(respond, [msg, history], [msg, chatbot])
clear.click(lambda: None, None, chatbot, queue=False)
demo.launch() |