Download chat.py from zhyiyang/chatonco: direct link, hf CLI and curl.
- Browser
- Download file 2.49 kB
-
https://huggingface.co/zhyiyang/chatonco/resolve/main/chat.py
- Command line
-
hf download hf://zhyiyang/chatonco/chat.py
-
curl -L -o chat.py https://huggingface.co/zhyiyang/chatonco/resolve/main/chat.py
2.49 kB
| import os | |
| from langchain.embeddings.openai import OpenAIEmbeddings | |
| from langchain.vectorstores import Chroma | |
| from langchain.document_loaders import TextLoader | |
| from langchain.chains.question_answering import load_qa_chain | |
| from langchain.chat_models import ChatOpenAI | |
| from langchain.prompts import PromptTemplate | |
| os.environ["OPENAI_API_KEY"] = "" | |
| global retriever | |
| def load_embedding(persist_directory): | |
| embedding = OpenAIEmbeddings() | |
| global retriever | |
| vectordb = Chroma(persist_directory=persist_directory, embedding_function=embedding) | |
| retriever = vectordb.as_retriever(search_kwargs={"k": 3}) | |
| # 指定模型 | |
| turbo_llm = ChatOpenAI( | |
| temperature=0, | |
| model_name='gpt-3.5-turbo' | |
| ) | |
| four_llm = ChatOpenAI( | |
| temperature=0, | |
| model_name='gpt-4' | |
| ) | |
| def prompt(query, model): | |
| prompt_template = """Please note: Please carefully assess the relevance of the query and the context information provided in the prompt. Only answer based on the input text information in this paragraph. If the query is unrelated to the provided material, please answer "I don't know". Also, do not answer unrelated answers. | |
| Context: {context} | |
| Question: {question} | |
| Answer:""" | |
| PROMPT = PromptTemplate( | |
| template=prompt_template, input_variables=["context", "question"] | |
| ) | |
| docs = retriever.get_relevant_documents(query) | |
| if model == 1: | |
| llm = turbo_llm | |
| elif model == 2: | |
| llm = four_llm | |
| # 基于docs来prompt,返回你想要的内容 | |
| chain = load_qa_chain(llm, chain_type="stuff", prompt=PROMPT) | |
| # prompt = chain.get_prompt({"context": docs, "question": query}) | |
| result = chain({"input_documents": docs, "question": query}) | |
| # return result['output_text'] | |
| return result | |
| def process_llm_response(llm_response): | |
| print(llm_response['output_text']) | |
| print('\n\nSources:') | |
| for source in llm_response["input_documents"]: | |
| print(source.metadata['source']) | |
| if __name__ == "__main__": | |
| persist_directory = './db' | |
| # load embedding | |
| load_embedding(persist_directory) | |
| # query = "Given that standard fractionated radiation therapy may provide limited benefit for breast cancer due to the similar a/b ratios of tumor and normal tissue, do SBRT and hypofractionated radiation therapy represent better approaches?" | |
| query = "What types of bridging treatments are available for HCC patients on the liver transplant waitlist? " | |
| llm_response = prompt(query,1) | |
| process_llm_response(llm_response) | |