Spaces:
Sleeping
Sleeping
File size: 16,659 Bytes
944f820 | 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 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 | """
cross_module_prompts.py
-----------------------
System prompts and prompt builders for cross-module codebase queries.
Cross-module queries reason across multiple modules simultaneously.
Two subtypes handled by ONE system prompt with internal classification:
1. dependency_analysis β what does function X depend on, what depends on it
2. impact_analysis β if function X changes, what breaks and where
The LLM receives:
- Primary function context (from vector_store / retriever)
- Dependency context (from call_graph β callers and callees)
- Call graph metadata (structured dependency relationships)
Depends on:
- rich (for __main__ preview only)
"""
# ββ Shared Rules ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
_SHARED_RULES = """
STRICT FORMATTING RULES:
- Respond ONLY in valid markdown.
- Use headers (##, ###) to separate sections clearly.
- Use triple backtick code blocks for flow diagrams and signatures.
- Use markdown tables for dependency and impact listings.
- Use bullet points for risk assessments and recommendations.
- Do NOT include conversational filler, preamble, or apologies.
- Do NOT say "Based on the context provided" or similar phrases.
- Be precise and technical. Assume the reader is a senior developer.
- Explicitly state cross-module boundaries using module names.
- If a dependency cannot be resolved from context, list it as unresolved.
- Always include a ## Limitations section for missing context.
"""
# ββ Subtype Classification (embedded in system prompt) ββββββββββββββββββββββββ
_SUBTYPE_DEFINITIONS = """
QUERY CLASSIFICATION β internally classify every query as ONE of:
TYPE D β Dependency Analysis
Triggered when developer asks:
- "What does X depend on?"
- "What calls X?"
- "What does X call?"
- "What are the dependencies of X?"
- "Who uses X?"
- "What modules interact with X?"
- "Show me the call chain for X"
TYPE E β Impact Analysis
Triggered when developer asks:
- "What breaks if X changes?"
- "How does changing X affect Y?"
- "What is the impact of modifying X?"
- "If I change X, what else do I need to update?"
- "What are the side effects of changing X across modules?"
- "How far does X's influence reach?"
If the query mentions both dependency and impact, classify as TYPE E
since impact analysis subsumes dependency analysis.
If ambiguous, default to TYPE D.
"""
# ββ Cross-Module System Prompt ββββββββββββββββββββββββββββββββββββββββββββββββ
CROSS_MODULE_SYSTEM = f"""
You are an expert software architect performing cross-module dependency
and impact analysis on a monolithic Python codebase.
Your task is to reason across multiple modules simultaneously,
tracing function dependencies and assessing the blast radius of changes.
You are strictly not allowed to do any task outside of this scope no matter the context.
If a function or code is not available in codebase, just return "The function/class might
not be indexed for explanation. Please check if it's available in codebase."
You will receive:
1. PRIMARY CONTEXT β the target function/class retrieved from the vector store
2. DEPENDENCY CONTEXT β functions this target calls and functions that call it
3. CALL GRAPH DATA β structured JSON of the dependency relationships
Use ALL three sources together. Prioritize CALL GRAPH DATA for structure,
PRIMARY and DEPENDENCY CONTEXT for semantic understanding.
{_SHARED_RULES}
{_SUBTYPE_DEFINITIONS}
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
RESPONSE SCHEMAS β use the schema matching your classified type:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
βββ TYPE D β Dependency Analysis βββ
## Dependency Analysis: `<function_name>`
**Module:** `<module>` | **File:** `<file>` | **Class:** `<class or top-level>`
## Summary
2-3 sentences describing the function's role in the broader system
and its connectivity to other modules.
## Outgoing Dependencies (What it calls)
| Function | Class | Module | File | Relationship |
|----------|-------|--------|------|-------------|
| ... | ... | ... | ... | direct call |
## Incoming Dependencies (What calls it)
| Function | Class | Module | File | Relationship |
|----------|-------|--------|------|-------------|
| ... | ... | ... | ... | direct call |
## Call Chain
```
[caller_2] β [caller_1] β [<function_name>] β [callee_1] β [callee_2]
```
## Cross-Module Boundaries
Bullet points identifying which module boundaries this function crosses,
and what data or control passes across those boundaries.
## Unresolved Dependencies
List any calls that could not be traced to a known function in the index.
## Limitations
Any gaps in the analysis due to missing context.
βββ TYPE E β Impact Analysis βββ
## Impact Analysis: `<function_name>`
**Module:** `<module>` | **File:** `<file>` | **Class:** `<class or top-level>`
## Proposed Change
Restate what the developer wants to change, clearly and precisely.
If no specific change is mentioned, analyze general modification impact.
## Direct Impact
What changes immediately inside this function and its direct callers.
## Ripple Effects
| Level | Affected Function | Class | Module | Impact Description | Risk |
|-------|-------------------|-------|--------|--------------------|------|
| 1 | ... | ... | ... | ... | Low/Medium/High |
| 2 | ... | ... | ... | ... | Low/Medium/High |
## Cross-Module Impact Map
```
[<function_name>] (changed)
β
[Level 1: direct callers] β <module_a>, <module_b>
β
[Level 2: indirect callers] β <module_c>
```
## Risk Assessment
- **Overall risk:** Low / Medium / High
- **Reason:** <why this risk level>
- **Most vulnerable function:** <which function is most at risk and why>
## Recommendations
- **Before changing:** <what to check or prepare>
- **After changing:** <what to test or update>
- **Safe change strategy:** <how to minimize blast radius>
## Unresolved Dependencies
List any functions in the impact chain that could not be fully traced.
## Limitations
Any gaps in the analysis due to missing context.
""".strip()
# ββ User Prompt Builder βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def build_cross_module_user_prompt(primary_context: str,
dependency_context: str,
call_graph_data: dict,
query: str,
function_name: str,
class_name: str = "") -> str:
"""
Build the user prompt for a cross-module query.
Args:
primary_context: Retrieved context for the target function.
dependency_context: Retrieved context for its dependencies.
call_graph_data: Dict from CallGraph containing calls/called_by.
query: The developer's natural language query.
function_name: Name of the target function.
class_name: Optional class name if it's a method.
Returns:
Formatted user prompt string.
"""
import json
scope = (
f"Method `{class_name}.{function_name}`"
if class_name
else f"Function `{function_name}`"
)
# Serialize call graph data cleanly
call_graph_str = json.dumps(call_graph_data, indent=2)
return f"""
SUBJECT: {scope}
βββ PRIMARY CONTEXT βββββββββββββββββββββββββββββββββββββββββββ
{primary_context}
βββ DEPENDENCY CONTEXT ββββββββββββββββββββββββββββββββββββββββ
{dependency_context if dependency_context.strip() else "No dependency context retrieved."}
βββ CALL GRAPH DATA βββββββββββββββββββββββββββββββββββββββββββ
{call_graph_str}
βββ DEVELOPER QUERY βββββββββββββββββββββββββββββββββββββββββββ
{query}
Classify this query as Type D or Type E internally.
Then respond using the exact schema for the classified type.
Do not mention the type classification in your response.
Trace ALL cross-module boundaries explicitly using module names.
""".strip()
# ββ Follow-up Prompt Builder ββββββββββββββββββββββββββββββββββββββββββββββββββ
CROSS_MODULE_FOLLOWUP_SYSTEM = """
You are an expert software architect continuing a cross-module dependency
or impact analysis discussion about a monolithic Python codebase.
The developer has a follow-up question after your previous analysis.
Use the same context, call graph, and your previous response to answer.
STRICT FORMATTING RULES:
- Respond ONLY in valid markdown.
- Be concise β the developer already has your full analysis.
- Focus only on what was asked in the follow-up.
- Do NOT repeat your previous full analysis.
- Always name modules explicitly when referencing cross-module relationships.
""".strip()
def build_cross_module_followup_prompt(previous_response: str,
followup_query: str,
primary_context: str,
dependency_context: str,
call_graph_data: dict) -> str:
"""
Build a follow-up user prompt for a cross-module conversation.
Args:
previous_response: The LLM's previous cross-module response.
followup_query: The developer's follow-up question.
primary_context: Original primary context.
dependency_context: Original dependency context.
call_graph_data: Original call graph data.
Returns:
Formatted follow-up user prompt string.
"""
import json
return f"""
βββ PRIMARY CONTEXT βββββββββββββββββββββββββββββββββββββββββββ
{primary_context}
βββ DEPENDENCY CONTEXT ββββββββββββββββββββββββββββββββββββββββ
{dependency_context if dependency_context.strip() else "No dependency context retrieved."}
βββ CALL GRAPH DATA βββββββββββββββββββββββββββββββββββββββββββ
{json.dumps(call_graph_data, indent=2)}
βββ YOUR PREVIOUS ANALYSIS ββββββββββββββββββββββββββββββββββββ
{previous_response}
βββ DEVELOPER FOLLOW-UP βββββββββββββββββββββββββββββββββββββββ
{followup_query}
Answer the follow-up using the context and your previous analysis.
Name all modules explicitly when referencing cross-module relationships.
""".strip()
# ββ Call Graph Data Builder βββββββββββββββββββββββββββββββββββββββββββββββββββ
def build_call_graph_payload(function_name: str,
calls: list,
called_by: list,
impact: dict) -> dict:
"""
Build a clean structured dict from CallGraph data to inject
into the cross-module prompt.
Args:
function_name: Target function name.
calls: List of CallNode objects (outgoing).
called_by: List of CallNode objects (incoming).
impact: Dict of impact levels from CallGraph.get_impact().
Returns:
Clean dict safe for JSON serialization.
"""
def node_to_dict(node) -> dict:
return {
"name": node.name,
"class_name": node.class_name,
"module": node.module,
"file": node.file,
}
impact_serialized = {}
for level, nodes in impact.items():
impact_serialized[level] = [node_to_dict(n) for n in nodes]
return {
"target_function": function_name,
"calls": [node_to_dict(n) for n in calls],
"called_by": [node_to_dict(n) for n in called_by],
"impact_chain": impact_serialized,
}
# ββ Prompt Accessor βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def get_cross_module_system_prompt(followup: bool = False) -> str:
"""
Return the cross-module system prompt.
Args:
followup: If True, returns the follow-up system prompt.
Returns:
System prompt string.
"""
return CROSS_MODULE_FOLLOWUP_SYSTEM if followup else CROSS_MODULE_SYSTEM
# ββ Entry Point (preview prompts) βββββββββββββββββββββββββββββββββββββββββββββ
if __name__ == "__main__":
from rich.console import Console
from rich.panel import Panel
from rich.rule import Rule
console = Console()
sample_primary = """
--- Chunk 1 (function: extract_function_types) ---
Scope: top-level function
Function: extract_function_types
Module: refurb
File: refurb/loader.py
Signature: def extract_function_types(func: Any) -> Generator[type[Node], None, None]
Docstring: No docstring provided.
Calls: list, callable, TypeError, signature, isinstance
""".strip()
sample_dependency = """
--- Chunk 1 (function: load_checks) ---
Scope: top-level function
Function: load_checks
Module: refurb
File: refurb/main.py
Signature: def load_checks(path: str) -> list[Check]
Calls: extract_function_types, import_module
--- Chunk 2 (function: run) ---
Class: Router
Module: refurb
File: refurb/main.py
Signature: def run(args: list[str]) -> int
Calls: load_checks, parse_args
""".strip()
sample_call_graph = build_call_graph_payload(
function_name="extract_function_types",
calls=[],
called_by=[],
impact={},
)
queries = [
("What does extract_function_types depend on and what depends on it?",
"Type D β Dependency Analysis"),
("What breaks if I change the return type of extract_function_types?",
"Type E β Impact Analysis"),
]
console.print(Rule("[bold cyan]Cross-Module β System Prompt[/bold cyan]"))
console.print(Panel(
CROSS_MODULE_SYSTEM,
border_style="cyan",
padding=(1, 2),
))
for query, label in queries:
console.print(Rule(f"[bold magenta]User Prompt β {label}[/bold magenta]"))
user_prompt = build_cross_module_user_prompt(
primary_context=sample_primary,
dependency_context=sample_dependency,
call_graph_data=sample_call_graph,
query=query,
function_name="extract_function_types",
)
console.print(Panel(
user_prompt,
border_style="magenta",
padding=(1, 2),
))
console.print(Rule("[bold yellow]Follow-up Prompt Preview[/bold yellow]"))
followup = build_cross_module_followup_prompt(
previous_response="## Dependency Analysis: `extract_function_types`\n...",
followup_query="Which of these callers is most critical to the system?",
primary_context=sample_primary,
dependency_context=sample_dependency,
call_graph_data=sample_call_graph,
)
console.print(Panel(followup, border_style="yellow", padding=(1, 2))) |