Spaces:
Runtime error
Runtime error
Update crewai_agent.py
Browse files1 unmodified line2345678910111213141516171819202158 unmodified lines8081828384858636 unmodified lines12312412512612712812913013113213313413513613713813914014114210 unmodified lines15315415515615715815916016116216316416516616716821 unmodified lines19019119219319419576 unmodified lines2722732741 unmodified linefrom typing import List, Dict, Any, Optionalfrom dotenv import load_dotenvfrom langchain.agents import AgentType, initialize_agent, Toolfrom langchain.memory import ConversationBufferMemoryfrom langchain.schema import BaseMessage, HumanMessage, AIMessagefrom langchain_google_genai import ChatGoogleGenerativeAIfrom langchain_huggingface import ChatHuggingFace, HuggingFaceEndpointfrom langchain_community.tools.tavily_search import TavilySearchResultsfrom langchain_community.document_loaders import WikipediaLoader, ArxivLoaderfrom langchain.tools import toolfrom langchain.prompts import PromptTemplatefrom langchain.chains import LLMChain# Load environment variablesGOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY')HUGGINGFACE_API_TOKEN= os.getenv('HUGGINGFACE_API_TOKEN')TAVILY_API_KEY = os.getenv('TAVILY_API_KEY')58 unmodified linesFormatted web search results"""try:search_results = TavilySearchResults(max_results=3,api_key=TAVILY_API_KEY).invoke(query)formatted_results = "\n\n---\n\n".join([f'Source: {result.get("url", "")}\n\nContent:\n{result.get("content", "")}'for result in search_results36 unmodified linesdef _get_llm(self, provider: str):"""Get the specified LLM."""if provider == "google":return ChatGoogleGenerativeAI(model="gemini-2.0-flash",temperature=0,max_tokens=2048,api_key=GOOGLE_API_KEY)elif provider == "huggingface":return ChatHuggingFace(llm=HuggingFaceEndpoint(repo_id="microsoft/DialoGPT-medium",temperature=0,max_length=2048,api_key=HUGGINGFACE_API_TOKEN),)else:10 unmodified linesdef _create_agent(self):"""Create the LangChain agent with tools."""return initialize_agent(tools=self.tools,llm=self.llm,agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,memory=self.memory,verbose=True,handle_parsing_errors=True,max_iterations=5,early_stopping_method="generate")def _determine_approach(self, question: str) -> str:"""Determine the best approach for answering the question."""21 unmodified linestry:print(f"Processing question: {question[:100]}...")# Determine the best approach for this questionapproach = self._determine_approach(question)print(f"Selected approach: {approach}")76 unmodified linesif __name__ == "__main__":test_langchain_agent()1 unmodified line2345678910111213141516171819202122232458 unmodified lines8384858687888990919236 unmodified lines12913013113213313413513613713813914014114214314414514614714814915015110 unmodified lines16216316416516616716816917017117217317417517617717817918018118221 unmodified lines20420520620720820921021121221321421521621721876 unmodified lines2952962972981 unmodified linefrom typing import List, Dict, Any, Optionalfrom dotenv import load_dotenv# Load environment variables from .env fileload_dotenv()from langchain.agents import AgentType, initialize_agent, Toolfrom langchain.memory import ConversationBufferMemoryfrom langchain_core.messages import BaseMessage, HumanMessage, AIMessagefrom langchain_google_genai import ChatGoogleGenerativeAIfrom langchain_huggingface import ChatHuggingFace, HuggingFaceEndpointfrom langchain_community.tools.tavily_search import TavilySearchResultsfrom langchain_community.document_loaders import WikipediaLoader, ArxivLoaderfrom langchain_core.tools import toolfrom langchain.prompts import PromptTemplatefrom langchain.chains import LLMChain# Load environment variablesGOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY')HUGGINGFACE_API_TOKEN = os.getenv('HUGGINGFACE_API_TOKEN')TAVILY_API_KEY = os.getenv('TAVILY_API_KEY')58 unmodified linesFormatted web search results"""try:if not TAVILY_API_KEY:return "Error: TAVILY_API_KEY not found in environment variables"search_results = TavilySearchResults(max_results=3, api_key=TAVILY_API_KEY).invoke(query)formatted_results = "\n\n---\n\n".join([f'Source: {result.get("url", "")}\n\nContent:\n{result.get("content", "")}'for result in search_results36 unmodified linesdef _get_llm(self, provider: str):"""Get the specified LLM."""if provider == "google":if not GOOGLE_API_KEY:raise ValueError("GOOGLE_API_KEY not found in environment variables")return ChatGoogleGenerativeAI(model="gemini-1.5-flash",temperature=0,max_tokens=2048,google_api_key=GOOGLE_API_KEY)elif provider == "huggingface":if not HUGGINGFACE_API_TOKEN:raise ValueError("HUGGINGFACE_API_TOKEN not found in environment variables")return ChatHuggingFace(llm=HuggingFaceEndpoint(repo_id="microsoft/DialoGPT-medium",temperature=0,max_length=2048,huggingfacehub_api_token=HUGGINGFACE_API_TOKEN),)else:10 unmodified linesdef _create_agent(self):"""Create the LangChain agent with tools."""try:return initialize_agent(tools=self.tools,llm=self.llm,agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,memory=self.memory,verbose=True,handle_parsing_errors=True,max_iterations=3,early_stopping_method="generate")except Exception as e:print(f"Error creating agent: {e}")# Return a simple agent without tools as fallbackreturn Nonedef _determine_approach(self, question: str) -> str:"""Determine the best approach for answering the question."""21 unmodified linestry:print(f"Processing question: {question[:100]}...")# If agent initialization failed, use direct LLMif self.agent is None:print("Agent not available, using direct LLM response")try:response = self.llm.invoke([HumanMessage(content=question)])return response.contentexcept Exception as llm_error:return f"Error: Unable to process question. {str(llm_error)}"# Determine the best approach for this questionapproach = self._determine_approach(question)print(f"Selected approach: {approach}")76 unmodified linesif __name__ == "__main__":test_langchain_agent()
crewai_agent.py+42-18