PromptBase
PromptBase SelectGet Select
Close icon
General
Home
Marketplace
Create
Hire
Login
Chat
Sell
Explore

Prompt Details

Model
(claude-5-5-sonnet)
Token size
4,090
Example input
[REPOSITORY_FILES_AND_ARCHITECTURE]: Python repository: - app.py: initializes the AI agent - agent.py: handles agent execution - tools.py: defines calculator and web-search tools - memory.py: stores conversation history - tests/test_agent.py: basic agent tests - requirements.txt: dependency declarations Source files are partially available. No lockfile supplied. [AGENT_FRAMEWORKS_RUNTIME_AND_DEPENDENCIES]: Python 3.11, LangChain-based agent, OpenAI model integration, pytest. Exact installed dependency versions are not verified. [TARGET_VERSIONS_AND_MIGRATION_GOALS]: Target Python 3.12. Modernize deprecated framework usage, improve modularity, and preserve agent inputs, outputs, tool behavior, and conversation memory. [KNOWN_PROBLEMS_AND_TEST_COVERAGE]: Agent initialization has inconsistent error handling. Some tools lack tests. Dependency compatibility is unknown. Existing tests cover basic execution only. [CONSTRAINTS_AND_ACCEPTANCE_CRITERIA]: No full rewrite. Preserve public interfaces and prompts. No destructive changes. Use small patches, add regression tests, verify dependency compatibility, and provide rollback instructions.
Example output
### Phase 1 β€” πŸ” Repository Discovery & Baseline Objective: Reconstruct the known repository structure and establish what must be verified. | Component | Available evidence | Status | | ------------------- | ------------------------- | --------- | | app.py | Agent initialization | Described | | agent.py | Agent execution | Described | | tools.py | Calculator and web search | Described | | memory.py | Conversation history | Described | | tests/test_agent.py | Basic tests | Described | | requirements.txt | Dependencies | Described | | Lockfile | Not supplied | Missing | Architecture map `app.py` β€” Entry point `agent.py` β€” Agent orchestration `tools.py` `memory.py` Conceptual structure based on the supplied description; actual import relationships are unverified. * Confirmed from the scenario: Five named source/test files and one dependency manifest are described. * Potential risk: Agent initialization may be difficult to diagnose when errors are handled inconsistently. * Missing evidence: Actual imports, function signatures, model configuration, dependency versions, and baseline test output. Baseline acceptance criteria: * Existing tests can be executed and their results recorded. * Current agent input/output contracts are documented. * Tool and memory behavior are characterized before changes. Status: PARTIAL β€” repository description only. ### Phase 2 β€” πŸ“¦ Dependency Inventory & Compatibility Objective: Identify dependency risks without guessing package versions. | Dependency | Known information | Required action | | ------------------- | ------------------------- | -------------------------------------------- | | Python | 3.11 current; 3.12 target | Test runtime compatibility | | LangChain | Framework used | Identify exact package and version | | OpenAI integration | Provider integration used | Identify SDK and integration versions | | pytest | Testing framework | Verify test environment | | Transitive packages | Unknown | Resolve from a lockfile or clean environment | Findings * No dependency can be confirmed as deprecated or vulnerable from the supplied evidence. * The absence of a supplied lockfile limits reproducibility analysis; it does not prove the project has no lockfile. * LangChain-related packages may have different compatibility constraints depending on their exact versions. Recommended actions: * Inspect `requirements.txt` and the repository's actual package manager configuration. * Capture installed versions and dependency constraints. * Resolve dependencies in a separate test environment. * Check Python 3.12 support before upgrading the runtime. * Pin or lock dependencies according to the existing project conventions. Status: NOT VERIFIED β€” versions and resolution results are unavailable. ### Phase 3 β€” ⚠️ Deprecated API & Framework Detection No actual source code or deprecation warnings have been supplied. Therefore, no deprecated API can be confirmed. | Location | Existing API | Replacement | Status | | --------- | ------------ | -------------------------------------------------------- | ------------ | | agent.py | Unknown | Determine from source and version-specific documentation | NOT VERIFIED | | app.py | Unknown | Inspect initialization patterns | NOT VERIFIED | | tools.py | Unknown | Inspect tool registration and invocation | NOT VERIFIED | | memory.py | Unknown | Inspect memory and persistence APIs | NOT VERIFIED | Validation procedure: * Search source files for imports, classes, methods, and configuration patterns used by the current framework. * Compare each identified API against documentation for the installed and target versions. * Confirm whether an API is deprecated, removed, or still supported. * Add a targeted test for every replacement. Pass condition: Every reported deprecation has supporting evidence and a verified migration path. Status: NOT RUN. ### Phase 4 β€” πŸ—οΈ Architecture & Technical Debt Audit | Potential finding | Impact | Proposed action | Priority | | ------------------------------------------ | ------------------------------------------- | ------------------------------------------------------- | -------- | | Inconsistent initialization error handling | Harder diagnosis and recovery | Standardize errors while preserving exception semantics | High | | Limited tool tests | Tool regressions may go unnoticed | Add unit and contract tests | High | | Unknown module coupling | Refactoring could affect unrelated behavior | Map imports and dependencies | Medium | | Missing reproducible dependency baseline | Difficult to compare environments | Establish a repeatable environment | High | These are risk assessments based on the sample scenario, not confirmed code-level findings. Example investigation: If `agent.py` initializes the model, registers tools, and manages memory in one large function, the engineer should first establish the actual responsibilities and callers. Extracting a component is justified only if the resulting boundary improves testing or maintainability without changing observable behavior. Status: Preliminary prioritization. ### Phase 5 β€” πŸ€– AI Agent-Specific Compatibility Audit The most important requirement is preserving agent semantics, not merely making imports succeed. | Contract | Baseline to capture | Regression test | | -------------- | ---------------------------------------------- | -------------------------------------- | | Input | Accepted arguments and validation | Valid and invalid input tests | | Execution | Agent invocation and model configuration | Controlled execution test | | Tools | Names, schemas, permissions, and results | Tool contract tests | | Memory | Save, retrieve, and session isolation behavior | Persistence tests | | Output | Response structure and error behavior | Schema and exception tests | | Async behavior | Awaiting, cancellation, and concurrency | Async integration tests, if applicable | Example behavior-preservation scenario: Given a user request requiring the calculator tool, the agent should still invoke the appropriate tool, process its result, and return the expected output format after refactoring. The test should compare tool invocation arguments and output contracts rather than demanding identical natural-language wording from a model. Status: Test design proposed; actual behavior not observed. ### Phase 6 β€” πŸ› οΈ Refactoring Strategy & Change Boundaries Recommended order: * Establish a baseline and capture current public interfaces. * Add tests for initialization failures and tool contracts. * Fix verified error-handling defects. * Refactor only components with demonstrated maintainability problems. * Introduce dependency upgrades as isolated changes. * Run regression tests after each patch. | Change | Classification | Risk | Approval requirement | | -------------------------- | --------------------------- | ------------------------------------ | ---------------------------- | | Add missing tests | Structural/test improvement | Low to medium | Normal review | | Standardize error handling | Compatibility or bug fix | Medium | Verify exception contracts | | Extract duplicated logic | Structural refactor | Medium | Confirm callers and behavior | | Upgrade framework | Dependency migration | High until compatibility is verified | Version and test evidence | Status: Proposed plan. ### Phase 7 β€” πŸš€ Framework & Runtime Migration Target: Python 3.12. The precise migration path depends on the installed LangChain packages, OpenAI SDK, and other dependency constraints. | Component | Current state | Target state | Required validation | | --------------- | ---------------------- | ------------------------------ | ----------------------------------- | | Python runtime | 3.11 stated | 3.12 | Clean installation and test suite | | Agent framework | Exact version unknown | Compatible supported version | API and execution tests | | Model SDK | Exact version unknown | Compatible supported version | Request/response tests | | Tool adapters | Source unavailable | Preserve tool contracts | Tool integration tests | | Memory layer | Implementation unknown | Preserve persistence semantics | Save/retrieve and restoration tests | Migration gates: * Gate A: Baseline tests and current versions recorded. * Gate B: Python 3.12 environment resolves successfully. * Gate C: Framework APIs and integration compatibility verified. * Gate D: Agent and tool contracts pass regression tests. * Gate E: Rollback procedure is tested. Do not upgrade the Python runtime and multiple major framework dependencies simultaneously unless compatibility evidence and test isolation justify it. Status: Migration planning only. ### Phase 8 β€” πŸ”— API & Interface Preservation Create a contract inventory before changing implementation details. | Interface | Compatibility requirement | Evidence needed | | ----------------- | --------------------------------- | --------------------------------------- | | Agent entry point | Preserve accepted inputs | Public function signatures | | Tool interfaces | Preserve names and schemas | Tool definitions and consumers | | Memory methods | Preserve save/retrieve behavior | Implementation and existing data format | | Output format | Preserve required response fields | Output models and consumers | | Configuration | Avoid silently changing defaults | Environment variables and config files | Compatibility classifications: * Backward compatible: Existing callers continue to work. * Conditionally compatible: Requires a documented adapter or configuration change. * Breaking: Existing consumers must change. * Unknown: Insufficient evidence. Acceptance criterion: No public contract changes without explicit justification, tests, and migration guidance. ### Phase 9 β€” πŸ’» Controlled Code Refactoring Because actual source files are unavailable, the following is a proposed implementation pattern, not a patch against the user's repository. Illustrative example of centralized initialization error handling: ```python import logging logger = logging.getLogger(__name__) def initialize_agent(factory): """Initialize an agent and preserve the original exception.""" try: return factory() except Exception: logger.exception("Agent initialization failed") raise ``` Why this example may help: * Records diagnostic information. * Preserves the original exception and traceback. * Avoids silently returning an invalid agent instance. Important limitations: * This pattern should only be used if it matches the repository's actual error-handling requirements. * It must not log secrets or sensitive configuration. * It does not prove the original initialization problem has been fixed. * If the application already handles exceptions at a higher layer, adding another handler may be unnecessary. Required tests: ```python import pytest def test_initialize_agent_returns_instance(): expected = object() assert initialize_agent(lambda: expected) is expected def test_initialize_agent_reraises_original_error(): error = RuntimeError("initialization failed") def factory(): raise error with pytest.raises(RuntimeError) as exc_info: initialize_agent(factory) assert exc_info.value is error ``` These are illustrative tests for the example helper, not tests of the actual repository. They have not been executed. Status: Example code generated; repository patch not applied. ### Phase 10 β€” πŸ”’ Dependency & Lockfile Control Proposed procedure: * Preserve the existing manifest and any available lockfile. * Record the original dependency versions. * Create an isolated migration branch. * Resolve dependencies against Python 3.12. * Review changes to direct and transitive dependencies. * Run installation, import, unit, and integration checks. * Record the final dependency resolution. * Retain the previous working dependency set for rollback. Pass criteria: * Clean environment installation succeeds. * Dependency constraints resolve without unexplained conflicts. * No unsupported version combinations remain. * Regression tests pass. Status: NOT RUN β€” package manager and exact versions are unknown. ### Phase 11 β€” πŸ§ͺ Regression Test Reconstruction | Requirement | Test scenario | Expected result | | -------------------- | ------------------------------ | -------------------------------- | | Initialization | Valid configuration | Agent initializes | | Error handling | Invalid configuration | Predictable, diagnosable failure | | Calculator tool | Valid arguments | Correct tool result | | Web-search tool | Mocked provider response | Expected adapter behavior | | Memory | Save and retrieve conversation | Expected state is preserved | | Public interface | Existing invocation pattern | No unintended breaking changes | | Dependency migration | Clean Python 3.12 install | Installation succeeds | Use deterministic mocks for external model and search APIs where appropriate. Keep a smaller set of integration tests to validate real provider interactions in a controlled environment. Status: Test plan prepared; execution not performed. ### Phase 12 β€” πŸ”¬ Migration Testing & Semantic Validation | Test | Preconditions | Expected result | Actual evidence | Status | | ------------------------- | --------------------------------------- | ----------------------------------------------- | --------------- | ------- | | Import and initialization | Target dependencies installed | Components import and initialize | None | NOT RUN | | Tool invocation | Controlled tool fixture | Correct arguments and result handling | None | NOT RUN | | Structured output | Defined schema and fixtures | Valid outputs accepted; invalid outputs handled | None | NOT RUN | | Memory persistence | Configured test storage | Expected state survives required lifecycle | None | NOT RUN | | Exception propagation | Controlled failing dependency | Intended exception contract preserved | None | NOT RUN | | Async behavior | Async functionality confirmed in source | Correct awaiting and cancellation behavior | None | NOT RUN | | Python 3.12 compatibility | Clean target environment | Installation and relevant tests pass | None | NOT RUN | Important: Passing unit tests alone does not prove equivalent agent behavior. Validate tool selection, state changes, output contracts, and error handling separately. ### Phase 13 β€” πŸ›‘οΈ Security, Reliability & Performance | Area | Risk to investigate | Control | | ---------------- | --------------------------------------------------- | ---------------------------------------- | | Secrets | Credentials exposed through logs | Redact sensitive values | | Tool permissions | Tools gain unintended access | Preserve least privilege | | Prompt injection | Untrusted tool output influences privileged actions | Maintain trust boundaries | | Retries | Repeated model/tool failures create loops | Bound retries and use timeouts | | Memory | Cross-session data leakage | Test session isolation and authorization | | Performance | Refactor increases latency or model calls | Benchmark identical workloads | These are review targets, not confirmed vulnerabilities. Performance acceptance: Compare baseline and target using the same representative tasks, concurrency, model configuration, and measurement conditions. Report measured results only. Status: Review requirements identified; security scans and benchmarks not run. ### Phase 14 β€” πŸ“š Developer Documentation The modernization should update documentation only after actual changes are implemented. Required documentation: * Runtime and dependency installation instructions. * Environment-variable and secret configuration. * Development and test commands. * Supported Python and framework versions. * Breaking changes and migration steps. * Tool and memory behavior contracts. * Rollback instructions. * Known limitations and unresolved compatibility concerns. Acceptance criterion: Every documented command and version is consistent with the actual repository and verified environment. Status: Documentation changes proposed, not applied. ### Phase 15 β€” πŸ”„ Change Sequencing, Rollback & Release Readiness Stage 1: Baseline Capture versions, interfaces, existing tests, and current behavior. Required first Stage 2: Characterization tests Test initialization, tools, memory, and output contracts. Stage 3: Small refactors Apply individually reviewable, behavior-preserving changes. Stage 4: Runtime and dependencies Migrate in an isolated branch with reproducible dependency resolution. Stage 5: Regression and release Verify all acceptance criteria, review risks, and document recovery steps. Rollback triggers: * Existing public interfaces unexpectedly break. * Agent tools behave differently without approval. * Memory becomes unreadable or state is corrupted. * Critical regression tests fail. * Target dependencies cannot be resolved reliably. Rollback procedure: * Stop the rollout. * Restore the previous application revision. * Restore the previous dependency manifest and lockfile. * Restore compatible configuration or data formats if changed. * Rerun baseline tests. * Document the failure before attempting another migration. Release decision: NO-GO for production migration until compatibility evidence and required regression tests are available. ### Phase 16 β€” πŸ“‹ Final Codebase Modernization Package ### 1\. Executive Summary The sample repository has a clear high-level structure, but insufficient evidence exists to confirm framework deprecations, dependency conflicts, or actual code defects. The safest strategy is to establish a baseline, strengthen tests, make small changes, and migrate to Python 3.12 only after verifying package compatibility. ### 2\. Repository Architecture Map Known modules: `app.py`, `agent.py`, `tools.py`, `memory.py`, and `tests/test_agent.py`. Actual imports, module ownership, and dependency direction remain unverified. ### 3\. Dependency & Compatibility Report Python 3.11 is the stated current runtime, and Python 3.12 is the target. Exact LangChain and OpenAI package versions are unknown. No dependency upgrade should be approved until version constraints and runtime compatibility have been checked. ### 4\. Deprecated API Register No confirmed deprecated APIs. Source inspection and version-specific documentation are required before recording any replacement. ### 5\. Technical Debt Prioritization * High: Establish reproducible dependency and test baselines. * High: Expand tests for tools and initialization errors. * Medium: Inspect module coupling and duplicated logic. * Medium: Investigate framework API modernization opportunities. ### 6\. AI Agent Behavior Preservation Plan Preserve agent inputs, tool names and schemas, model configuration, prompts, memory semantics, exception contracts, and output structure unless an explicitly approved migration requires a change. ### 7\. Framework Migration Roadmap Baseline β†’ dependency compatibility verification β†’ characterization tests β†’ isolated runtime migration β†’ framework changes β†’ semantic regression testing β†’ release review. ### 8\. Refactoring Plan Prioritize test coverage and verified error-handling defects. Defer speculative cleanup and any framework changes lacking evidence. ### 9\. Updated Code & Patch Set One illustrative initialization helper and two illustrative tests were generated above. They have not been applied to repository files. ### 10\. Dependency & Lockfile Changes No version changes proposed because the installed package versions and package manager are unknown. ### 11\. Regression & Migration Test Plan Cover initialization, tool execution, memory persistence, output contracts, exceptions, dependency resolution, and applicable asynchronous workflows. ### 12\. Security & Reliability Review Verify secret redaction, tool permissions, session isolation, bounded retries, and failure recovery. No security scan has been executed. ### 13\. Developer Documentation Updates Update installation, migration, testing, configuration, and rollback instructions after implementation and verification. ### 14\. Implementation Task Graph ```mermaid flowchart TD A["Capture baseline"] --> B["Characterization tests"] B --> C["Low-risk refactoring"] C --> D["Resolve dependency compatibility"] D --> E["Python and framework migration"] E --> F["Regression and security tests"] F --> G["Documentation and release review"] F -->|Failure| H["Rollback and investigate"] ``` ### 15\. Rollback & Release Decision Current decision: NO-GO for production migration. Reason: The actual source, dependency versions, and executed test results are unavailable. This is an evidence limitation, not a claim that the repository is defective. ### 16\. Final Modernization Blueprint 1 Repository baseline Described 2 Dependency analysis Pending 3 API compatibility Pending 4 Refactoring Pending 5 Framework migration Pending 6 Code validation Pending 7 Regression testing Pending 8 Documentation Pending 9 Release decision Pending Highest-priority findings * Obtain the actual repository and dependency versions. * Establish baseline tests. * Verify runtime and framework compatibility. * Preserve agent and tool contracts. Proposed code changes * Add characterization and regression tests. * Standardize error handling only where the existing implementation warrants it. * Refactor verified coupling or duplication in small patches. Migration blockers * Missing source files. * Unknown dependency versions and constraints. * No baseline test output. Tests executed and evidence * Actual repository tests: NOT RUN. * Example helper tests: NOT RUN. * Dependency compatibility checks: NOT RUN. * Security scans and benchmarks: NOT RUN. Tests still required \- Unit, integration, tool-contract, memory, runtime-compatibility, and regression tests. Unresolved decisions * Exact LangChain and OpenAI package versions. * Whether any APIs are actually deprecated. * Whether direct or staged framework migration is supported. Definition of done * The target environment installs reproducibly. * All required tests pass with recorded evidence. * Public contracts and agent behavior remain compatible. * Approved patches are reviewed and rollback is documented. * No unresolved critical migration risks remain. ### βœ… Sample Test Result ### AACRU-ST-001 Summary Test design completeness Covered Evidence-based reporting Applied Actual code validation Not performed Production readiness Not approved Final verdict: The sample demonstrates a complete 16-phase modernization workflow while distinguishing supplied facts, potential risks, proposed changes, and unexecuted tests.
Claude

Agent Codebase Refactoring Upgrade

Add to Cart
Instant accessInstant access
Usage rightsCommercial use
Money-back guaranteeMoney‑back
By purchasing this prompt, you agree to our terms of service
CLAUDE-5-5-SONNET
Tested icon
Guide icon
4 examples icon
Free credits icon
The AI Agent Codebase Refactoring & Upgrade Engineer helps experienced developers identify technical debt, analyze dependencies, detect deprecated APIs, and migrate AI agent applications toward more maintainable and compatible architectures. Repository Analysis Dependency Compatibility Deprecated API Detection Framework Migration Planning AI Agent Compatibili Designed to modernize existing projects without unnecessary rewrites, unsupported assumptions, or unverified claims of successful testing.
...more
Added 4 days ago
Report
Browse Marketplace