File size: 5,495 Bytes
d317445 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 | #!/usr/bin/env python3
"""
LangChain tools for Long Term Memory integration with Ollama
"""
from langchain.tools import tool
from langchain_ollama import OllamaLLM
from langchain.agents import create_react_agent, AgentExecutor
from langchain import hub
from typing import Optional, Dict, Any, List
import requests
import json
# Import your existing LTM demo class
from gradio_demo import LongTermMemoryDemo
# Initialize shared memory instance
ltm = LongTermMemoryDemo()
@tool
def save_memory(content: str, title: str, tags: str = "", context: str = "") -> str:
"""
Save important insights, conclusions, or context to long-term memory.
Use this to remember key information from conversations that might be useful later.
Args:
content: The insight or information to save
title: A brief descriptive title
tags: Optional comma-separated tags
context: Optional additional context
"""
try:
return ltm.save_memory(content, title, tags, context)
except Exception as e:
return f"Error saving memory: {str(e)}"
@tool
def search_memory(query: str, limit: int = 5, threshold: float = 0.3) -> str:
"""
Search through long-term memory for relevant information.
Use this to find previously saved insights or context related to current discussion.
Args:
query: What to search for
limit: Max number of results (default: 5)
threshold: Similarity threshold 0-1 (default: 0.3)
"""
try:
return ltm.search_memory(query, limit, threshold)
except Exception as e:
return f"Error searching memory: {str(e)}"
@tool
def list_memories(limit: int = 10) -> str:
"""
List all stored memories to see what information is available.
Useful for getting an overview of stored knowledge.
Args:
limit: Maximum number of memories to show (default: 10)
"""
try:
return ltm.list_memories(limit)
except Exception as e:
return f"Error listing memories: {str(e)}"
@tool
def memory_stats() -> str:
"""
Get statistics about stored memories.
Shows total count, tags, and other metadata.
"""
try:
return ltm.get_memory_stats()
except Exception as e:
return f"Error getting stats: {str(e)}"
# Example usage with Ollama
def create_memory_enabled_agent(model_name: str = "llama3.2"):
"""Create a LangChain agent with memory capabilities"""
# Initialize Ollama LLM
llm = OllamaLLM(model=model_name)
# Create tools list
tools = [save_memory, search_memory, list_memories, memory_stats]
# Get the react prompt from hub
try:
prompt = hub.pull("hwchase17/react")
except:
# Fallback prompt if hub is not available
from langchain.prompts import PromptTemplate
template = """Answer the following questions as best you can. You have access to the following tools:
{tools}
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Begin!
Question: {input}
Thought:{agent_scratchpad}"""
prompt = PromptTemplate.from_template(template)
# Create agent
agent = create_react_agent(llm, tools, prompt)
# Create agent executor
agent_executor = AgentExecutor(
agent=agent,
tools=tools,
verbose=True,
handle_parsing_errors=True,
max_iterations=10
)
return agent_executor
# Example conversation loop
def main():
"""Example usage"""
print("🧠 Initializing Memory-Enabled Agent with Ollama...")
try:
agent = create_memory_enabled_agent("llama3.2") # или любая другая модель в Ollama
print("✅ Agent ready! Type 'quit' to exit.")
print("💡 Try commands like:")
print(" - 'Save this insight: quantum computers might revolutionize AI with title Quantum AI and tags quantum,ai,future' ")
print(" - 'Search my memories for information about quantum computing'")
print(" - 'What memories do I have stored?'")
print(" - 'Show me memory statistics'")
print()
while True:
try:
user_input = input("You: ").strip()
if user_input.lower() in ['quit', 'exit', 'bye']:
print("Goodbye!")
break
if not user_input:
continue
# Run the agent
response = agent.invoke({"input": user_input})
print(f"Agent: {response['output']}")
print()
except KeyboardInterrupt:
print("\nGoodbye!")
break
except Exception as e:
print(f"Error: {e}")
continue
except Exception as e:
print(f"Failed to initialize agent: {e}")
print("Make sure Ollama is running and the model is available.")
print("Try: ollama pull llama3.2")
if __name__ == "__main__":
main() |