pratikshahp commited on
Commit
5ad3e74
·
verified ·
1 Parent(s): 5d13aef

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +84 -0
app.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from openai import OpenAI
3
+ import os
4
+ import numpy as np
5
+ from sklearn.metrics.pairwise import cosine_similarity
6
+ from dotenv import load_dotenv
7
+
8
+ # Load environment variables
9
+ load_dotenv()
10
+
11
+ # Set up OpenAI API key
12
+ api_key = os.getenv("OPENAI_API_KEY") # Ensure your OpenAI API key is stored in the .env file
13
+ client = OpenAI(api_key=api_key)
14
+
15
+ # Define the paragraph as a global variable
16
+ paragraph = (
17
+ "Artificial Intelligence (AI) refers to the simulation of human intelligence in machines that are programmed to think and learn like humans. AI systems can perform tasks such as recognizing speech, understanding natural language, making decisions, and identifying patterns. These systems are powered by algorithms and vast amounts of data, enabling them to improve their performance over time. AI has a wide range of applications, including autonomous vehicles, medical diagnostics, customer service, and more. As AI continues to evolve, it holds the potential to revolutionize industries and change the way humans interact with technology."
18
+ "Machine Learning (ML) is a subset of Artificial Intelligence that focuses on the development of algorithms that allow computers to learn from and make predictions or decisions based on data. Unlike traditional programming, where a developer explicitly tells the computer how to perform tasks, ML algorithms improve their performance by analyzing patterns and making adjustments without human intervention. ML is widely used in applications such as recommendation systems, fraud detection, image recognition, and natural language processing. The field continues to grow rapidly, driven by advancements in computational power, data availability, and algorithmic improvements."
19
+ )
20
+
21
+ # Function to generate embeddings
22
+ def get_embeddings(text):
23
+ response = client.embeddings.create(
24
+ input=text,
25
+ model="text-embedding-ada-002" # Using a more efficient embedding model
26
+ )
27
+ return np.array(response.data[0].embedding)
28
+
29
+ # Function to retrieve relevant part of the paragraph based on the query
30
+ def retrieve_relevant_paragraph(paragraph, question):
31
+ # Get the embeddings of the paragraph and question
32
+ paragraph_embedding = get_embeddings(paragraph)
33
+ question_embedding = get_embeddings(question)
34
+
35
+ # Compute cosine similarity between the paragraph and question embeddings
36
+ similarity = cosine_similarity([question_embedding], [paragraph_embedding])[0][0]
37
+
38
+ # Return the similarity score (you can use this to decide how relevant the paragraph is)
39
+ if similarity > 0.7:
40
+ return paragraph # If the paragraph is relevant enough, return the full paragraph
41
+ else:
42
+ return "The question does not match the paragraph well enough."
43
+
44
+ # Function to generate response from OpenAI based on the context
45
+ def generate_response(question):
46
+ relevant_paragraph = retrieve_relevant_paragraph(paragraph, question)
47
+ print(relevant_paragraph)
48
+ if relevant_paragraph == "The question does not match the paragraph well enough.":
49
+ return relevant_paragraph
50
+ else:
51
+ try:
52
+ response = client.chat.completions.create(
53
+ model="gpt-4o-mini",
54
+ messages=[
55
+ {"role": "system", "content": "You are a helpful assistant. Answer questions based on the provided paragraph in 30 words."},
56
+ {"role": "user", "content": f"Here is the paragraph: {relevant_paragraph}\n\nQuestion: {question}"}
57
+ ]
58
+ )
59
+ # Extract the response
60
+ return response.choices[0].message.content.strip()
61
+ except Exception as e:
62
+ return f"Error: {e}"
63
+
64
+ # Gradio app
65
+ with gr.Blocks() as app:
66
+ gr.Markdown("# Chat with a Paragraph 📄🤖")
67
+
68
+ # Display the paragraph stored in the global variable
69
+ gr.Markdown(f"### Paragraph: \n{paragraph}")
70
+
71
+ # User input for the question
72
+ question = gr.Textbox(label="Ask a Question", placeholder="Ask a question about the paragraph...")
73
+
74
+ # Button to trigger the response generation
75
+ submit_button = gr.Button("Get Answer")
76
+
77
+ # Output text area for the response
78
+ answer = gr.Textbox(label="Answer", interactive=False)
79
+
80
+ # Define the button click behavior
81
+ submit_button.click(generate_response, inputs=[question], outputs=answer)
82
+
83
+ # Launch the Gradio app
84
+ app.launch()