File size: 2,494 Bytes
647f8d8 | 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 | 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)
|