File size: 9,979 Bytes
4ef118d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
"""
Research plan generation services using Agno ReasoningTools.

This module replaces the original prompt-based plan generation with an
agent-based approach using ReasoningTools for transparent, structured planning.
"""

from __future__ import annotations

import json
from collections.abc import AsyncGenerator
from types import SimpleNamespace
from typing import Any

from agno.agent import Agent
from agno.tools.reasoning import ReasoningTools

from ..prompts import ACADEMIC_PLANNER_PROMPT, GENERAL_PLANNER_PROMPT
from .agent_registry import _apply_model_settings, _build_model


async def generate_research_plan(
    *,
    provider: str,
    user_message: str,
    api_key: str,
    base_url: str | None = None,
    model: str | None = None,
    temperature: float | None = None,
    top_p: float | None = None,
    top_k: float | None = None,
    frequency_penalty: float | None = None,
    presence_penalty: float | None = None,
    thinking: Any = None,
) -> str:
    """
    Generate a research plan using Agent with ReasoningTools.

    This replaces the original prompt-based approach with an agent that uses
    think() and analyze() tools for transparent, structured planning.
    """
    # Build model using the same approach as agent_registry
    plan_model = _build_model(provider, api_key, base_url, model)

    # Apply model settings (temperature, top_p, etc.)
    request = SimpleNamespace(
        provider=provider,
        temperature=temperature,
        top_p=top_p,
        top_k=top_k,
        frequency_penalty=frequency_penalty,
        presence_penalty=presence_penalty,
        thinking=thinking,
    )
    _apply_model_settings(plan_model, request)

    # Create planner agent with ReasoningTools
    planner = Agent(
        model=plan_model,
        tools=[ReasoningTools(
            add_instructions=True,
            enable_think=True,
            enable_analyze=True
        )],
        instructions=GENERAL_PLANNER_PROMPT
    )

    # Run the planner
    response = await planner.arun(user_message)

    # Extract content and format as JSON string (for backward compatibility)
    if hasattr(response, 'content'):
        plan_text = response.content
    else:
        plan_text = str(response)

    plan_text = plan_text.strip()

    # Remove markdown code blocks if present
    if plan_text.startswith("```"):
        parts = plan_text.split("```")
        if len(parts) >= 2:
            plan_text = parts[1]
            if plan_text.startswith("json"):
                plan_text = plan_text[4:]
            plan_text = plan_text.rstrip("`").strip()

    # Validate it's valid JSON
    try:
        plan = json.loads(plan_text)
        return json.dumps(plan, ensure_ascii=True, indent=2)
    except json.JSONDecodeError:
        return plan_text


async def generate_academic_research_plan(
    *,
    provider: str,
    user_message: str,
    api_key: str,
    base_url: str | None = None,
    model: str | None = None,
    temperature: float | None = None,
    top_p: float | None = None,
    top_k: float | None = None,
    frequency_penalty: float | None = None,
    presence_penalty: float | None = None,
    thinking: Any = None,
) -> str:
    """
    Generate an academic research plan using Agent with ReasoningTools.
    """
    # Build model using the same approach as agent_registry
    plan_model = _build_model(provider, api_key, base_url, model)

    # Apply model settings
    request = SimpleNamespace(
        provider=provider,
        temperature=temperature,
        top_p=top_p,
        top_k=top_k,
        frequency_penalty=frequency_penalty,
        presence_penalty=presence_penalty,
        thinking=thinking,
    )
    _apply_model_settings(plan_model, request)

    # Create academic planner agent with ReasoningTools
    planner = Agent(
        model=plan_model,
        tools=[ReasoningTools(
            add_instructions=True,
            enable_think=True,
            enable_analyze=True
        )],
        instructions=ACADEMIC_PLANNER_PROMPT
    )

    # Run the planner with the user message
    response = await planner.arun(user_message)

    # Extract content and format as JSON string
    if hasattr(response, 'content'):
        plan_text = response.content
    else:
        plan_text = str(response)

    plan_text = plan_text.strip()

    # Remove markdown code blocks if present
    if plan_text.startswith("```"):
        parts = plan_text.split("```")
        if len(parts) >= 2:
            plan_text = parts[1]
            if plan_text.startswith("json"):
                plan_text = plan_text[4:]
            plan_text = plan_text.rstrip("`").strip()

    # Validate and format
    try:
        plan = json.loads(plan_text)
        return json.dumps(plan, ensure_ascii=True, indent=2)
    except json.JSONDecodeError:
        return plan_text


