File size: 9,033 Bytes
3708220
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df7388a
 
 
 
 
 
 
 
 
3708220
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df7388a
 
 
 
 
3708220
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df7388a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3708220
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
"""
LangChain-compatible tools for the LangGraph multi-agent system

This module provides LangChain tools that work properly with LangGraph agents,
replacing the LlamaIndex tools with native LangChain implementations.
"""

import os
import wikipedia
import arxiv
from typing import List, Optional, Type
from langchain_core.tools import BaseTool, tool
from pydantic import BaseModel, Field
from huggingface_hub import list_models
from observability import tool_span

# Defensive import for langchain_tavily
try:
    from langchain_tavily import TavilySearch
    TAVILY_AVAILABLE = True
except ImportError as e:
    print(f"Warning: langchain_tavily not available: {e}")
    TAVILY_AVAILABLE = False
    TavilySearch = None


# Pydantic schemas for tool inputs
class WikipediaSearchInput(BaseModel):
    """Input for Wikipedia search tool."""
    query: str = Field(description="The search query for Wikipedia")


class ArxivSearchInput(BaseModel):
    """Input for ArXiv search tool."""
    query: str = Field(description="The search query for ArXiv papers")


class HubStatsInput(BaseModel):
    """Input for Hugging Face Hub stats tool."""
    author: str = Field(description="The author/organization name on Hugging Face Hub")


class TavilySearchInput(BaseModel):
    """Input for Tavily search tool."""
    query: str = Field(description="The search query for web search")


# LangChain-compatible tool implementations

@tool("wikipedia_search", args_schema=WikipediaSearchInput)
def wikipedia_search_tool(query: str) -> str:
    """Search Wikipedia for information about a topic."""
    try:
        with tool_span("wikipedia_search", metadata={"query": query}):
            # Use wikipedia library directly
            try:
                # Search for pages
                search_results = wikipedia.search(query, results=3)
                if not search_results:
                    return f"No Wikipedia results found for '{query}'"
                
                # Get the first page that works
                for page_title in search_results:
                    try:
                        page = wikipedia.page(page_title)
                        # Get summary and first few paragraphs
                        content = page.summary
                        if len(content) > 1000:
                            content = content[:1000] + "..."
                        
                        return f"Wikipedia: {page.title}\n\nURL: {page.url}\n\nSummary:\n{content}"
                    
                    except wikipedia.exceptions.DisambiguationError as e:
                        # Try the first suggestion
                        try:
                            page = wikipedia.page(e.options[0])
                            content = page.summary
                            if len(content) > 1000:
                                content = content[:1000] + "..."
                            return f"Wikipedia: {page.title}\n\nURL: {page.url}\n\nSummary:\n{content}"
                        except:
                            continue
                    except:
                        continue
                
                return f"Could not retrieve Wikipedia content for '{query}'"
                        
            except Exception as e:
                return f"Wikipedia search error: {str(e)}"
                
    except Exception as e:
        return f"Wikipedia search failed: {str(e)}"


@tool("arxiv_search", args_schema=ArxivSearchInput)
def arxiv_search_tool(query: str) -> str:
    """Search ArXiv for academic papers."""
    try:
        with tool_span("arxiv_search", metadata={"query": query}):
            # Use arxiv library
            search = arxiv.Search(
                query=query,
                max_results=3,
                sort_by=arxiv.SortCriterion.Relevance
            )
            
            results = []
            for paper in search.results():
                result = f"""Title: {paper.title}
Authors: {', '.join([author.name for author in paper.authors])}
Published: {paper.published.strftime('%Y-%m-%d')}
URL: {paper.entry_id}
Summary: {paper.summary[:500]}..."""
                results.append(result)
            
            if results:
                return f"ArXiv Search Results for '{query}':\n\n" + "\n\n---\n\n".join(results)
            else:
                return f"No ArXiv papers found for '{query}'"
                
    except Exception as e:
        return f"ArXiv search failed: {str(e)}"


