-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
66 lines (55 loc) · 1.95 KB
/
Copy pathmain.py
File metadata and controls
66 lines (55 loc) · 1.95 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
63
64
65
66
from typing import TypedDict
from dotenv import load_dotenv
from langchain.agents import create_agent
from pydantic import BaseModel
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import PydanticOutputParser
from langchain.agents.middleware import ModelRequest, dynamic_prompt
from tools import wiki_tool, save_to_txt
load_dotenv()
class ResearchResponse(BaseModel):
topic:str
summary:str
sources:list[str]
tools_used:list[str]
class Context(TypedDict):
user_role:str
@dynamic_prompt
def prompt(request: ModelRequest) -> str:
user_role = request.runtime.context.get('user_role',"user")
base_prompt = (
"You are a research assistant that always gives detailed and reliable information. "
"After generating the research result, always call the `save_to_txt` tool "
"to save the output to a text file."
)
if user_role == "student":
return f"{base_prompt} Explain concepts simply and avoid jargon."
elif user_role == "researcher":
return f"{base_prompt} Provide detailed technical responses."
return base_prompt
llm = ChatOpenAI(model="gpt-4o-mini")
parser = PydanticOutputParser(pydantic_object=ResearchResponse)
tools = [wiki_tool, save_to_txt]
agent = create_agent(
model="gpt-4o-mini",
tools=tools,
middleware=[prompt],
context_schema=Context,
)
query = input("What can i help you research? ")
raw_response = agent.invoke(
{"messages": [{"role": "user", "content": query}]},
context={"user_role": "researcher"} # örnek role
)
messages = raw_response.get("messages", [])
last_ai_message = None
for m in reversed(messages):
if m.__class__.__name__ == "AIMessage" and m.content:
last_ai_message = m.content
break
if not last_ai_message:
print("⚠️ No AI message found in response.")
else:
print("\n🧠 --- Research Output ---\n")
print(last_ai_message.replace(". ", ".\n"))
print("\n--------------------------")