import os import gradio as gr from langchain_core.prompts import PromptTemplate from langchain_community.document_loaders import PyPDFLoader from langchain_google_genai import ChatGoogleGenerativeAI import google.generativeai as genai from langchain.chains.question_answering import load_qa_chain import torch from transformers import AutoTokenizer, AutoModelForCausalLM from PIL import Image import io # Configure Gemini API genai.configure(api_key=os.getenv("GOOGLE_API_KEY")) # Load models model_path_mistral = "nvidia/Mistral-NeMo-Minitron-8B-Base" mistral_tokenizer = AutoTokenizer.from_pretrained(model_path_mistral) device = 'cuda' if torch.cuda.is_available() else 'cpu' dtype = torch.bfloat16 mistral_model = AutoModelForCausalLM.from_pretrained(model_path_mistral, torch_dtype=dtype, device_map=device) openelm_270m_instruct = AutoModelForCausalLM.from_pretrained("apple/OpenELM-1_1B", trust_remote_code=True) tokenizer = AutoTokenizer.from_pretrained("NousResearch/Llama-2-7b-hf") # 替代的LangSmith評估函數 def evaluate_with_langsmith(text): score = len(text.split()) # 根據生成文本的字數評分 return f"Score: {score}" def process_pdf(file_path, question): model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3) prompt_template = """Answer the question as precise as possible using the provided context. If the answer is not contained in the context, say "answer not available in context" \n\n Context: \n {context}?\n Question: \n {question} \n Answer: """ prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"]) pdf_loader = PyPDFLoader(file_path) pages = pdf_loader.load_and_split() context = "\n".join(str(page.page_content) for page in pages[:200]) stuff_chain = load_qa_chain(model, chain_type="stuff", prompt=prompt) stuff_answer = stuff_chain({"input_documents": pages, "question": question, "context": context}, return_only_outputs=True) return stuff_answer['output_text'] def process_image(image, question): model = genai.GenerativeModel('gemini-pro-vision') response = model.generate_content([image, question]) return response.text def generate_mistral_followup(answer): mistral_prompt = f"Based on this answer: {answer}\nGenerate a follow-up question:" mistral_inputs = mistral_tokenizer.encode(mistral_prompt, return_tensors='pt').to(device) with torch.no_grad(): mistral_outputs = mistral_model.generate(mistral_inputs, max_length=200) mistral_output = mistral_tokenizer.decode(mistral_outputs[0], skip_special_tokens=True) return mistral_output def generate(newQuestion, num): tokenized_prompt = tokenizer(newQuestion) tokenized_prompt = torch.tensor(tokenized_prompt['input_ids']).unsqueeze(0) output_ids = openelm_270m_instruct.generate(tokenized_prompt, max_length=int(num), pad_token_id=0) output_text = tokenizer.decode(output_ids[0].tolist(), skip_special_tokens=True) return output_text def process_input(file, image, question, gen_length): try: if file is not None: gemini_answer = process_pdf(file.name, question) elif image is not None: gemini_answer = process_image(image, question) else: return "Please upload a PDF file or an image." mistral_followup = generate_mistral_followup(gemini_answer) openelm_response = generate(question, gen_length) langsmith_score = evaluate_with_langsmith(openelm_response) combined_output = f"Gemini Answer: {gemini_answer}\n\nMistral Follow-up: {mistral_followup}\n\nOpenELM Response: {openelm_response}\n\nLangSmith Score: {langsmith_score}" return combined_output except Exception as e: return f"An error occurred: {str(e)}" # Define Gradio Interface with gr.Blocks() as demo: gr.Markdown("# Multi-modal RAG Knowledge Retrieval using Gemini API, Mistral, OpenELM, and LangSmith") with gr.Row(): with gr.Column(): input_file = gr.File(label="Upload PDF File") input_image = gr.Image(type="pil", label="Upload Image") input_question = gr.Textbox(label="Ask about the document or image") input_gen_length = gr.Textbox(label="Number of generated tokens", value="50") output_text = gr.Textbox(label="Answer - Combined Outputs with LangSmith Evaluation") submit_button = gr.Button("Submit") submit_button.click(fn=process_input, inputs=[input_file, input_image, input_question, input_gen_length], outputs=output_text) demo.launch()