Skip to content

Commit 7a4da21

Browse files
committed
query agents
1 parent 50126dc commit 7a4da21

4 files changed

Lines changed: 112 additions & 56 deletions

File tree

backend/agents/orchestrator/agent_orchestrator.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from typing import Dict, List, Any, Optional, Tuple, TypedDict
22
import asyncio
3-
from agents.utils.base_agent import BasicQueryAgent as BaseAgent
3+
from agents.utils.base_agent import BaseAgent
44
import logging
55
from agents.vector_store.vector_store import VectorStore
66
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage

backend/agents/orchestrator/run_orchestrator.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import json
44
import os
55
from dotenv import load_dotenv
6+
from agents.utils.basic_query_agent import BasicQueryAgent
67

78
# Add the backend directory to Python path
89
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
@@ -30,6 +31,17 @@ async def main():
3031
# Initialize orchestrator
3132
orchestrator = AgentOrchestrator(openai_api_key)
3233

34+
# Register specialized agents
35+
await orchestrator.register_agent(SoilAnalyzerAgent("soil_analyzer", openai_api_key))
36+
await orchestrator.register_agent(WeatherAnalyzerAgent("weather_analyzer", openai_api_key))
37+
await orchestrator.register_agent(CropRecommenderAgent("crop_recommender", openai_api_key))
38+
await orchestrator.register_agent(SustainabilityAdvisorAgent("sustainability_advisor", openai_api_key))
39+
await orchestrator.register_agent(DataCollectorAgent("data_collector", openai_api_key))
40+
41+
# Create and register the basic query agent
42+
basic_agent = BasicQueryAgent("basic_query_agent", openai_api_key)
43+
await orchestrator.register_agent(basic_agent)
44+
3345
# Process query
3446
result = await orchestrator.process_query(query)
3547

backend/agents/utils/base_agent.py

Lines changed: 39 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,44 @@
1-
from typing import Dict, List, Any, Optional
2-
from agents.utils.base_agent import BaseAgent
3-
from langchain_openai import ChatOpenAI
4-
from langchain_core.prompts import ChatPromptTemplate
1+
from abc import ABC, abstractmethod
2+
from typing import Any, Dict, List, Optional
3+
import logging
54

6-
class BasicQueryAgent(BaseAgent):
7-
"""Agent for handling simple, general farming queries without specialized processing."""
8-
9-
def __init__(self, name: str, openai_api_key: str):
10-
super().__init__(name)
11-
self.llm = ChatOpenAI(
12-
model="gpt-3.5-turbo", # Using a smaller model for efficiency
13-
temperature=0,
14-
openai_api_key=openai_api_key
15-
)
5+
class BaseAgent(ABC):
6+
def __init__(self, name: str, config: Optional[Dict[str, Any]] = None):
7+
self.name = name
8+
self.config = config or {}
9+
self.logger = logging.getLogger(f"agent.{name}")
1610

11+
@abstractmethod
1712
async def initialize(self) -> None:
18-
"""Initialize the agent."""
19-
self.initialized = True
20-
return
21-
22-
async def process(self, query: str) -> Dict[str, Any]:
23-
"""
24-
Process a simple farming query and provide a direct response.
25-
26-
Returns:
27-
Dict with:
28-
- status: "success" or "error"
29-
- result: The response to the query
30-
"""
31-
try:
32-
# Process the query with a farming-focused prompt
33-
answer_prompt = ChatPromptTemplate.from_messages([
34-
("system", """You are a knowledgeable farming assistant with general knowledge about sustainable
35-
agriculture, common farming practices, and basic crop information.
36-
37-
Provide helpful, concise answers to general farming questions. If the query requires
38-
specialized agricultural expertise beyond general knowledge, still provide the best
39-
answer you can based on general principles.
40-
"""),
41-
("human", "{query}")
42-
])
43-
44-
response = self.llm.invoke(answer_prompt.format_messages(query=query))
45-
46-
return {
47-
"status": "success",
48-
"result": response.content
49-
}
50-
51-
except Exception as e:
52-
return {
53-
"status": "error",
54-
"error": str(e)
55-
}
13+
"""Initialize the agent with necessary resources"""
14+
pass
15+
16+
@abstractmethod
17+
async def process(self, input_data: Any) -> Any:
18+
"""Process the input data and return results"""
19+
pass
5620

21+
@abstractmethod
5722
async def cleanup(self) -> None:
58-
"""Cleanup resources."""
59-
self.initialized = False
60-
return
23+
"""Cleanup resources when the agent is done"""
24+
pass
25+
26+
def get_capabilities(self) -> Dict[str, Any]:
27+
"""Return the capabilities of the agent"""
28+
return {
29+
"name": self.name,
30+
"capabilities": self.config.get("capabilities", [])
31+
}
32+
33+
async def validate_input(self, input_data: Any) -> bool:
34+
"""Validate the input data before processing"""
35+
return True
36+
37+
async def handle_error(self, error: Exception) -> Dict[str, Any]:
38+
"""Handle any errors that occur during processing"""
39+
self.logger.error(f"Error in {self.name}: {str(error)}")
40+
return {
41+
"status": "error",
42+
"agent": self.name,
43+
"error": str(error)
44+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
from typing import Dict, List, Any, Optional
2+
from agents.utils.base_agent import BaseAgent
3+
from langchain_openai import ChatOpenAI
4+
from langchain_core.prompts import ChatPromptTemplate
5+
6+
class BasicQueryAgent(BaseAgent):
7+
"""Agent for handling simple, general farming queries without specialized processing."""
8+
9+
def __init__(self, name: str, openai_api_key: str):
10+
super().__init__(name)
11+
self.llm = ChatOpenAI(
12+
model="gpt-3.5-turbo", # Using a smaller model for efficiency
13+
temperature=0,
14+
openai_api_key=openai_api_key
15+
)
16+
17+
async def initialize(self) -> None:
18+
"""Initialize the agent."""
19+
self.initialized = True
20+
return
21+
22+
async def process(self, query: str) -> Dict[str, Any]:
23+
"""
24+
Process a simple farming query and provide a direct response.
25+
26+
Returns:
27+
Dict with:
28+
- status: "success" or "error"
29+
- result: The response to the query
30+
"""
31+
try:
32+
# Process the query with a farming-focused prompt
33+
answer_prompt = ChatPromptTemplate.from_messages([
34+
("system", """You are a knowledgeable farming assistant with general knowledge about sustainable
35+
agriculture, common farming practices, and basic crop information.
36+
37+
Provide helpful, concise answers to general farming questions. If the query requires
38+
specialized agricultural expertise beyond general knowledge, still provide the best
39+
answer you can based on general principles.
40+
"""),
41+
("human", "{query}")
42+
])
43+
44+
response = self.llm.invoke(answer_prompt.format_messages(query=query))
45+
46+
return {
47+
"status": "success",
48+
"result": response.content
49+
}
50+
51+
except Exception as e:
52+
return {
53+
"status": "error",
54+
"error": str(e)
55+
}
56+
57+
async def cleanup(self) -> None:
58+
"""Cleanup resources."""
59+
self.initialized = False
60+
return

0 commit comments

Comments
 (0)