-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
211 lines (174 loc) · 7.93 KB
/
Copy pathagent.py
File metadata and controls
211 lines (174 loc) · 7.93 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
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
# agent.py
import logging
from typing import Literal
from pydantic import BaseModel, Field
from langchain.chat_models import init_chat_model
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
from langchain_core.runnables import RunnableConfig
from langgraph.types import Command
from langgraph.graph import END
from config import Configuration
from state import AgentState, ResearchQuestion
from prompt import lead_researcher_prompt
logger = logging.getLogger(__name__)
# Global configurable model
configurable_model = init_chat_model(
configurable_fields=("model", "max_tokens", "api_key", "base_url", "model_provider"),
)
# Structured output models
class ClarifyWithUser(BaseModel):
"""Model for user clarification requests."""
need_clarification: bool = Field(
description="Whether the user needs to be asked a clarifying question."
)
question: str = Field(
description="Question to ask the user. Empty if no clarification needed."
)
verification: str = Field(
description="Verification message that research will start."
)
class ClarifyAgent:
"""Agent for checking if user query needs clarification."""
def __init__(self):
"""Initialize ClarifyAgent."""
logger.info("ClarifyAgent initialized")
async def invoke(
self,
state: AgentState,
config: RunnableConfig
) -> Command[Literal["write_research_brief", "__end__"]]:
"""Check if user query needs clarification."""
logger.info(f"Clarify agent started. Query: '{state.get('query', '')}'")
try:
configurable = Configuration.from_runnable_config(config)
# تنظیم model configuration - بدون max_completion_tokens
model_config = {
"model": configurable.clarify_model,
"api_key": configurable.NVIDIA_api_key,
"base_url": configurable.research_base_url,
"model_provider": "openai",
# حذف max_tokens - NVIDIA از max_completion_tokens پشتیبانی نمیکند
# "max_tokens": configurable.clarify_max_tokens,
"tags": ["langsmith:nostream"]
}
# استفاده از method="json_mode" به جای json_schema
model = (
configurable_model
.with_structured_output(
ClarifyWithUser,
method="json_mode", # کلیدی! به جای json_schema
include_raw=False
)
.with_retry(stop_after_attempt=configurable.max_structured_output_retries)
.with_config(model_config)
)
# Format messages - اضافه کردن دستورالعمل JSON
messages_str = "\n".join([str(msg.content) for msg in state.get('messages', [])])
prompt = f"""You must respond with valid JSON matching this schema:
{{
"need_clarification": boolean,
"question": "string (question to ask user, empty if no clarification needed)",
"verification": "string (verification message that research will start)"
}}
{configurable.clarify_prompt.format(query=state.get('query', ''), messages=messages_str)}
Respond ONLY with valid JSON, no other text."""
response = await model.ainvoke(prompt)
logger.info(f"Clarification needed: {response.need_clarification}")
if response.need_clarification:
logger.info(f"Asking clarification: {response.question}")
return Command(
goto="__end__",
update={"messages": [AIMessage(content=response.question)]}
)
else:
logger.info(f"Proceeding to research: {response.verification}")
return Command(
goto="write_research_brief",
update={"messages": [AIMessage(content=response.verification)]}
)
except Exception as e:
logger.error(f"Error in clarify_agent: {e}", exc_info=True)
return Command(
goto="write_research_brief",
update={"messages": [AIMessage(content="Processing your request...")]}
)
class WriteResearchBrief:
"""Agent for transforming user messages into structured research brief."""
def __init__(self):
"""Initialize WriteResearchBrief."""
logger.info("WriteResearchBrief initialized")
async def invoke(
self,
state: AgentState,
config: RunnableConfig
) -> Command[Literal["__end__"]]:
"""Transform user messages into research brief."""
logger.info("Starting research brief generation...")
try:
configurable = Configuration.from_runnable_config(config)
# تنظیم model configuration - بدون max_completion_tokens
model_config = {
"model": configurable.research_model,
"api_key": configurable.NVIDIA_api_key,
"base_url": configurable.research_base_url,
"model_provider": "openai",
# حذف max_tokens
# "max_tokens": configurable.research_model_max_tokens,
"tags": ["langsmith:nostream"]
}
# استفاده از method="json_mode"
model = (
configurable_model
.with_structured_output(
ResearchQuestion,
method="json_mode", # کلیدی!
include_raw=False
)
.with_retry(stop_after_attempt=configurable.max_structured_output_retries)
.with_config(model_config)
)
# آمادهسازی messages
messages_str = "\n".join([
str(msg.content) for msg in state.get("messages", [])
])
if not messages_str.strip():
messages_str = state.get("query", "")
# اضافه کردن دستورالعمل JSON
prompt = f"""You must respond with valid JSON matching this schema:
{{
"research_brief": "string (detailed research brief)"
}}
{configurable.research_topic_prompt.format(messages=messages_str)}
Respond ONLY with valid JSON, no other text."""
logger.info(f"Calling model for research brief...")
response = await model.ainvoke(prompt)
logger.info(f"Research brief created: {response.research_brief[:100]}...")
# ساخت supervisor prompt
supervisor_system_prompt = lead_researcher_prompt.format(
max_concurrent_research_units=configurable.max_concurrent_research_units,
max_researcher_iterations=configurable.max_researcher_iterations
)
return Command(
goto="__end__",
update={
"research_brief": response.research_brief,
"supervisor_messages": {
"type": "override",
"value": [
SystemMessage(content=supervisor_system_prompt),
HumanMessage(content=response.research_brief)
]
},
"messages": [
AIMessage(content=f"Research brief created:\n\n{response.research_brief}")
]
}
)
except Exception as e:
logger.error(f"Error in write_research_brief: {e}", exc_info=True)
return Command(
goto="__end__",
update={
"messages": [AIMessage(content=f"Error: {str(e)}")]
}
)