async def stream_generate_research_plan(
    *,
    provider: str,
    user_message: str,
    api_key: str,
    base_url: str | None = None,
    model: str | None = None,
    temperature: float | None = None,
    top_p: float | None = None,
    top_k: float | None = None,
    frequency_penalty: float | None = None,
    presence_penalty: float | None = None,
    thinking: Any = None,
) -> AsyncGenerator[dict[str, Any], None]:
    """
    Stream research plan generation using Agent with ReasoningTools.

    This is the streaming version of generate_research_plan that yields
    events as the agent plans using think() and analyze() tools.
    """
    # Build model using the same approach as agent_registry
    plan_model = _build_model(provider, api_key, base_url, model)

    # Apply model settings (temperature, top_p, etc.)
    request = SimpleNamespace(
        provider=provider,
        temperature=temperature,
        top_p=top_p,
        top_k=top_k,
        frequency_penalty=frequency_penalty,
        presence_penalty=presence_penalty,
        thinking=thinking,
    )
    _apply_model_settings(plan_model, request)

    # Create planner agent with ReasoningTools
    planner = Agent(
        model=plan_model,
        tools=[ReasoningTools(
            add_instructions=True,
            enable_think=True,
            enable_analyze=True
        )],
        instructions=GENERAL_PLANNER_PROMPT
    )

    # Stream the planner execution
    full_content = ""
    async for chunk in planner.arun(user_message, stream=True):
        chunk_text = ""
        if hasattr(chunk, "content"):
            chunk_text = chunk.content or ""
        elif isinstance(chunk, str):
            chunk_text = chunk
        else:
            chunk_text = str(chunk)

        if chunk_text:
            full_content += chunk_text
            yield {"type": "text", "content": chunk_text}

    # Clean and finalize the plan
    plan_text = full_content.strip()

    # Remove markdown code blocks if present
    if plan_text.startswith("```"):
        parts = plan_text.split("```")
        if len(parts) >= 2:
            plan_text = parts[1]
            if plan_text.startswith("json"):
                plan_text = plan_text[4:]
            plan_text = plan_text.rstrip("`").strip()

    # Validate and format
    try:
        plan = json.loads(plan_text)
        final_plan = json.dumps(plan, ensure_ascii=True, indent=2)
        yield {"type": "done", "content": final_plan}
    except json.JSONDecodeError:
        yield {"type": "done", "content": plan_text}


async def stream_generate_academic_research_plan(
    *,
    provider: str,
    user_message: str,
    api_key: str,
    base_url: str | None = None,
    model: str | None = None,
    temperature: float | None = None,
    top_p: float | None = None,
    top_k: float | None = None,
    frequency_penalty: float | None = None,
    presence_penalty: float | None = None,
    thinking: Any = None,
) -> AsyncGenerator[dict[str, Any], None]:
    """
    Stream academic research plan generation using Agent with ReasoningTools.

    This is the streaming version of generate_academic_research_plan that yields
    events as the agent plans using think() and analyze() tools.
    """
    # Build model using the same approach as agent_registry
    plan_model = _build_model(provider, api_key, base_url, model)

    # Apply model settings
    request = SimpleNamespace(
        provider=provider,
        temperature=temperature,
        top_p=top_p,
        top_k=top_k,
        frequency_penalty=frequency_penalty,
        presence_penalty=presence_penalty,
        thinking=thinking,
    )
    _apply_model_settings(plan_model, request)

    # Create academic planner agent with ReasoningTools
    planner = Agent(
        model=plan_model,
        tools=[ReasoningTools(
            add_instructions=True,
            enable_think=True,
            enable_analyze=True
        )],
        instructions=ACADEMIC_PLANNER_PROMPT
    )

    # Stream the planner execution
    full_content = ""
    async for chunk in planner.arun(user_message, stream=True):
        chunk_text = ""
        if hasattr(chunk, "content"):
            chunk_text = chunk.content or ""
        elif isinstance(chunk, str):
            chunk_text = chunk
        else:
            chunk_text = str(chunk)

        if chunk_text:
            full_content += chunk_text
            yield {"type": "text", "content": chunk_text}

    # Clean and finalize the plan
    plan_text = full_content.strip()

    # Remove markdown code blocks if present
    if plan_text.startswith("```"):
        parts = plan_text.split("```")
        if len(parts) >= 2:
            plan_text = parts[1]
            if plan_text.startswith("json"):
                plan_text = plan_text[4:]
            plan_text = plan_text.rstrip("`").strip()

    # Validate and format
    try:
        plan = json.loads(plan_text)
        final_plan = json.dumps(plan, ensure_ascii=True, indent=2)
        yield {"type": "done", "content": final_plan}
    except json.JSONDecodeError:
        yield {"type": "done", "content": plan_text}