File size: 9,174 Bytes
9f3730d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
import os
from langchain_groq import ChatGroq
from langchain.prompts import PromptTemplate
from langgraph.graph import START, StateGraph, MessagesState
from langgraph.prebuilt import ToolNode, tools_condition
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_community.document_loaders import WikipediaLoader
from langchain_core.messages import HumanMessage
from langchain.tools import tool
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import Runnable
from dotenv import load_dotenv

# Load environment variables from .env
load_dotenv()

# Initialize LLM
def initialize_llm():
    """Initializes the ChatGroq LLM."""
    llm = ChatGroq(
        temperature=0,
        model_name="qwen-qwq-32b",
        groq_api_key=os.getenv("GROQ_API_KEY")
    )
    return llm

# Initialize Tavily Search Tool
def initialize_search_tool():
    """Initializes the TavilySearchResults tool."""
    return TavilySearchResults()

# Weather tool
def get_weather(location: str, search_tool: TavilySearchResults = None) -> str:
    """
    Fetches the current weather information for a given location using Tavily search.
    Args:
        location (str): The name of the location to search for.
        search_tool (TavilySearchResults, optional):  Defaults to None.
    Returns:
        str: The weather information for the specified location.
    """
    if search_tool is None:
        search_tool = initialize_search_tool()
    query = f"current weather in {location}"
    return search_tool.run(query)

# Recommendation chain
def initialize_recommendation_chain(llm: ChatGroq) -> Runnable:
    """
    Initializes the recommendation chain.
    Args:
      llm(ChatGroq):The LLM to use
    Returns:
        Runnable: A runnable sequence to generate recommendations.
    """
    recommendation_prompt = ChatPromptTemplate.from_template("""
    You are a helpful assistant that gives weather-based advice.
    
    Given the current weather condition: "{weather_condition}", provide:
    1. Clothing or activity recommendations suited for this weather.
    2. At least one health tip to stay safe or comfortable in this condition.
    Be concise and clear.
    """)
    return recommendation_prompt | llm

def get_recommendation(weather_condition: str, recommendation_chain: Runnable = None) -> str:
    """
    Gives activity/clothing recommendations and health tips based on the weather condition.
    Args:
        weather_condition (str): The current weather condition.
        recommendation_chain (Runnable, optional): The recommendation chain to use. Defaults to None.
    Returns:
        str:  Recommendations and health tips for the given weather condition.
    """
    if recommendation_chain is None:
        llm = initialize_llm()
        recommendation_chain = initialize_recommendation_chain(llm)
    return recommendation_chain.invoke({"weather_condition": weather_condition})

# Math tools
@tool
def add(x: int, y: int) -> int:
    """
    Adds two integers.
    Args:
        x (int): The first integer.
        y (int): The second integer.
    Returns:
        int: The sum of x and y.
    """
    return x + y

@tool
def subtract(x: int, y: int) -> int:
    """
    Subtracts two integers.
    Args:
        x (int): The first integer.
        y (int): The second integer.
    Returns:
        int: The difference between x and y.
    """
    return x - y

@tool
def multiply(x: int, y: int) -> int:
    """
    Multiplies two integers.
    Args:
        x (int): The first integer.
        y (int): The second integer.
    Returns:
        int: The product of x and y.
    """
    return x * y

@tool
def divide(x: int, y: int) -> float:
    """
    Divides two numbers.
    Args:
        x (int): The numerator.
        y (int): The denominator.
    Returns:
        float: The result of the division.
    Raises:
        ValueError: If y is zero.
    """
    if y == 0:
        raise ValueError("Cannot divide by zero.")
    return x / y

@tool
def square(x: int) -> int:
    """
    Calculates the square of a number.
    Args:
        x (int): The number to square.
    Returns:
        int: The square of x.
    """
    return x * x

@tool
def cube(x: int) -> int:
    """
    Calculates the cube of a number.
    Args:
        x (int): The number to cube.
    Returns:
        int: The cube of x.
    """
    return x * x * x

