219 lines
7.9 KiB
Python
219 lines
7.9 KiB
Python
import sys
|
|
import os
|
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
|
|
import asyncio
|
|
import tempfile
|
|
from context.sketch_pad import RedisFileSketchPadBackend
|
|
|
|
|
|
async def sketch_pad_example():
|
|
"""SketchPad usage example."""
|
|
print("=== SketchPad Usage Example ===")
|
|
|
|
# Create a temporary file.
|
|
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
|
|
temp_file = f.name
|
|
|
|
try:
|
|
# Initialize SketchPad.
|
|
sketch_pad = RedisFileSketchPadBackend(
|
|
sketch_pad_id="example_pad",
|
|
file_path=temp_file
|
|
)
|
|
|
|
print("1. Storing user preference settings...")
|
|
await sketch_pad.set_item(
|
|
key="user_preferences",
|
|
value={
|
|
"theme": "dark",
|
|
"language": "en-US",
|
|
"notifications": True,
|
|
"auto_save": True
|
|
},
|
|
summary="User interface preference settings",
|
|
tags={"preferences", "ui", "settings"}
|
|
)
|
|
|
|
print("2. Storing recently accessed files...")
|
|
await sketch_pad.set_item(
|
|
key="recent_files",
|
|
value=[
|
|
{"name": "main.py", "path": "/project/main.py", "last_accessed": "2024-01-15"},
|
|
{"name": "config.json", "path": "/project/config.json", "last_accessed": "2024-01-14"},
|
|
{"name": "README.md", "path": "/project/README.md", "last_accessed": "2024-01-13"}
|
|
],
|
|
summary="List of recently accessed files",
|
|
tags={"files", "recent", "history"}
|
|
)
|
|
|
|
print("3. Storing temporary calculation results...")
|
|
await sketch_pad.set_item(
|
|
key="temp_calculation",
|
|
value={
|
|
"expression": "2 + 3 * 4",
|
|
"result": 14,
|
|
"timestamp": "2024-01-15T10:30:00"
|
|
},
|
|
summary="Temporary math calculation result",
|
|
tags={"calculation", "temp", "math"},
|
|
ttl=300 # Expires after 5 minutes.
|
|
)
|
|
|
|
print("4. Storing code snippets...")
|
|
await sketch_pad.set_item(
|
|
key="code_snippet",
|
|
value={
|
|
"language": "python",
|
|
"code": "def hello_world():\n print('Hello, World!')",
|
|
"description": "Simple Hello World function"
|
|
},
|
|
summary="Python code snippet",
|
|
tags={"code", "python", "snippet"}
|
|
)
|
|
|
|
print("\n5. Querying and retrieving...")
|
|
|
|
# Get user preferences.
|
|
preferences = sketch_pad.get_item("user_preferences")
|
|
print(f" User preferences: {preferences.value if preferences else 'Not found'}")
|
|
|
|
# Search for items containing "file".
|
|
file_items = sketch_pad.search_by_content("file", limit=5)
|
|
print(f" Items containing 'file': {len(file_items)}")
|
|
|
|
# Search for items with a specific tag.
|
|
recent_items = sketch_pad.search_by_tags({"recent"})
|
|
print(f" Recent item count: {len(recent_items)}")
|
|
|
|
# Search for items with multiple tags.
|
|
ui_items = sketch_pad.search_by_tags({"ui", "settings"}, match_all=True)
|
|
print(f" Items containing both ui and settings tags: {len(ui_items)}")
|
|
|
|
print("\n6. Statistics...")
|
|
stats = sketch_pad.get_statistics()
|
|
print(f" Total item count: {stats.total_items}")
|
|
print(f" Total accesses: {stats.total_accesses}")
|
|
print(f" Popular tags: {stats.popular_tags}")
|
|
|
|
print("\n7. Listing all items...")
|
|
items = sketch_pad.list_items(include_value=False)
|
|
for item in items:
|
|
print(f" - {item.key}: {item.summary} (tags: {item.tags})")
|
|
|
|
print("\n8. Persisting data...")
|
|
sketch_pad.persist()
|
|
print(" Data saved to file")
|
|
|
|
print("\n=== Example Complete ===")
|
|
|
|
finally:
|
|
if os.path.exists(temp_file):
|
|
os.unlink(temp_file)
|
|
|
|
|
|
async def llm_integration_example():
|
|
"""Example showing SketchPad integration with an LLM."""
|
|
print("\n=== SketchPad and LLM Integration Example ===")
|
|
|
|
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
|
|
temp_file = f.name
|
|
|
|
try:
|
|
sketch_pad = RedisFileSketchPadBackend(
|
|
sketch_pad_id="llm_memory",
|
|
file_path=temp_file
|
|
)
|
|
|
|
print("1. Storing LLM conversation context...")
|
|
await sketch_pad.set_item(
|
|
key="conversation_context",
|
|
value={
|
|
"user_intent": "Create a Python function to calculate the Fibonacci sequence",
|
|
"current_step": "Implementing the function logic",
|
|
"requirements": ["recursive implementation", "performance optimization", "error handling"],
|
|
"code_progress": "def fibonacci(n):\n if n <= 1:\n return n\n return fibonacci(n-1) + fibonacci(n-2)"
|
|
},
|
|
summary="LLM conversation context - Fibonacci function development",
|
|
tags={"llm", "conversation", "python", "fibonacci", "development"}
|
|
)
|
|
|
|
print("2. Storing user feedback...")
|
|
await sketch_pad.set_item(
|
|
key="user_feedback",
|
|
value={
|
|
"feedback_type": "positive",
|
|
"message": "The function works well, but it could use some comments",
|
|
"suggestions": ["add a docstring", "add type hints", "add examples"],
|
|
"timestamp": "2024-01-15T11:00:00"
|
|
},
|
|
summary="User feedback on the Fibonacci function",
|
|
tags={"feedback", "user", "improvement"}
|
|
)
|
|
|
|
print("3. Storing code version...")
|
|
await sketch_pad.set_item(
|
|
key="code_version_1",
|
|
value={
|
|
"version": "1.0",
|
|
"code": "def fibonacci(n):\n \"\"\"Calculate the nth term of the Fibonacci sequence.\"\"\"\n if n <= 1:\n return n\n return fibonacci(n-1) + fibonacci(n-2)",
|
|
"features": ["basic recursive implementation", "simple error handling"],
|
|
"performance": "O(2^n) time complexity"
|
|
},
|
|
summary="Fibonacci function version 1.0",
|
|
tags={"code", "version", "fibonacci", "recursive"}
|
|
)
|
|
|
|
print("\n4. LLM query example...")
|
|
|
|
# Simulate an LLM querying related context.
|
|
context_items = sketch_pad.search_by_tags({"llm", "conversation"})
|
|
print(f" Found {len(context_items)} conversation context items")
|
|
|
|
# Simulate an LLM querying user feedback.
|
|
feedback_items = sketch_pad.search_by_content("feedback", limit=3)
|
|
print(f" Found {len(feedback_items)} feedback-related items")
|
|
|
|
# Simulate an LLM querying code versions.
|
|
code_items = sketch_pad.search_by_tags({"code", "version"})
|
|
print(f" Found {len(code_items)} code version items")
|
|
|
|
print("\n5. Building LLM context...")
|
|
context_parts = []
|
|
|
|
# Get conversation context.
|
|
conv_context = sketch_pad.get_item("conversation_context")
|
|
if conv_context:
|
|
context_parts.append(f"Conversation context: {conv_context.value}")
|
|
|
|
# Get user feedback.
|
|
feedback = sketch_pad.get_item("user_feedback")
|
|
if feedback:
|
|
context_parts.append(f"User feedback: {feedback.value}")
|
|
|
|
# Get the latest code version.
|
|
code_version = sketch_pad.get_item("code_version_1")
|
|
if code_version:
|
|
context_parts.append(f"Current code: {code_version.value}")
|
|
|
|
print(" Constructed LLM context:")
|
|
for i, part in enumerate(context_parts, 1):
|
|
print(f" {i}. {part[:100]}...")
|
|
|
|
print("\n=== LLM Integration Example Complete ===")
|
|
|
|
finally:
|
|
if os.path.exists(temp_file):
|
|
os.unlink(temp_file)
|
|
|
|
|
|
async def main():
|
|
"""Main function."""
|
|
await sketch_pad_example()
|
|
await llm_integration_example()
|
|
print("\nAll examples complete!")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
asyncio.run(main())
|