@tool("huggingface_hub_stats", args_schema=HubStatsInput)
def huggingface_hub_stats_tool(author: str) -> str:
    """Get statistics for a Hugging Face Hub author."""
    try:
        with tool_span("huggingface_hub_stats", metadata={"author": author}):
            models = list(list_models(author=author, sort="downloads", direction=-1, limit=5))
            if models:
                results = []
                for i, model in enumerate(models, 1):
                    results.append(f"{i}. {model.id} - {model.downloads:,} downloads")
                
                top_model = models[0]
                summary = f"Top 5 models by {author}:\n" + "\n".join(results)
                summary += f"\n\nMost popular: {top_model.id} with {top_model.downloads:,} downloads"
                return summary
            else:
                return f"No models found for author '{author}'"
                
    except Exception as e:
        return f"Hub stats error: {str(e)}"


@tool("tavily_search_results_json", args_schema=TavilySearchInput)
def tavily_search_fallback_tool(query: str) -> str:
    """Fallback web search tool when Tavily is not available."""
    try:
        with tool_span("tavily_search_fallback", metadata={"query": query}):
            # Simple fallback using DuckDuckGo or similar
            import requests
            
            # Use a simple web search API as fallback
            # This is a basic implementation - in production you'd want a proper search API
            search_url = f"https://duckduckgo.com/lite/?q={query}"
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            }
            
            try:
                response = requests.get(search_url, headers=headers, timeout=10)
                if response.status_code == 200:
                    return f"Web search completed for '{query}'. Found general web results (fallback mode - Tavily not available)."
                else:
                    return f"Web search failed for '{query}' (status: {response.status_code})"
            except Exception as e:
                return f"Web search error for '{query}': {str(e)}"
                
    except Exception as e:
        return f"Web search failed: {str(e)}"


def get_tavily_search_tool() -> BaseTool:
    """Get the Tavily search tool from LangChain community, with fallback."""
    if TAVILY_AVAILABLE and TavilySearch:
        try:
            return TavilySearch(
                api_key=os.getenv("TAVILY_API_KEY"),
                max_results=6,
                include_answer=True,
                include_raw_content=True,
                description="Search the web for current information and facts"
            )
        except Exception as e:
            print(f"Warning: Failed to create TavilySearch tool: {e}")
            return tavily_search_fallback_tool
    else:
        print("Warning: Using fallback search tool (Tavily not available)")
        return tavily_search_fallback_tool


def get_calculator_tools() -> List[BaseTool]:
    """Get calculator tools as LangChain tools."""
    
    @tool("multiply")
    def multiply(a: float, b: float) -> float:
        """Multiply two numbers."""
        return a * b
    
    @tool("add") 
    def add(a: float, b: float) -> float:
        """Add two numbers."""
        return a + b
    
    @tool("subtract")
    def subtract(a: float, b: float) -> float:
        """Subtract two numbers."""
        return a - b
    
    @tool("divide")
    def divide(a: float, b: float) -> float:
        """Divide two numbers."""
        if b == 0:
            raise ValueError("Cannot divide by zero")
        return a / b
    
    @tool("modulus")
    def modulus(a: int, b: int) -> int:
        """Get the modulus of two integers."""
        if b == 0:
            raise ValueError("Cannot modulo by zero")
        return a % b
    
    return [multiply, add, subtract, divide, modulus]


def get_research_tools() -> List[BaseTool]:
    """Get all research tools for the research agent."""
    tools = [
        get_tavily_search_tool(),
        wikipedia_search_tool,
        arxiv_search_tool,
    ]
    return tools


def get_code_tools() -> List[BaseTool]:
    """Get all code/computation tools for the code agent."""
    tools = get_calculator_tools()
    tools.append(huggingface_hub_stats_tool)
    return tools


def get_all_tools() -> List[BaseTool]:
    """Get all available tools."""
    return get_research_tools() + get_code_tools()