mirror of
https://github.com/codeflash-ai/codeflash-internal.git
synced 2026-05-04 18:25:18 +00:00
react omni aiservice
This commit is contained in:
parent
eb5f4b460e
commit
81f8bd76c1
7 changed files with 204 additions and 5 deletions
|
|
@ -8,5 +8,6 @@ AZURE_API_BASE=
|
|||
# To run in local mode, set OPENAI_API_TYPE anything other than azure
|
||||
OPENAI_API_TYPE=
|
||||
OPENAI_API_KEY=
|
||||
AZURE_ANTHROPIC_API_KEY=
|
||||
AZURE_ANTHROPIC_ENDPOINT=https://codeflash-anthropic-resource.openai.azure.com/anthropic
|
||||
AWS_ACCESS_KEY_ID=
|
||||
AWS_SECRET_ACCESS_KEY=
|
||||
AWS_REGION=us-east-1
|
||||
|
|
|
|||
|
|
@ -103,6 +103,8 @@ async def optimize_javascript_code_single(
|
|||
is_async: bool = False,
|
||||
call_sequence: int | None = None,
|
||||
language: str = "javascript",
|
||||
is_react_component: bool = False,
|
||||
react_context: str | None = None,
|
||||
) -> tuple[OptimizeResponseItemSchema | None, float | None, str]:
|
||||
"""Optimize JavaScript/TypeScript code using LLMs.
|
||||
|
||||
|
|
@ -136,9 +138,13 @@ async def optimize_javascript_code_single(
|
|||
f"Multi-file context detected with {len(original_file_to_code)} files: {list(original_file_to_code.keys())}"
|
||||
)
|
||||
|
||||
# Get language-appropriate prompts (TypeScript uses same prompts as JavaScript)
|
||||
system_prompt = get_system_prompt(is_async)
|
||||
user_prompt = get_user_prompt(is_async)
|
||||
# Get language-appropriate prompts
|
||||
if is_react_component:
|
||||
system_prompt = _load_react_prompt("system_prompt")
|
||||
user_prompt = _load_react_prompt("user_prompt")
|
||||
else:
|
||||
system_prompt = get_system_prompt(is_async)
|
||||
user_prompt = get_user_prompt(is_async)
|
||||
|
||||
# Format prompts with proper language tag
|
||||
system_prompt = system_prompt.format(language_version=language_version)
|
||||
|
|
@ -179,6 +185,10 @@ You MUST output the target file. You may also output helper files if you optimiz
|
|||
if dependency_code:
|
||||
user_prompt = f"Dependencies (read-only):\n```{code_block_tag}\n{dependency_code}\n```\n\n{user_prompt}"
|
||||
|
||||
# Add React context if available
|
||||
if is_react_component and react_context:
|
||||
user_prompt = f"React Component Analysis:\n{react_context}\n\n{user_prompt}"
|
||||
|
||||
obs_context: dict[str, Any] | None = {"call_sequence": call_sequence} if call_sequence is not None else None
|
||||
|
||||
messages: list[ChatCompletionMessageParam] = [
|
||||
|
|
@ -302,6 +312,19 @@ You MUST output the target file. You may also output helper files if you optimiz
|
|||
return result, llm_cost, optimize_model.name
|
||||
|
||||
|
||||
def _load_react_prompt(prompt_name: str) -> str:
|
||||
"""Load a React-specific prompt template from the prompts directory."""
|
||||
from pathlib import Path # noqa: PLC0415
|
||||
|
||||
prompt_dir = Path(__file__).parent / "prompts" / "react_optimizer"
|
||||
prompt_file = prompt_dir / f"{prompt_name}.md"
|
||||
if prompt_file.exists():
|
||||
return prompt_file.read_text(encoding="utf-8")
|
||||
logging.warning("React prompt not found: %s", prompt_file)
|
||||
# Fall back to standard prompts
|
||||
return get_system_prompt(False) if "system" in prompt_name else get_user_prompt(False)
|
||||
|
||||
|
||||
def _normalize_code(code: str) -> str:
|
||||
"""Normalize code for comparison (remove comments and whitespace)."""
|
||||
# Remove single-line comments
|
||||
|
|
@ -322,6 +345,8 @@ async def optimize_javascript_code(
|
|||
is_async: bool = False,
|
||||
n_candidates: int = 0,
|
||||
language: str = "javascript",
|
||||
is_react_component: bool = False,
|
||||
react_context: str | None = None,
|
||||
) -> tuple[list[OptimizeResponseItemSchema], float, dict[str, str]]:
|
||||
"""Run parallel optimizations with multiple models.
|
||||
|
||||
|
|
@ -359,6 +384,8 @@ async def optimize_javascript_code(
|
|||
is_async=is_async,
|
||||
call_sequence=call_sequence,
|
||||
language=language,
|
||||
is_react_component=is_react_component,
|
||||
react_context=react_context,
|
||||
)
|
||||
)
|
||||
tasks.append(task)
|
||||
|
|
@ -470,6 +497,8 @@ async def optimize_javascript(
|
|||
is_async=data.is_async or False,
|
||||
n_candidates=data.n_candidates,
|
||||
language=language,
|
||||
is_react_component=getattr(data, "is_react_component", False),
|
||||
react_context=getattr(data, "react_context", None),
|
||||
)
|
||||
)
|
||||
user_task = None
|
||||
|
|
|
|||
|
|
@ -0,0 +1,50 @@
|
|||
You are a professional React performance engineer. Your goal is to optimize React components to reduce unnecessary re-renders and improve rendering performance while maintaining identical behavior.
|
||||
|
||||
**Behavioral Preservation (CRITICAL)**
|
||||
- Do NOT rename components or change their props interface.
|
||||
- The component MUST render the exact same output for the same props and state.
|
||||
- Do NOT change event handler behavior, side effects, or state management logic.
|
||||
- Preserve existing type annotations (for TypeScript) - all props types, return types, and variable annotations must be preserved exactly as written.
|
||||
- Preserve the export structure - exported components must remain exported.
|
||||
- Preserve ALL existing comments exactly as written, unless the corresponding code logic is changed.
|
||||
|
||||
**React.memo Usage Rules**
|
||||
- Wrap components in React.memo() when they receive props that are referentially stable (primitives, memoized objects/arrays).
|
||||
- Do NOT use React.memo() on components that always receive new object/array references as props unless those are also memoized.
|
||||
- When using React.memo(), provide a custom comparison function ONLY if the default shallow comparison is insufficient.
|
||||
- Do NOT wrap components that rely on context changes for re-rendering unless the context value is stable.
|
||||
|
||||
**useMemo/useCallback Guidelines**
|
||||
- Use useMemo() for expensive computations (array .filter/.sort/.map/.reduce, complex object transformations).
|
||||
- Use useCallback() for functions passed as props to child components, especially memoized children.
|
||||
- Always specify the complete dependency array - never omit dependencies to "prevent re-renders".
|
||||
- Do NOT use useMemo/useCallback for trivial operations where the memoization overhead exceeds the computation cost.
|
||||
|
||||
**Inline Object/Function Avoidance**
|
||||
- Extract inline object literals from JSX props to useMemo or module-level constants.
|
||||
- Extract inline function expressions from JSX props to useCallback.
|
||||
- Style objects that never change should be module-level constants, not useMemo.
|
||||
|
||||
**React 19+ Awareness**
|
||||
- If the code uses React 19 or later, be aware that the React Compiler may auto-memoize.
|
||||
- Still apply optimizations that help the compiler (avoid inline objects, use stable references).
|
||||
|
||||
**Must NOT**
|
||||
- Change the component's public API (props interface, exported name).
|
||||
- Add unnecessary dependencies to hook dependency arrays.
|
||||
- Break server-side rendering (SSR) compatibility.
|
||||
- Use React internals or undocumented APIs.
|
||||
- Wrap every single function in useCallback or every value in useMemo indiscriminately.
|
||||
|
||||
**Response Format (REQUIRED)**
|
||||
- ALWAYS start your response with a brief explanation (2-4 sentences) of what optimization you made and why it reduces re-renders or improves render performance.
|
||||
- Then provide the optimized code in a markdown code block.
|
||||
- Example format:
|
||||
```
|
||||
**Optimization Explanation:**
|
||||
[Your explanation here describing the memoization strategy and expected render reduction]
|
||||
|
||||
```typescript:filename.tsx
|
||||
[optimized code]
|
||||
```
|
||||
```
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
Optimize the following React component for rendering performance. Focus on reducing unnecessary re-renders while preserving identical behavior.
|
||||
|
||||
## Component Source Code
|
||||
```{{ language }}
|
||||
{{ source_code }}
|
||||
```
|
||||
|
||||
{% if dependency_code %}
|
||||
## Read-Only Context (Dependencies)
|
||||
```{{ language }}
|
||||
{{ dependency_code }}
|
||||
```
|
||||
{% endif %}
|
||||
|
||||
{% if react_context %}
|
||||
## React Component Analysis
|
||||
{{ react_context }}
|
||||
{% endif %}
|
||||
|
||||
{% if module_system %}
|
||||
## Module System
|
||||
This project uses {{ module_system }} modules.
|
||||
{% endif %}
|
||||
|
||||
## Requirements
|
||||
1. The optimized component MUST produce identical rendered output for all possible prop/state combinations.
|
||||
2. Focus on: React.memo wrapping, useMemo for expensive computations, useCallback for event handlers passed to children, extracting inline objects/arrays from JSX props.
|
||||
3. Do NOT change the component's props interface or exported name.
|
||||
4. Return the complete optimized component code.
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
You are a professional React test engineer. Your goal is to generate comprehensive tests for React components using @testing-library/react that verify both correctness and rendering efficiency.
|
||||
|
||||
**Test Categories to Generate**
|
||||
|
||||
1. **Render Correctness Tests**
|
||||
- Verify the component renders without errors.
|
||||
- Check that key UI elements are present in the rendered output.
|
||||
- Use `screen.getByRole`, `screen.getByText`, `screen.getByTestId` queries (prefer accessible queries).
|
||||
|
||||
2. **Interaction Tests**
|
||||
- Test user events (clicks, typing, form submissions) using `@testing-library/user-event`.
|
||||
- Verify state changes result in correct UI updates.
|
||||
- Always wrap state-changing operations in `act()` when needed.
|
||||
|
||||
3. **Re-render Counting Tests**
|
||||
- Create tests that verify the component doesn't re-render unnecessarily.
|
||||
- Use the render counting pattern: render with props, then rerender with same props.
|
||||
- For memoized components, verify that same props produce zero extra renders.
|
||||
|
||||
**Test Framework**
|
||||
- Use `@testing-library/react` for rendering and querying.
|
||||
- Use `@testing-library/user-event` for simulating user interactions.
|
||||
- Use Jest (`describe`, `it`, `expect`) for test structure.
|
||||
- Use `jest.fn()` for mocking callback props.
|
||||
|
||||
**Response Format (REQUIRED)**
|
||||
- Provide test code in a single markdown code block.
|
||||
- Tests must be self-contained and runnable with Jest + @testing-library/react.
|
||||
- Include all necessary imports at the top.
|
||||
- Use descriptive test names that explain what behavior is being verified.
|
||||
|
||||
Example format:
|
||||
```typescript:ComponentName.test.tsx
|
||||
import { render, screen, act } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { ComponentName } from './ComponentName';
|
||||
|
||||
describe('ComponentName', () => {
|
||||
it('should render correctly with default props', () => {
|
||||
// ...
|
||||
});
|
||||
|
||||
it('should handle user interaction', async () => {
|
||||
// ...
|
||||
});
|
||||
|
||||
it('should not re-render with same props', () => {
|
||||
// ...
|
||||
});
|
||||
});
|
||||
```
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
Generate comprehensive tests for the following React component. Include render correctness tests, interaction tests, and re-render efficiency tests.
|
||||
|
||||
## Component Source Code
|
||||
```{{ language }}
|
||||
{{ source_code }}
|
||||
```
|
||||
|
||||
{% if props_interface %}
|
||||
## Props Interface
|
||||
```typescript
|
||||
{{ props_interface }}
|
||||
```
|
||||
{% endif %}
|
||||
|
||||
{% if hooks_used %}
|
||||
## Hooks Used
|
||||
{{ hooks_used | join(', ') }}
|
||||
{% endif %}
|
||||
|
||||
{% if child_components %}
|
||||
## Child Components Rendered
|
||||
{{ child_components | join(', ') }}
|
||||
{% endif %}
|
||||
|
||||
{% if dependency_code %}
|
||||
## Dependencies (Read-Only Context)
|
||||
```{{ language }}
|
||||
{{ dependency_code }}
|
||||
```
|
||||
{% endif %}
|
||||
|
||||
## Requirements
|
||||
1. Generate tests using @testing-library/react and @testing-library/user-event.
|
||||
2. Include at least one render correctness test.
|
||||
3. Include re-render counting tests if the component could benefit from memoization.
|
||||
4. Use `jest.fn()` for callback props.
|
||||
5. Ensure tests are self-contained and will pass on the original component code.
|
||||
|
|
@ -33,6 +33,8 @@ class OptimizeSchema(Schema):
|
|||
call_sequence: int | None = None # Deprecated: call_sequence is now auto-assigned
|
||||
n_candidates: int = 5 # default value for backward compatibility
|
||||
is_numerical_code: bool | None = None
|
||||
is_react_component: bool = False # Whether target is a React component
|
||||
react_context: str | None = None # React-specific context (props, hooks, opportunities)
|
||||
|
||||
|
||||
class OptimizeSchemaLP(Schema):
|
||||
|
|
|
|||
Loading…
Reference in a new issue