File size: 7,008 Bytes
0123ece
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc8ad2d
 
 
 
 
 
 
0123ece
 
 
 
 
 
cc8ad2d
 
 
 
0123ece
cc8ad2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0123ece
 
 
 
 
cc8ad2d
 
 
 
 
676c678
cc8ad2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0123ece
cc8ad2d
 
 
 
 
 
 
 
 
 
 
676c678
cc8ad2d
 
 
676c678
cc8ad2d
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
# import gradio as gr
# from langchain.prompts import PromptTemplate
# from langchain_community.llms import CTransformers
# from langchain_community.vectorstores import Pinecone as LangchainPinecone
# from langchain.chains import RetrievalQA
# from pinecone import Pinecone
# from dotenv import load_dotenv
# import os

# # Load environment variables
# load_dotenv()
# PINECONE_API_KEY = os.getenv('PINECONE_API_KEY')
# index_name = "apple-chatbot"

# class AppleChatbot:
#     def __init__(self, k=2, max_tokens=512, temperature=0.8):
#         self.k = k
#         self.max_tokens = max_tokens
#         self.temperature = temperature
#         self.qa_chain = self.initialize_chatbot()

#     def download_hf_embeddings(self):
#         from langchain_community.embeddings import HuggingFaceEmbeddings
#         return HuggingFaceEmbeddings()

#     def initialize_chatbot(self):
#         embeddings = self.download_hf_embeddings()
#         model_path = "TheBloke/Llama-2-7B-Chat-GGML"
#         llm = CTransformers(
#             model=model_path,
#             model_type="llama",
#             config={
#                 'max_new_tokens': self.max_tokens,
#                 'temperature': self.temperature
#             }
#         )
        
#         # Initialize pinecone
#         pc = Pinecone(api_key=PINECONE_API_KEY)
#         index = pc.Index(index_name)

#         # Use the same prompt template from your original application
#         prompt_template = """
#         You are an expert in apple cultivation and orchard management. Use the following pieces of context to answer the question at the end.
#         If you don't know the answer, just say that you don't know, don't try to make up an answer.
#         {context}
#         Question: {question}
#         Answer:"""
#         PROMPT = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
#         chain_type_kwargs = {"prompt": PROMPT}
        
#         docsearch = LangchainPinecone(index, embeddings.embed_query, "text")
#         qa = RetrievalQA.from_chain_type(
#             llm=llm,
#             chain_type="stuff",
#             retriever=docsearch.as_retriever(search_kwargs={'k': self.k}),
#             return_source_documents=True,
#             chain_type_kwargs=chain_type_kwargs
#         )
#         return qa

#     def get_response(self, question):
#         try:
#             result = self.qa_chain({"query": question})
#             return result["result"]
#         except Exception as e:
#             return f"Error: {str(e)}"

# # Initialize the chatbot
# chatbot = AppleChatbot()

# # Define the Gradio interface
# def respond(message, history):
#     response = chatbot.get_response(message)
#     return response

# # Create the Gradio interface
# demo = gr.ChatInterface(
#     respond,
#     chatbot=gr.Chatbot(height=600),
#     textbox=gr.Textbox(placeholder="Ask me anything about apple cultivation...", container=False),
#     title="Apple Orchard Expert Chatbot",
#     description="Ask questions about apple cultivation and orchard management. Built with Langchain, Pinecone, and Llama-2.",
#     theme=gr.themes.Soft(),
#     examples=[
#         "What are the ideal conditions for growing apples?",
#         "How do I prevent common apple diseases?",
#         "What is the best time to harvest apples?",
#     ],
#     cache_examples=False,
# )

# # Launch the interface
# if __name__ == "__main__":
#     demo.queue()  # Enable queuing
#     demo.launch(
#         server_name="0.0.0.0",
#         server_port=7860,
#         share=True
#     )


import gradio as gr
from langchain.prompts import PromptTemplate
from langchain_community.vectorstores import Pinecone as LangchainPinecone
from langchain.chains import RetrievalQA
from pinecone import Pinecone
from dotenv import load_dotenv
import os
import google.generativeai as genai
import logging

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Load environment variables
load_dotenv()
PINECONE_API_KEY = os.getenv('PINECONE_API_KEY')
GEMINI_API_KEY = os.getenv('GEMINI_API_KEY')
index_name = "apple-chatbot"

class AppleChatbot:
    def __init__(self, k=2, max_tokens=512, temperature=0.8):
        self.k = k
        self.max_tokens = max_tokens
        self.temperature = temperature
        self.qa_chain = self.initialize_chatbot()

    def download_hf_embeddings(self):
        from langchain_community.embeddings import HuggingFaceEmbeddings
        return HuggingFaceEmbeddings()

    def initialize_chatbot(self):
        embeddings = self.download_hf_embeddings()
        
        # Initialize Gemini
        genai.configure(api_key=GEMINI_API_KEY)
        llm = genai.GenerativeModel('gemini-pro')
        
        # Initialize Pinecone
        pc = Pinecone(api_key=PINECONE_API_KEY)
        index = pc.Index(index_name)

        # Use the same prompt template from your original application
        prompt_template = """
        You are an expert in apple cultivation and orchard management. Use the following pieces of context to answer the question at the end.
        If you don't know the answer, just say that you don't know, don't try to make up an answer.
        {context}
        Question: {question}
        Answer:"""
        PROMPT = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
        chain_type_kwargs = {"prompt": PROMPT}
        
        docsearch = LangchainPinecone(index, embeddings.embed_query, "text")
        qa = RetrievalQA.from_chain_type(
            llm=llm,
            chain_type="stuff",
            retriever=docsearch.as_retriever(search_kwargs={'k': self.k}),
            return_source_documents=True,
            chain_type_kwargs=chain_type_kwargs
        )
        return qa

    def get_response(self, question):
        try:
            result = self.qa_chain({"query": question})
            return result["result"]
        except Exception as e:
            return f"Error: {str(e)}"

# Initialize the chatbot
chatbot = AppleChatbot()

# Define the Gradio interface
def respond(message, history):
    response = chatbot.get_response(message)
    return response

# Create the Gradio interface
demo = gr.ChatInterface(
    respond,
    chatbot=gr.Chatbot(height=600),
    textbox=gr.Textbox(placeholder="Ask me anything about apple cultivation...", container=False),
    title="Apple Orchard Expert Chatbot",
    description="Ask questions about apple cultivation and orchard management. Built with Langchain, Pinecone, and Gemini.",
    theme=gr.themes.Soft(),
    examples=[
        "What are the ideal conditions for growing apples?",
        "How do I prevent common apple diseases?",
        "What is the best time to harvest apples?",
    ],
    cache_examples=False,
)

# Launch the interface
if __name__ == "__main__":
    demo.queue()  # Enable queuing
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=True
    )