Spaces:
Running
Running
File size: 8,879 Bytes
3be4504 e97a3af 3be4504 c171781 3be4504 a8eed7c 3be4504 a8eed7c 3be4504 c171781 3be4504 80c79bc 6d565bf 3be4504 a858144 3be4504 a858144 3be4504 a858144 3be4504 a858144 3be4504 a858144 3be4504 a858144 3be4504 |
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 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 |
import os
from langchain_core.prompts import ChatPromptTemplate
from langsmith import Client, traceable
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langsmith import Client, traceable
from langchain_core.output_parsers import StrOutputParser
from langchain_nomic.embeddings import NomicEmbeddings
from langchain_groq import ChatGroq
from dotenv import load_dotenv
load_dotenv()
GROQ_API_KEY = os.getenv('GROQ_API_KEY')
HF_API_KEY = os.getenv("HF_API_KEY")
#LANGSMITH_TRACING="true"
#LANGSMITH_ENDPOINT="https://api.smith.langchain.com"
#LANGSMITH_API_KEY=os.getenv("LANGSMITH_API_KEY")
#LANGSMITH_PROJECT="pr-internal-hand-91"
model_name="llama-3.1-70b-versatile"
llm = ChatGroq(
temperature=0,
model= "llama-3.3-70b-versatile", #"llama3-70b-8192",
api_key=GROQ_API_KEY,
verbose= True,
max_retries=2,
)
#@traceable
def get_answer(question):
prompt = ChatPromptTemplate.from_messages([
("system", """You are an AI assistant designed to help hydroponic farmers optimize their systems, troubleshoot issues, and improve crop yields. You have access to real-time and historical data from the hydroponic system, including pH, EC, temperature, humidity, light levels, dissolved oxygen, and nutrient concentrations. Your goal is to provide actionable recommendations, answer questions, and explain concepts in simple terms.
Instructions:
Understand the Context: The farmer is managing a hydroponic system and has access to sensor data. They may ask for advice on optimizing parameters, diagnosing problems, or improving crop health.
Use Data: When answering questions, refer to the available data (e.g., pH, EC, temperature) to provide specific, data-driven recommendations.
Be Proactive: Suggest improvements or warn about potential issues even if not explicitly asked (e.g., "Your pH level is trending high, which could affect nutrient uptake. Consider adjusting it to 5.8–6.2.").
Explain Clearly: Use simple language and avoid overly technical jargon unless the farmer asks for detailed explanations.
Provide Step-by-Step Guidance: If the farmer needs to take action, break it down into clear, actionable steps.
Be Polite and Supportive: Act as a friendly and knowledgeable partner, not just a tool.
Example Questions and Answers
1. General Optimization
Farmer: "How can I improve the growth of my lettuce?"
AI: "Based on your current data, your pH is at 6.8, which is slightly high for lettuce. Lettuce thrives in a pH range of 5.5–6.5. I recommend lowering the pH to 6.0 using a pH-down solution. Additionally, your EC is at 1.8 mS/cm, which is good, but you could increase it to 2.0–2.4 mS/cm during the growth stage for better results. Lastly, ensure your light levels are at least 200–300 µmol/m²/s for 14–16 hours a day."
2. Troubleshooting
Farmer: "My plants are wilting. What’s wrong?"
AI: "Let’s check your data. Your dissolved oxygen level is at 4 mg/L, which is below the optimal range of 5–8 mg/L for healthy roots. Low oxygen levels can cause wilting. I recommend increasing aeration in your nutrient solution. Also, your temperature is at 28°C, which is slightly high. Try lowering it to 22–25°C to reduce stress on the plants."
3. Disease Prevention
Farmer: "How can I prevent root rot?"
AI: "Root rot is often caused by poor oxygenation or high pathogen levels in the water. Your dissolved oxygen is at 5.5 mg/L, which is acceptable, but your water temperature is at 26°C, which is on the higher side. Lower the temperature to 20–22°C to reduce the risk. Additionally, ensure your EC is within the optimal range (1.8–2.2 mS/cm for most plants) to avoid nutrient imbalances that can weaken plants."
4. Real-Time Adjustments
Farmer: "What should I adjust right now?"
AI: "Looking at your real-time data:
pH: 7.2 (too high for most plants; adjust to 5.8–6.2).
EC: 1.5 mS/cm (slightly low; increase to 1.8–2.2 mS/cm).
Temperature: 24°C (optimal; no change needed).
Light: 150 µmol/m²/s (increase to 200–300 µmol/m²/s for better growth).
I recommend adding pH-down solution and increasing nutrient concentration. Also, check your light source to ensure it’s providing enough intensity."
5. Educational Questions
Farmer: "Why is pH important in hydroponics?"
AI: "pH is crucial because it affects nutrient availability. If the pH is too high or too low, plants can’t absorb certain nutrients, even if they’re present in the solution. For example, iron becomes less available at high pH levels, leading to deficiencies. Most plants prefer a pH range of 5.5–6.5 for optimal nutrient uptake.and here is some facts: {facts}"""),
("user", "{question}")
])
chain = prompt | llm
parser = StrOutputParser()
chain = prompt | llm | parser
answer= chain.invoke({"question": question, "facts": fake_db_retrieval()})
return answer
embedding_model = NomicEmbeddings(model="nomic-embed-text-v1.5", inference_mode="local")
db = "db1"
from langchain.vectorstores import Chroma
vector_store = Chroma(
collection_name="chromadb3",
persist_directory=db,
embedding_function=embedding_model,
)
from langchain.chains.conversation.memory import ConversationBufferWindowMemory
from langchain.chains import RetrievalQA
conversational_memory = ConversationBufferWindowMemory(
memory_key='chat_history',
k=5, #Number of messages stored in memory
return_messages=True #Must return the messages in the response.
)
qa = RetrievalQA.from_chain_type(
llm=llm,
chain_type="stuff",
retriever=vector_store.as_retriever(k=5)
)
from langchain.agents import Tool
#Defining the list of tool objects to be used by LangChain.
tools = [
Tool(
name='Hydroponic Knowledge database',
func=qa.run,
description=(
'use this tool when answering Hydroponic knowledge queries to get '
'more information about the topic'
)
)
]
from langchain.agents import create_react_agent
from langchain import hub
prompt = hub.pull("hwchase17/react-chat")
agent = create_react_agent(
tools=tools,
llm=llm,
prompt=prompt,
)
# Create an agent executor by passing in the agent and tools
from langchain.agents import AgentExecutor
agent_executor = AgentExecutor(agent=agent,
tools=tools,
verbose=True,
memory=conversational_memory,
max_iterations=30,
max_execution_time=600,
#early_stopping_method='generate',
handle_parsing_errors=True
)
# Function for continuing the conversation
import streamlit as st
# Function for continuing the conversation
def continue_conversation(input, history):
# Invoke the agent and get the response
response = agent_executor.invoke({"input": input})
output = response['output']
# Prepend the new input and output to the history (latest conversation comes first)
history.insert(0, {"role": "Patient", "message": input})
history.insert(0, {"role": "Doctor", "message": output})
# Return the current response and the full history (hidden state)
return output, history
# Streamlit UI
def main():
st.set_page_config(page_title="Hydroponic AI Chatbot", page_icon="👨⚕️")
st.title("Medical Chatbot")
# Initialize the conversation history
if 'history' not in st.session_state:
st.session_state.history = []
# Sidebar for memory display
with st.sidebar:
st.header("Conversation History")
st.write("This section contains the conversation history.")
# Create a container for the chat
chat_container = st.container()
# Display the chat history with the latest conversation at the top
for chat in st.session_state.history:
if chat['role'] == 'Patient':
chat_container.markdown(f"**Agricultor:** {chat['message']}")
else:
chat_container.markdown(f"**Hydroponic AI Assistant:** {chat['message']}")
# User input text box at the bottom
user_input = st.text_input("Ask a question:", key="input", placeholder="Tell me what do you want to know ?")
if user_input:
# Get the response and update the conversation history
output, updated_history = continue_conversation(user_input, st.session_state.history)
# Update the session state with the new history
st.session_state.history = updated_history
# Display memory of past conversation in an expandable section
with st.expander("Memory", expanded=True):
for chat in st.session_state.history:
st.write(f"**{chat['role']}:** {chat['message']}")
if __name__ == "__main__":
main()
|