Spaces:
Runtime error
Runtime error
Update crewai_agent.py
Browse files1 unmodified line234567897101112131412151617181920182122232458 unmodified lines838485868788838990919236 unmodified lines12913013113213313412713513613713013113813914014114214314414514614713914814915015110 unmodified lines16216316416515615715815916016116216316416516616716816917017117217317417517617717817918018118221 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.schema import BaseMessage, HumanMessage, AIMessagefrom 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.tools import toolfrom 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')HUGGINGFACE_API_TOKEN = os.getenv('HUGGINGFACE_API_TOKEN')TAVILY_API_KEY = os.getenv('TAVILY_API_KEY')
58 unmodified lines Formatted 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) 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 lines def _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-2.0-flash", model="gemini-1.5-flash", temperature=0, max_tokens=2048, api_key=GOOGLE_API_KEY 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, api_key=HUGGINGFACE_API_TOKEN huggingfacehub_api_token=HUGGINGFACE_API_TOKEN ), ) else:10 unmodified lines def _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=5, early_stopping_method="generate" ) 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 fallback return None def _determine_approach(self, question: str) -> str: """Determine the best approach for answering the question."""21 unmodified lines try: print(f"Processing question: {question[:100]}...") # If agent initialization failed, use direct LLM if self.agent is None: print("Agent not available, using direct LLM response") try: response = self.llm.invoke([HumanMessage(content=question)]) return response.content except Exception as llm_error: return f"Error: Unable to process question. {str(llm_error)}" # Determine the best approach for this question approach = self._determine_approach(question) print(f"Selected approach: {approach}")76 unmodified lines
if __name__ == "__main__": test_langchain_agent()
crewai_agent.py+42-18