Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dev #1

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ test_venv/
.vscode
hit.py
try.ipynb
db/
db/
data/
22 changes: 8 additions & 14 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,25 +1,19 @@
FROM python:3.9-slim

FROM python:3.12.7-slim-bullseye

WORKDIR /app


COPY requirements.txt .

RUN apt-get update && apt-get install -y libmagic-dev
RUN apt-get update && apt-get install -y \
build-essential \
libmagic-dev \
gcc \
g++ \
&& rm -rf /var/lib/apt/lists/*

RUN pip install --upgrade pip

RUN pip install --no-cache-dir -r requirements.txt


COPY . .


EXPOSE 8000


ENV PORT=8000

# Command to run the application
# CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
CMD ["uvicorn", "api:app", "--host", "0.0.0.0", "--port", "10000"]
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,17 @@ percentage, missing keywords, and profile summary.
- **Starter Code Generation:**
- The starter code generator agent produces starter Python code for the project, including data loading, model definition, and a basic training loop based on the findings from the problem definition, data assessment, and model recommendation.

### 30. Agrilens

- **Route:** `/agrilens`
- **Description:** This API endpoint allows users to upload agricultural images and receive AI-powered insights into crops, pests, diseases, and overall health assessment.
The analysis also includes actionable recommendations for improving agricultural practices and yields.
- **Features:**
- **Image Upload:** Users can upload agricultural images in JPG, JPEG, or PNG formats.
- **Advanced Detection:** Identifies crops, pests, diseases, and farming equipment within the uploaded image.
- **Health Assessment:** Evaluates crop health, identifying stress factors or signs of disease.
- **Smart Recommendations:** Provides actionable insights for enhancing agricultural productivity, such as fertilizer, pesticide, or irrigation advice.

## Usage

Each endpoint accepts specific parameters as described in the respective endpoint documentation. Users can make POST requests to these endpoints with the required parameters to perform the desired tasks.
Expand Down
8 changes: 3 additions & 5 deletions agents/agent_doc/agents.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
from crewai import Agent
from .tools import scrape_tool, search_tool
from langchain_google_genai import ChatGoogleGenerativeAI
import os
import settings

llm=ChatGoogleGenerativeAI(model=settings.GEMINI_FLASH,
verbose=True,
temperature=0.7,
google_api_key=os.getenv("GOOGLE_API_KEY"))
os.environ["GEMINI_API_KEY"] = os.environ.get('GEMINI_API_KEY')

llm = "gemini/gemini-1.5-flash-8b"


diagnostician = Agent(
Expand Down
5 changes: 2 additions & 3 deletions agents/agent_doc/crew.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,12 @@

doc_crew = Crew(
agents=[diagnostician, treatment_advisor],
tasks=[diagnose_task, treatment_task],
verbose=2
tasks=[diagnose_task, treatment_task]
)

def run_doc_crew(input_data):
result = doc_crew.kickoff(inputs=input_data)
return result
return str(result)

if __name__=='__main__':
doc_agent_input ={
Expand Down
8 changes: 3 additions & 5 deletions agents/investment_risk_analyst_agent/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@
from .tools import search_tool,scrape_tool
from dotenv import load_dotenv
load_dotenv()
from langchain_google_genai import ChatGoogleGenerativeAI
import os
import settings

llm=ChatGoogleGenerativeAI(model=settings.GEMINI_FLASH,
verbose=True,
temperature=0.5,
google_api_key=os.getenv("GOOGLE_API_KEY"))
os.environ["GEMINI_API_KEY"] = os.environ.get('GEMINI_API_KEY')

llm = "gemini/gemini-1.5-flash-8b"

data_analyst_agent = Agent(
role="Data Analyst",
Expand Down
9 changes: 4 additions & 5 deletions agents/investment_risk_analyst_agent/crew.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,9 @@
from .agents import data_analyst_agent,trading_strategy_agent,execution_agent,risk_management_agent
from .tasks import data_analysis_task,strategy_development_task,risk_assessment_task,execution_planning_task

llm=ChatGoogleGenerativeAI(model="gemini-1.5-flash-latest",
verbose=True,
temperature=0.7,
google_api_key=os.getenv("GOOGLE_API_KEY"))
os.environ["GEMINI_API_KEY"] = os.environ.get('GEMINI_API_KEY')

llm = "gemini/gemini-1.5-flash-8b"


financial_trading_crew = Crew(
Expand All @@ -31,7 +30,7 @@

def run_investment_crew(input_data):
result = financial_trading_crew.kickoff(inputs=input_data)
return result
return str(result)

if __name__=='__main__':
financial_trading_inputs ={
Expand Down
8 changes: 3 additions & 5 deletions agents/job_posting_agent/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@
from .tools import web_search_tool, serper_search_tool
import os
import settings
from langchain_google_genai import ChatGoogleGenerativeAI

llm=ChatGoogleGenerativeAI(model=settings.GEMINI_FLASH,
verbose=True,
temperature=0.7,
google_api_key=os.getenv("GOOGLE_API_KEY"))
os.environ["GEMINI_API_KEY"] = os.environ.get('GEMINI_API_KEY')

llm = "gemini/gemini-1.5-flash-8b"


class JobAgents():
Expand Down
2 changes: 1 addition & 1 deletion agents/job_posting_agent/crew.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@

def run_job_crew(input_data):
result = job_crew.kickoff(input_data)
return result
return str(result)

if __name__=='__main__':
job_agent_input = {
Expand Down
5 changes: 2 additions & 3 deletions agents/ml_assistant/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@

class MLAgents():
def __init__(self,model) -> None:
self.llm = ChatGroq(
api_key=os.environ['GROQ_API_KEY'],
model_name=model)
os.environ["GROQ_API_KEY"] = os.environ.get('GROQ_API_KEY')
self.llm = f"groq/{model}"

def problem_definition_agent(self):
return Agent(
Expand Down
4 changes: 2 additions & 2 deletions agents/ml_assistant/crew.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def run_ml_crew(file_path, user_question, model="llama3-70b-8192"):
# Format the input data for agents
input_data = {
"ml_problem": user_question,
"df": df.head(),
"df": df.head().to_json(orient="records"),
"file_name": file_path
}

Expand All @@ -40,7 +40,7 @@ def run_ml_crew(file_path, user_question, model="llama3-70b-8192"):
)

result = ml_crew.kickoff(input_data)
return result
return str(result)

if __name__=="__main__":
print(run_ml_crew(file_path="data/iris.csv",
Expand Down
9 changes: 3 additions & 6 deletions agents/tech_news_agent/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,12 @@
from .tools import tool
from dotenv import load_dotenv
load_dotenv()
from langchain_google_genai import ChatGoogleGenerativeAI
import os


## call the gemini models
llm=ChatGoogleGenerativeAI(model="gemini-1.5-flash",
verbose=True,
temperature=0.5,
google_api_key=os.getenv("GOOGLE_API_KEY"))
os.environ["GEMINI_API_KEY"] = os.environ.get('GEMINI_API_KEY')

llm = "gemini/gemini-1.5-flash-8b"

# Creating a senior researcher agent with memory and verbose mode

Expand Down
2 changes: 1 addition & 1 deletion agents/tech_news_agent/crew.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

def run_crew(topic):
result = crew.kickoff(inputs={'topic': topic})
return result
return str(result)

if __name__=='__main__':
print(run_crew(topic="AI in Constructions"))
74 changes: 70 additions & 4 deletions api.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
from mongo import MongoDB
from helper_functions import get_qa_chain,get_gemini_response,get_url_doc_qa,extract_transcript_details,\
get_gemini_response_health,get_gemini_pdf,read_sql_query,remove_substrings,questions_generator,groq_pdf,\
summarize_audio,chatbot_send_message,extraxt_pdf_text,advance_rag_llama_index,parse_sql_response, extract_video_id
summarize_audio,chatbot_send_message,extraxt_pdf_text,advance_rag_llama_index,parse_sql_response, extract_video_id,\
encode_image
from langchain_groq import ChatGroq
from langchain.chains.conversation.base import ConversationChain
from langchain.chains.conversation.memory import ConversationBufferWindowMemory
Expand Down Expand Up @@ -47,12 +48,21 @@
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
from groq import Groq
import openai
from dotenv import load_dotenv

load_dotenv()

os.environ["LANGCHAIN_TRACING_V2"]="true"
os.environ["LANGCHAIN_API_KEY"]=os.getenv("LANGCHAIN_API_KEY")
os.environ["LANGCHAIN_PROJECT"]="genify"
os.environ["LANGCHAIN_ENDPOINT"]="https://api.smith.langchain.com"

openai_compatible_client = openai.OpenAI(
base_url="https://api.groq.com/openai/v1",
api_key=os.getenv("GROQ_API_KEY")
)

redis = Redis(host=os.getenv("REDIS_HOST"), port=settings.REDIS_PORT, password=os.getenv("REDIS_PASSWORD"))
client = Groq()
mongo_client = MongoDB(collection_name=os.getenv("MONGO_COLLECTION_USER"))
Expand Down Expand Up @@ -314,7 +324,7 @@ async def blogs(topic: str = Form("Generative AI")):
print("Retrieving response from Redis cache")
return ResponseText(response=cached_response.decode("utf-8"))

model = genai.GenerativeModel(settings.GEMINI_FLASH)
model = genai.GenerativeModel(settings.GEMINI_FLASH_8B)
blog_prompt = f""" You are expert in blog writing. Write a blog on the topic {topic}. Use a friendly and informative tone, and include examples and tips to encourage readers to get started with the topic provided. """
response = model.generate_content(blog_prompt)
redis.set(cache_key, response.text, ex=60)
Expand Down Expand Up @@ -523,7 +533,7 @@ async def ats(resume_pdf: UploadFile = File(...), job_description: str = Form(..
return ResponseText(response=cached_response.decode("utf-8"))

text = extraxt_pdf_text(resume_pdf.file)
model = genai.GenerativeModel(settings.GEMINI_PRO_1_5)
model = genai.GenerativeModel(settings.GEMINI_FLASH_8B)
ats_prompt = f"""
Hey Act Like a skilled or very experienced ATS (Application Tracking System)
with a deep understanding of the tech field, software engineering, data science, data analysis,
Expand Down Expand Up @@ -1032,7 +1042,7 @@ async def ml_crew(file: UploadFile = File(...),user_question: str = Form(...),mo
db = MongoDB()
payload = {
"endpoint": "/ml_assistant",
"propmt" : user_question,
"prompt" : user_question,
"Model" : model,
"Output" : output
}
Expand All @@ -1043,6 +1053,62 @@ async def ml_crew(file: UploadFile = File(...),user_question: str = Form(...),mo

except Exception as e:
return {"error": str(e)}

@app.post("/agrilens")
async def analyze_image(file: UploadFile,custom_prompt: str = Form(""),token: str = Depends(oauth2_scheme)):
try:
payload = jwt.decode(token, os.getenv("TOKEN_SECRET_KEY"), algorithms=[settings.ALGORITHM])
email = payload.get("sub")
if email is None:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
user = users_collection.find_one({"email": email})
if user is None:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
except JWTError:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")


if not file.filename.lower().endswith(('.jpg', '.jpeg', '.png')):
raise HTTPException(status_code=400, detail="Invalid file type. Only JPG, JPEG, and PNG are supported.")

image_data = await file.read()
base64_image = encode_image(image_data)

final_prompt = custom_prompt if custom_prompt and custom_prompt.strip() else settings.AGRILENS_DEFAULT_PROMPT

try:
chat_completion = openai_compatible_client.chat.completions.create(
messages=[
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}"
},
},
{"type": "text", "text": final_prompt},
],
}
],
model="llama-3.2-90b-vision-preview"
)

response_content = chat_completion.choices[0].message.content
db = MongoDB()
payload = {
"endpoint": "/agrilens",
"custom_prompt" : final_prompt,
"Output" : response_content
}
mongo_data = {"Document": payload}
result = db.insert_data(mongo_data)
print(result)
return ResponseText(response=response_content)

except Exception as e:
raise HTTPException(status_code=500, detail=f"Error during analysis: {e}")

if __name__ == '__main__':
import uvicorn
Expand Down
Binary file removed data/Chinook.db
Binary file not shown.
Binary file removed data/Sample.mp3
Binary file not shown.
Binary file removed data/burger.jpg
Binary file not shown.
Binary file removed data/employees.db
Binary file not shown.
Loading
Loading