tahamajs's picture
download
raw
17.8 kB
"""
Geometry Tools for LangChain Agents
ابزارهای هندسه برای عوامل LangChain
This module provides specialized tools for geometric problem solving
that can be used by LangChain agents.
"""
import os
import json
import logging
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from typing import Dict, List, Any, Optional, Tuple
from datetime import datetime
import sympy as sp
from sympy import symbols, solve, simplify, expand, factor
from sympy.geometry import Point, Line, Circle, Triangle, Polygon
from sympy.geometry.util import intersection
from langchain.tools import BaseTool
from langchain.llms.base import BaseLLM
logger = logging.getLogger(__name__)
class GeometryTools:
"""
Collection of geometry tools for LangChain agents
مجموعه ابزارهای هندسه برای عوامل LangChain
"""
def __init__(self, config: Dict[str, Any], llm: BaseLLM):
"""
Initialize geometry tools
Args:
config: Tools configuration
llm: Language model for advanced reasoning
"""
self.config = config
self.llm = llm
# Load theorem database
self.theorem_db = self._load_theorem_database()
logger.info("Geometry Tools initialized")
def _load_theorem_database(self) -> Dict[str, Any]:
"""Load theorem database from file"""
try:
db_path = (
self.config.get("theorem_lookup", {})
.get("parameters", {})
.get("database_path", "data/theorems/theorems.json")
)
if os.path.exists(db_path):
with open(db_path, "r", encoding="utf-8") as f:
return json.load(f)
else:
# Create sample theorem database
return self._create_sample_theorem_db()
except Exception as e:
logger.error(f"Error loading theorem database: {e}")
return self._create_sample_theorem_db()
def _create_sample_theorem_db(self) -> Dict[str, Any]:
"""Create a sample theorem database"""
return {
"pythagorean": {
"name": "قضیه فیثاغورث",
"description": "در مثلث قائم‌الزاویه، مربع وتر برابر است با مجموع مربعات دو ضلع دیگر",
"formula": "a² + b² = c²",
"category": "مثلث",
"difficulty": "پایه",
},
"thales": {
"name": "قضیه تالس",
"description": "اگر خطی موازی با یکی از اضلاع مثلث رسم شود، مثلث‌های مشابه ایجاد می‌کند",
"formula": "AB/AC = AD/AE",
"category": "مثلث",
"difficulty": "متوسط",
},
"circle_angle": {
"name": "قضیه زاویه مرکزی و محیطی",
"description": "زاویه مرکزی دو برابر زاویه محیطی است که روی همان کمان قرار دارد",
"formula": "∠AOB = 2∠ACB",
"category": "دایره",
"difficulty": "متوسط",
},
"tangent": {
"name": "قضیه مماس",
"description": "خط مماس بر دایره عمود بر شعاع در نقطه تماس است",
"formula": "OT ⊥ PT",
"category": "دایره",
"difficulty": "پایه",
},
"chord": {
"name": "قضیه وتر",
"description": "اگر دو وتر در دایره همدیگر را قطع کنند، حاصل ضرب قطعات یکی برابر حاصل ضرب قطعات دیگری است",
"formula": "AE × EB = CE × ED",
"category": "دایره",
"difficulty": "متوسط",
},
}
def coordinate_geometry_solver(self, problem_description: str) -> str:
"""
Solve geometric problems using coordinate geometry
Args:
problem_description: Description of the geometric problem
Returns:
Solution using coordinate geometry
"""
try:
# Use LLM to analyze the problem and extract coordinates
analysis_prompt = f"""
مسئله هندسی زیر را تحلیل کنید و مختصات نقاط را استخراج کنید:
{problem_description}
لطفاً:
1. نوع مسئله را تشخیص دهید
2. مختصات نقاط را مشخص کنید
3. فرمول‌های مورد نیاز را شناسایی کنید
4. راه‌حل را با استفاده از هندسه تحلیلی ارائه دهید
"""
analysis = self.llm(analysis_prompt)
# Try to solve using SymPy for symbolic computation
try:
# Define symbolic variables
x, y = symbols("x y")
# This is a simplified example - in practice, you'd parse the problem
# and create appropriate equations
solution = f"""
تحلیل مسئله:
{analysis}
راه‌حل با هندسه تحلیلی:
1. مختصات نقاط را تعریف می‌کنیم
2. معادلات مربوطه را تشکیل می‌دهیم
3. سیستم معادلات را حل می‌کنیم
4. نتیجه نهایی را محاسبه می‌کنیم
توجه: این یک راه‌حل نمونه است. برای مسائل پیچیده‌تر،
نیاز به تحلیل دقیق‌تر مسئله و تشکیل معادلات مناسب است.
"""
except Exception as e:
solution = f"""
تحلیل مسئله:
{analysis}
خطا در محاسبات سمبلیک: {str(e)}
لطفاً مسئله را با جزئیات بیشتری ارائه دهید.
"""
logger.info("Coordinate geometry solution generated")
return solution
except Exception as e:
logger.error(f"Error in coordinate geometry solver: {e}")
return f"خطا در حل مسئله با هندسه تحلیلی: {str(e)}"
def synthetic_geometry_solver(self, problem_description: str) -> str:
"""
Solve geometric problems using synthetic geometry
Args:
problem_description: Description of the geometric problem
Returns:
Solution using synthetic geometry
"""
try:
# Use LLM to analyze the problem
analysis_prompt = f"""
مسئله هندسی زیر را با استفاده از هندسه ترکیبی حل کنید:
{problem_description}
لطفاً:
1. قضایای مرتبط را شناسایی کنید
2. مراحل اثبات را به ترتیب ارائه دهید
3. از نمادهای هندسی مناسب استفاده کنید
4. نتیجه نهایی را مشخص کنید
"""
solution = self.llm(analysis_prompt)
# Add theorem references
relevant_theorems = self._find_relevant_theorems(problem_description)
if relevant_theorems:
solution += "\n\nقضایای مرتبط:\n"
for theorem in relevant_theorems:
solution += f"- {theorem['name']}: {theorem['description']}\n"
logger.info("Synthetic geometry solution generated")
return solution
except Exception as e:
logger.error(f"Error in synthetic geometry solver: {e}")
return f"خطا در حل مسئله با هندسه ترکیبی: {str(e)}"
def theorem_lookup(self, query: str) -> str:
"""
Look up relevant theorems based on query
Args:
query: Search query for theorems
Returns:
Relevant theorems information
"""
try:
relevant_theorems = self._find_relevant_theorems(query)
if not relevant_theorems:
return "هیچ قضیه مرتبطی یافت نشد. لطفاً کلمات کلیدی دیگری امتحان کنید."
result = "قضایای مرتبط:\n\n"
for theorem in relevant_theorems:
result += f"📐 {theorem['name']}\n"
result += f" توضیح: {theorem['description']}\n"
result += f" فرمول: {theorem.get('formula', 'N/A')}\n"
result += f" دسته‌بندی: {theorem['category']}\n"
result += f" سطح: {theorem['difficulty']}\n\n"
logger.info(f"Found {len(relevant_theorems)} relevant theorems")
return result
except Exception as e:
logger.error(f"Error in theorem lookup: {e}")
return f"خطا در جستجوی قضایا: {str(e)}"
def _find_relevant_theorems(self, query: str) -> List[Dict[str, Any]]:
"""
Find relevant theorems based on query
Args:
query: Search query
Returns:
List of relevant theorems
"""
try:
relevant_theorems = []
query_lower = query.lower()
# Simple keyword matching
keywords = {
"مثلث": ["pythagorean", "thales"],
"دایره": ["circle_angle", "tangent", "chord"],
"فیثاغورث": ["pythagorean"],
"تالس": ["thales"],
"مماس": ["tangent"],
"وتر": ["chord"],
"زاویه": ["circle_angle"],
}
for keyword, theorem_keys in keywords.items():
if keyword in query_lower:
for theorem_key in theorem_keys:
if theorem_key in self.theorem_db:
relevant_theorems.append(self.theorem_db[theorem_key])
return relevant_theorems
except Exception as e:
logger.error(f"Error finding relevant theorems: {e}")
return []
def proof_verification(self, proof_statement: str) -> str:
"""
Verify mathematical proofs
Args:
proof_statement: The proof to verify
Returns:
Verification result
"""
try:
verification_prompt = f"""
اثبات زیر را بررسی کنید و صحت آن را تأیید کنید:
{proof_statement}
لطفاً:
1. هر مرحله از اثبات را بررسی کنید
2. منطق ریاضی را تأیید کنید
3. خطاهای احتمالی را شناسایی کنید
4. نتیجه نهایی را مشخص کنید
"""
verification = self.llm(verification_prompt)
logger.info("Proof verification completed")
return verification
except Exception as e:
logger.error(f"Error in proof verification: {e}")
return f"خطا در تأیید اثبات: {str(e)}"
def diagram_generation(self, description: str) -> str:
"""
Generate geometric diagrams
Args:
description: Description of the geometric figure
Returns:
Information about the generated diagram
"""
try:
# Use LLM to analyze the description and create diagram specifications
analysis_prompt = f"""
بر اساس توضیحات زیر، مشخصات نمودار هندسی را تعیین کنید:
{description}
لطفاً:
1. نوع شکل هندسی را مشخص کنید
2. نقاط، خطوط و زاویه‌ها را شناسایی کنید
3. ابعاد و مختصات را تعیین کنید
4. راهنمای رسم نمودار را ارائه دهید
"""
diagram_specs = self.llm(analysis_prompt)
# Create a simple diagram using matplotlib
try:
fig, ax = plt.subplots(1, 1, figsize=(10, 8))
# This is a simplified example - in practice, you'd parse the description
# and create appropriate geometric elements
# Draw a sample triangle
triangle = patches.Polygon(
[(1, 1), (4, 1), (2.5, 3)],
closed=True,
fill=False,
edgecolor="blue",
linewidth=2,
)
ax.add_patch(triangle)
# Add labels
ax.text(1, 0.8, "A", fontsize=12, ha="center")
ax.text(4, 0.8, "B", fontsize=12, ha="center")
ax.text(2.5, 3.2, "C", fontsize=12, ha="center")
ax.set_xlim(0, 5)
ax.set_ylim(0, 4)
ax.set_aspect("equal")
ax.grid(True, alpha=0.3)
ax.set_title("نمودار هندسی نمونه", fontsize=14)
# Save the diagram
diagram_path = f"visualizations/diagram_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
os.makedirs(os.path.dirname(diagram_path), exist_ok=True)
plt.savefig(diagram_path, dpi=300, bbox_inches="tight")
plt.close()
result = f"""
نمودار هندسی ایجاد شد:
{diagram_specs}
فایل نمودار در مسیر زیر ذخیره شد:
{diagram_path}
"""
except Exception as e:
result = f"""
تحلیل نمودار:
{diagram_specs}
خطا در ایجاد نمودار: {str(e)}
"""
logger.info("Diagram generation completed")
return result
except Exception as e:
logger.error(f"Error in diagram generation: {e}")
return f"خطا در ایجاد نمودار: {str(e)}"
def get_tool_info(self) -> Dict[str, Any]:
"""
Get information about available tools
Returns:
Dictionary containing tool information
"""
return {
"tools": [
{
"name": "coordinate_geometry_solver",
"description": "حل مسائل هندسی با استفاده از هندسه تحلیلی",
"parameters": ["problem_description"],
},
{
"name": "synthetic_geometry_solver",
"description": "حل مسائل هندسی با استفاده از هندسه ترکیبی",
"parameters": ["problem_description"],
},
{
"name": "theorem_lookup",
"description": "جستجوی قضایای مرتبط",
"parameters": ["query"],
},
{
"name": "proof_verification",
"description": "تأیید صحت اثبات‌های ریاضی",
"parameters": ["proof_statement"],
},
{
"name": "diagram_generation",
"description": "ایجاد نمودارهای هندسی",
"parameters": ["description"],
},
],
"theorem_database_size": len(self.theorem_db),
"available_theorems": list(self.theorem_db.keys()),
}
def add_theorem(self, theorem_data: Dict[str, Any]):
"""
Add a new theorem to the database
Args:
theorem_data: Dictionary containing theorem information
"""
try:
theorem_id = theorem_data.get("id", f"theorem_{len(self.theorem_db) + 1}")
self.theorem_db[theorem_id] = theorem_data
logger.info(f"Theorem '{theorem_id}' added to database")
except Exception as e:
logger.error(f"Error adding theorem: {e}")
def save_theorem_database(self, file_path: str = None):
"""
Save theorem database to file
Args:
file_path: Path to save the database
"""
try:
if file_path is None:
file_path = (
self.config.get("theorem_lookup", {})
.get("parameters", {})
.get("database_path", "data/theorems/theorems.json")
)
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with open(file_path, "w", encoding="utf-8") as f:
json.dump(self.theorem_db, f, ensure_ascii=False, indent=2)
logger.info(f"Theorem database saved to {file_path}")
except Exception as e:
logger.error(f"Error saving theorem database: {e}")

Xet Storage Details

Size:
17.8 kB
·
Xet hash:
6c2477553c7423de7c3878a8a5ff4f50d20efcd232dd33b293ebba43a986549a

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.