diff --git a/templates/langchain/advanced/__init__.py b/templates/langchain/advanced/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/templates/langchain/advanced/agent.py b/templates/langchain/advanced/agent.py deleted file mode 100644 index 5513487..0000000 --- a/templates/langchain/advanced/agent.py +++ /dev/null @@ -1,137 +0,0 @@ -import os -from typing import Any, Dict, List - -from dotenv import load_dotenv -from langchain.agents import AgentExecutor, create_openai_functions_agent -from langchain.chat_models import ChatOpenAI -from langchain.memory import ConversationBufferWindowMemory -from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder -from langchain.schema import AIMessage, HumanMessage -from langchain.tools import tool - -# Load environment variables -load_dotenv() - - -# Define custom tools -@tool -def calculate(expression: str) -> str: - """Evaluate a mathematical expression safely.""" - try: - # Basic safety: only allow certain characters - allowed_chars = set("0123456789+-*/.() ") - if not all(c in allowed_chars for c in expression): - return "Error: Invalid characters in expression" - - result = eval(expression) - return f"Result: {result}" - except Exception as e: - return f"Error in calculation: {str(e)}" - - -@tool -def search_knowledge(query: str) -> str: - """Search for information in the knowledge base.""" - # This is a placeholder - implement your actual search logic - knowledge_base = { - "python": "Python is a high-level programming language known for its simplicity and readability.", - "ai": "Artificial Intelligence (AI) refers to the simulation of human intelligence in machines.", - "langchain": "LangChain is a framework for developing applications powered by language models.", - } - - query_lower = query.lower() - for key, value in knowledge_base.items(): - if key in query_lower: - return f"Knowledge: {value}" - - return f"No specific knowledge found for: {query}. Try asking about Python, AI, or LangChain." - - -class LangChainAdvancedAgent: - """Advanced LangChain agent with tools, memory, and custom prompts""" - - def __init__(self, config: Dict[str, Any] = None): - self.config = config or {} - - # Initialize LLM - self.llm = ChatOpenAI( - temperature=self.config.get("temperature", 0.7), - model_name=self.config.get("model", "gpt-4"), - api_key=os.getenv("OPENAI_API_KEY"), - ) - - # Initialize tools - self.tools = [calculate, search_knowledge] - - # Create custom prompt - system_prompt = self.config.get( - "system_prompt", - "You are a helpful AI assistant with access to tools for calculation and knowledge search. " - "Use the tools when appropriate to provide accurate and helpful responses.", - ) - - self.prompt = ChatPromptTemplate.from_messages( - [ - ("system", system_prompt), - MessagesPlaceholder(variable_name="chat_history"), - ("human", "{input}"), - MessagesPlaceholder(variable_name="agent_scratchpad"), - ] - ) - - # Initialize memory - self.memory = ConversationBufferWindowMemory( - memory_key="chat_history", - return_messages=True, - k=self.config.get("memory_window", 5), - ) - - # Create agent - self.agent = create_openai_functions_agent( - llm=self.llm, tools=self.tools, prompt=self.prompt - ) - - # Create agent executor - self.agent_executor = AgentExecutor( - agent=self.agent, - tools=self.tools, - memory=self.memory, - verbose=self.config.get("verbose", False), - handle_parsing_errors=True, - max_iterations=self.config.get("max_iterations", 3), - ) - - def process_message(self, message: str) -> Dict[str, Any]: - """Process a single message and return detailed response""" - try: - result = self.agent_executor.invoke({"input": message}) - - return { - "output": result["output"], - "intermediate_steps": result.get("intermediate_steps", []), - "tools_used": [ - step[0].tool for step in result.get("intermediate_steps", []) - ], - } - except Exception as e: - raise Exception(f"Error processing message: {str(e)}") - - def process_messages(self, messages: list) -> Dict[str, Any]: - """Process a list of messages and return the final response""" - if not messages: - return {"output": "No messages provided", "tools_used": []} - - # Add previous messages to memory (except the last one) - for msg in messages[:-1]: - if msg.get("role") == "user": - self.memory.chat_memory.add_user_message(msg["content"]) - elif msg.get("role") == "assistant": - self.memory.chat_memory.add_ai_message(msg["content"]) - - # Process the last message - last_message = messages[-1]["content"] - return self.process_message(last_message) - - def get_available_tools(self) -> List[str]: - """Get list of available tool names""" - return [tool.name for tool in self.tools] diff --git a/templates/langchain/advanced/main.py b/templates/langchain/advanced/main.py deleted file mode 100644 index 30bee98..0000000 --- a/templates/langchain/advanced/main.py +++ /dev/null @@ -1,72 +0,0 @@ -import time -from typing import Any, Dict - -from agent import LangChainAdvancedAgent - - -def run(input_data: Dict[str, Any]) -> Dict[str, Any]: - """ - Main entry point for the LangChain Advanced agent - - Args: - input_data: Dictionary containing: - - messages: List of message objects with 'role' and 'content' - - config: Optional configuration parameters - - Returns: - Dictionary with result, errors, and success status - """ - start_time = time.time() - - try: - # Extract configuration - config = input_data.get("config", {}) - messages = input_data.get("messages", []) - - if not messages: - return { - "result": { - "type": "string", - "content": "No messages provided", - "metadata": {"execution_time": time.time() - start_time}, - }, - "errors": ["No messages provided"], - "success": False, - } - - # Initialize agent - agent = LangChainAdvancedAgent(config) - - # Process messages - response = agent.process_messages(messages) - - # Calculate execution time - execution_time = time.time() - start_time - - return { - "result": { - "type": "string", - "content": response["output"], - "metadata": { - "model_used": config.get("model", "gpt-4"), - "framework": "langchain", - "template": "advanced", - "execution_time": execution_time, - "tools_available": agent.get_available_tools(), - "tools_used": response.get("tools_used", []), - "conversation_length": len(messages), - "intermediate_steps": len(response.get("intermediate_steps", [])), - }, - }, - "errors": [], - "success": True, - } - - except Exception as e: - execution_time = time.time() - start_time - return { - "result": None, - "errors": [str(e)], - "success": False, - "metadata": {"execution_time": execution_time}, - } diff --git a/templates/langchain/advanced/requirements.txt b/templates/langchain/advanced/requirements.txt deleted file mode 100644 index ac267f8..0000000 --- a/templates/langchain/advanced/requirements.txt +++ /dev/null @@ -1,4 +0,0 @@ -langchain==0.1.0 -langchain-openai==0.0.5 -openai==1.12.0 -python-dotenv==1.0.0 \ No newline at end of file