-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
62 lines (47 loc) · 1.43 KB
/
Copy pathmain.py
File metadata and controls
62 lines (47 loc) · 1.43 KB
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
from dotenv import load_dotenv
from langchain_ollama import ChatOllama
from langchain_tavily import TavilySearch
from langchain.agents import create_agent
from langchain_core.messages import ToolMessage,HumanMessage
load_dotenv()
# LLM
llm = ChatOllama(model="qwen3:8b ")
# Tool
search_tool = TavilySearch()
# Agent
agent = create_agent(
model=llm,
tools=[search_tool], # The agent rewrites the tool input based on the conversation context.
system_prompt="""
You are a helpful assistant.
Use the Tavily search tool whenever the user asks about:
- latest versions
- current prices
- current leaders
- today's news
- weather
- stock prices
- cryptocurrency prices
- recent events
- anything containing words like:
latest, current, today, recent, now, this week, this month, this year
For timeless knowledge questions, answer directly without searching.
Keep responses concise unless the user asks for more detail.
"""
)
def get_answer(question, chat_history):
response = agent.invoke(
{
"messages": [
*chat_history,
HumanMessage(content=question)
]
}
)
answer = response["messages"][-1].content
used_search = any(
isinstance(msg, ToolMessage)
for msg in response["messages"]
)
source = "🌐 Web Search" if used_search else "🧠 Model Knowledge"
return answer, source