@tool
def power(x: int, y: int) -> int:
    """
    Raises a number to the power of another number.
    Args:
        x (int): The base number.
        y (int): The exponent.
    Returns:
        int: x raised to the power of y.
    """
    return x ** y

@tool
def factorial(n: int) -> int:
    """
    Calculates the factorial of a non-negative integer.
    Args:
        n (int): The non-negative integer.
    Returns:
        int: The factorial of n.
    Raises:
        ValueError: If n is negative.
    """
    if n < 0:
        raise ValueError("Factorial is not defined for negative numbers.")
    if n == 0 or n == 1:
        return 1
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

@tool
def mean(numbers: list) -> float:
    """
    Calculates the mean of a list of numbers.
    Args:
        numbers (list): A list of numbers.
    Returns:
        float: The mean of the numbers.
    Raises:
        ValueError: If the list is empty.
    """
    if not numbers:
        raise ValueError("The list is empty.")
    return sum(numbers) / len(numbers)

@tool
def standard_deviation(numbers: list) -> float:
    """
    Calculates the standard deviation of a list of numbers.
    Args:
        numbers (list): A list of numbers.
    Returns:
        float: The standard deviation of the numbers.
    Raises:
        ValueError: If the list is empty.
    """
    if not numbers:
        raise ValueError("The list is empty.")
    mean_value = mean(numbers)
    variance = sum((x - mean_value) ** 2 for x in numbers) / len(numbers)
    return variance ** 0.5

# Build the LangGraph
def build_graph():
    """
    Builds the LangGraph with the defined tools and assistant node.
    Returns:
        RunnableGraph: The compiled LangGraph.
    """
    llm = initialize_llm()
    search_tool = initialize_search_tool()
    recommendation_chain = initialize_recommendation_chain(llm)

    @tool
    def weather_tool(location: str) -> str:
        """
        Fetches the weather for a location.
        Args:
            location (str): The location to fetch weather for.
        Returns:
            str: The weather information.
        """
        return get_weather(location, search_tool)
    
    @tool
    def web_search(query: str) -> str:
        """Search the web for a given query and return the summary.
        Args:
            query (str): The search query.
        """
        
        search_tool = TavilySearchResults()
        result = search_tool.run(query)
        return result[0]['content']
    
    @tool
    def wiki_search(query : str) -> str:
        """Search Wikipedia for a given query and return the summary.
        Args:
            query (str): The search query.
        """
    
        search_docs = WikipediaLoader(query=query, load_max_docs=1).load()
        formatted_search_docs = "\n\n----\n\n".join(
            [
                f'<Document Source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}">\n{doc.page_content}\n</Document>'
                for doc in search_docs
            ]
        )
        return formatted_search_docs

    @tool
    def recommendation_tool(weather_condition: str) -> str:
        """
        Provides recommendations based on weather conditions.
        Args:
            weather_condition (str): The weather condition.
        Returns:
            str: The recommendations.
        """
        return get_recommendation(weather_condition, recommendation_chain)

    tools = [weather_tool, recommendation_tool, wiki_search, web_search,
             add, subtract, multiply, divide, square, cube, power, factorial, mean, standard_deviation]

    llm_with_tools = llm.bind_tools(tools)

    def assistant(state: MessagesState):
        """
        Assistant node in the LangGraph.
        Args:
            state (MessagesState): The current state of the conversation.
        Returns:
            dict: The next state of the conversation.
        """
        print("Entering assistant node...")
        response = llm_with_tools.invoke(state["messages"])
        print(f"Assistant says: {response.content}")
        return {"messages": [response]}

    builder = StateGraph(MessagesState)
    builder.add_node("assistant", assistant)
    builder.add_node("tools", ToolNode(tools))
    builder.set_entry_point("assistant")
    builder.add_conditional_edges("assistant", tools_condition)
    builder.add_edge("tools", "assistant")
    return builder.compile()

if __name__ == "__main__":
    graph = build_graph()
    question = "How many albums were pulished by Mercedes Sosa?"
    messages = [HumanMessage(content=question)]
    result = graph.invoke({"messages": messages})
    for msg in result["messages"]:
        msg.pretty_print()