Spaces:
Runtime error
Runtime error
File size: 10,833 Bytes
98ad3a1 e5e6ba2 fbb9428 98ad3a1 0209368 fbb9428 98ad3a1 f908aec fbb9428 e5e6ba2 fbb9428 5460a4a b1d8650 5460a4a baca904 fbb9428 98ad3a1 ebb6bdc 98ad3a1 e8d518e 98ad3a1 e8d518e 98ad3a1 6e5318d f908aec fbb9428 e5e6ba2 a949598 e5e6ba2 de42c12 e5e6ba2 f908aec 8c3956a f908aec 8c3956a 009c740 8c3956a f908aec 8c3956a e5e6ba2 e6376d0 e5e6ba2 a949598 e5e6ba2 718fa4c e5e6ba2 0209368 f908aec 5460a4a 74c9c64 d80c981 0209368 459baae 0209368 e5e6ba2 009c740 e5e6ba2 b3dae47 e5e6ba2 9b21883 f87e37d e5e6ba2 9b21883 d80c981 f87e37d e5e6ba2 fbb9428 4e238ad 8eaf49f e5e6ba2 d4b40f3 e5e6ba2 ba05602 e5e6ba2 7944fcb b3dae47 e5e6ba2 f439b59 e5e6ba2 de42c12 e5e6ba2 |
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 296 297 298 |
# from typing import Any, Coroutine
import openai
import os
from langchain.vectorstores import Chroma
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from langchain.chat_models import AzureChatOpenAI
from langchain.document_loaders import DirectoryLoader
from langchain.chains import RetrievalQA
from langchain.vectorstores import Pinecone
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.agents import Tool
# from langchain.agents import load_tools
from langchain.tools import BaseTool
from langchain.tools import DuckDuckGoSearchRun
from langchain.utilities import WikipediaAPIWrapper
from langchain.python import PythonREPL
from langchain.chains import LLMMathChain
import pinecone
from pinecone.core.client.configuration import Configuration as OpenApiConfiguration
import gradio as gr
import time
class DB_Search(BaseTool):
name = "Vector Database Search"
description = "This is the internal database to search information firstly. If information is found, it is trustful."
def _run(self, query: str) -> str:
response, source = QAQuery_p(query)
# response = "test db_search feedback"
return response
def _arun(self, query: str):
raise NotImplementedError("N/A")
Wikipedia = WikipediaAPIWrapper()
Netsearch = DuckDuckGoSearchRun()
Python_REPL = PythonREPL()
wikipedia_tool = Tool(
name = "Wikipedia Search",
func = Wikipedia.run,
description = "Useful to search a topic, country or person when there is no availble information in vector database"
)
duckduckgo_tool = Tool(
name = "Duckduckgo Internet Search",
func = Netsearch.run,
description = "Useful to search information in internet when it is not available in other tools"
)
python_tool = Tool(
name = "Python REPL",
func = Python_REPL.run,
description = "Useful when you need python to answer questions. You should input python code."
)
# tools = [DB_Search(), wikipedia_tool, duckduckgo_tool, python_tool]
os.environ["OPENAI_API_TYPE"] = "azure"
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
os.environ["OPENAI_API_BASE"] = os.getenv("OPENAI_API_BASE")
os.environ["OPENAI_API_VERSION"] = "2023-05-15"
username = os.getenv("username")
password = os.getenv("password")
SysLock = os.getenv("SysLock") # 0=unlock 1=lock
chat = AzureChatOpenAI(
deployment_name="Chattester",
temperature=0,
)
llm = chat
llm_math = LLMMathChain.from_llm(llm)
math_tool = Tool(
name ='Calculator',
func = llm_math.run,
description ='Useful for when you need to answer questions about math.'
)
tools = [DB_Search(), duckduckgo_tool, python_tool, math_tool]
# tools = load_tools(["Vector Database Search","Wikipedia Search","Python REPL","llm-math"], llm=llm)
embeddings = OpenAIEmbeddings(deployment="model_embedding", chunk_size=15)
pinecone.init(
api_key = os.getenv("pinecone_api_key"),
environment='asia-southeast1-gcp-free',
# openapi_config=openapi_config
)
index_name = 'stla-baby'
index = pinecone.Index(index_name)
# index.delete(delete_all=True, namespace='')
# print(pinecone.whoami())
# print(index.describe_index_stats())
PREFIX = """Answer the following questions as best you can. You must always check internal vector database first and try to answer the question based on the information in internal vector database only.
Only when there is no information available from vector database, you can search information by using another tools.
You have access to the following tools:
Vector Database Search: This is the internal database to search information firstly. If information is found, it is trustful.
Duckduckgo Internet Search: Useful to search information in internet when it is not available in other tools
Python REPL: Useful when you need python to answer questions. You should input python code.
Calculator: Useful for when you need to answer questions about math."""
FORMAT_INSTRUCTIONS = """Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [Vector Database Search, Duckduckgo Internet Search, Python REPL, Calculator]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question"""
SUFFIX = """Begin!
Question: {input}
Thought:{agent_scratchpad}"""
agent = initialize_agent(tools, llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose = True,
handle_parsing_errors = True,
max_iterations = int(os.getenv("max_iterations")),
early_stopping_method="generate",
agent_kwargs={
'prefix': PREFIX,
'format_instructions': FORMAT_INSTRUCTIONS,
'suffix': SUFFIX
}
)
print(agent.agent.llm_chain.prompt.template)
global vectordb
vectordb = Chroma(persist_directory='db', embedding_function=embeddings)
global vectordb_p
vectordb_p = Pinecone.from_existing_index(index_name, embeddings)
# loader = DirectoryLoader('./documents', glob='**/*.txt')
# documents = loader.load()
# text_splitter = CharacterTextSplitter(chunk_size=500, chunk_overlap=200)
# split_docs = text_splitter.split_documents(documents)
# print(split_docs)
# vectordb = Chroma.from_documents(split_docs, embeddings, persist_directory='db')
# question = "what is LCDV ?"
# rr = vectordb.similarity_search(query=question, k=4)
# vectordb.similarity_search(question)
# print(type(rr))
# print(rr)
def chathmi(message, history):
# response = "I don't know"
# print(message)
response, source = QAQuery_p(message)
time.sleep(0.3)
print(history)
yield response
# yield history
def chathmi2(message, history):
try:
output = agent.run(message)
time.sleep(0.3)
print("History: ", history)
response = output
yield response
except Exception as e:
print("error:", e)
# yield history
# chatbot = gr.Chatbot().style(color_map =("blue", "pink"))
# chatbot = gr.Chatbot(color_map =("blue", "pink"))
demo = gr.ChatInterface(
chathmi2,
title="STLA BABY - YOUR FRIENDLY GUIDE ",
description= "v0.2: Powered by MECH Core Team",
)
# demo = gr.Interface(
# chathmi,
# ["text", "state"],
# [chatbot, "state"],
# allow_flagging="never",
# )
def CreatDb_P():
global vectordb_p
index_name = 'stla-baby'
loader = DirectoryLoader('./documents', glob='**/*.txt')
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=500, chunk_overlap=200)
split_docs = text_splitter.split_documents(documents)
print(split_docs)
pinecone.Index(index_name).delete(delete_all=True, namespace='')
vectordb_p = Pinecone.from_documents(split_docs, embeddings, index_name = "stla-baby")
print("Pinecone Updated Done")
print(index.describe_index_stats())
def QAQuery_p(question: str):
global vectordb_p
# vectordb = Chroma(persist_directory='db', embedding_function=embeddings)
retriever = vectordb_p.as_retriever()
retriever.search_kwargs['k'] = int(os.getenv("search_kwargs_k"))
# retriever.search_kwargs['fetch_k'] = 100
qa = RetrievalQA.from_chain_type(llm=chat, chain_type="stuff",
retriever=retriever, return_source_documents = True,
verbose = True)
# qa = VectorDBQA.from_chain_type(llm=chat, chain_type="stuff", vectorstore=vectordb, return_source_documents=True)
# res = qa.run(question)
res = qa({"query": question})
print("-" * 20)
print("Question:", question)
# print("Answer:", res)
print("Answer:", res['result'])
print("-" * 20)
print("Source:", res['source_documents'])
response = res['result']
# response = res['source_documents']
source = res['source_documents']
return response, source
def CreatDb():
global vectordb
loader = DirectoryLoader('./documents', glob='**/*.txt')
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=500, chunk_overlap=200)
split_docs = text_splitter.split_documents(documents)
print(split_docs)
vectordb = Chroma.from_documents(split_docs, embeddings, persist_directory='db')
vectordb.persist()
def QAQuery(question: str):
global vectordb
# vectordb = Chroma(persist_directory='db', embedding_function=embeddings)
retriever = vectordb.as_retriever()
retriever.search_kwargs['k'] = 3
# retriever.search_kwargs['fetch_k'] = 100
qa = RetrievalQA.from_chain_type(llm=chat, chain_type="stuff", retriever=retriever, return_source_documents = True)
# qa = VectorDBQA.from_chain_type(llm=chat, chain_type="stuff", vectorstore=vectordb, return_source_documents=True)
# res = qa.run(question)
res = qa({"query": question})
print("-" * 20)
print("Question:", question)
# print("Answer:", res)
print("Answer:", res['result'])
print("-" * 20)
print("Source:", res['source_documents'])
response = res['result']
return response
# Used to complete content
def completeText(Text):
deployment_id="Chattester"
prompt = Text
completion = openai.Completion.create(deployment_id=deployment_id,
prompt=prompt, temperature=0)
print(f"{prompt}{completion['choices'][0]['text']}.")
# Used to chat
def chatText(Text):
deployment_id="Chattester"
conversation = [{"role": "system", "content": "You are a helpful assistant."}]
user_input = Text
conversation.append({"role": "user", "content": user_input})
response = openai.ChatCompletion.create(messages=conversation,
deployment_id="Chattester")
print("\n" + response["choices"][0]["message"]["content"] + "\n")
if __name__ == '__main__':
# chatText("what is AI?")
# CreatDb()
# QAQuery("what is COFOR ?")
# CreatDb_P()
# QAQuery_p("what is GST ?")
if SysLock == "1":
demo.queue().launch(auth=(username, password))
else:
demo.queue().launch()
pass
|