Skip to content

Commit 3d1f9e7

Browse files
authored
Merge pull request #1 from codeoxygen/graph-dev
Graph dev
2 parents 384cda7 + 1ac90b8 commit 3d1f9e7

56 files changed

Lines changed: 10313 additions & 0 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

app/.DS_Store

8 KB
Binary file not shown.

app/configs.py

Lines changed: 302 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,302 @@
1+
import os
2+
from pathlib import Path
3+
from prompt_store import PromptStore
4+
from dotenv import load_dotenv
5+
6+
load_dotenv()
7+
8+
MONGO_URI = "mongodb+srv://lahiruprabhath099:qYVDTCA22Mds96KV@cluster1.diq5rte.mongodb.net/?retryWrites=true&w=majority&appName=Cluster1&tlsAllowInvalidCertificates=true"
9+
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")
10+
WORKSPACE_DIR = Path(os.path.join(os.getcwd(), "workspace"))
11+
TEMPLATE_DIR = os.path.join(os.getcwd(), "templates/workspace")
12+
PACKAGE_MANAGER = "npm"
13+
MIN_NODE = (18, 18, 0)
14+
15+
store = PromptStore(MONGO_URI, db_name="GameOnAI", collection_name="prompts")
16+
17+
prompt_template = store.get_prompt("project_planner_prompt")
18+
19+
INSTRUCTIONS= """
20+
**Game Logic & Features:**
21+
- AI opponents with multiple difficulty levels (Easy, Medium, Hard)
22+
- Single-player vs AI
23+
- 2 players multiplayer option
24+
- Single-Player vs AI feature should work without connecting to web Socket or not
25+
- page.tsx should inside the app folder.
26+
- Multiplayer game isn't not playing from the same device.
27+
- Win/lose/draw condition detection with pixel-perfect accuracy
28+
- Comprehensive error handling for all edge cases
29+
- Player statistics and scoring system
30+
- Eliminate lynting error and type defining errors
31+
32+
## UI/UX PRIORITY SPECIFICATIONS:
33+
34+
**Visual Design:**
35+
- Modern, sleek interface with smooth micro-animations
36+
- CRITICAL : Text colors, UI componenet allignments, spacing, utilizing the space as UX professionals.
37+
- the playing areas should designed perfectly as match per the requested game.
38+
- Space utilisation, deciding the size of each component, allignments, positioning should be world class
39+
- No instructions and No dcumentaions.
40+
- Eye catching Gradient backgrounds with dynamic color transitions
41+
- Eye-catching color palettes with strategic color mixing
42+
- Glassmorphism effects and card-based layouts
43+
- Subtle shadows, borders, and depth effects
44+
- Hover animations and interactive feedback
45+
- Loading spinners, success states, and error notifications
46+
- Minimal text, no guidelines or explanations
47+
- Player turn indicators must be clear and immediate
48+
49+
##CRITICAL for MULTIPLAYER IMPLEMENTATION:
50+
51+
- Multiplayer game feature is only allowed to play via web soket implementaion in multiple devices.
52+
- But must not create join room UI feature in multiplayer option. You can assume when game is opened it is created already.
53+
- Understand that multiplayer game option is not playing in the same device. It is playing from two devices
54+
- UI States are update through the websocket in two players screen accordingly.
55+
56+
CRITICAL : UI/UX components positioning , color mixing ,player turns return should be world class
57+
Use filled color game objects. Less Text , no guidelines or explanations in the UI
58+
"""
59+
60+
summarizer_prompt = """You are a game development requirements analyzer. Your task is to extract and summarize the core game concept and requirements from user queries, focusing only on gameplay mechanics, features, and user experience elements.
61+
62+
INSTRUCTIONS:
63+
1. Extract the main game concept and identify the specific game type
64+
2. Summarize ONLY the gameplay requirements, features, and mechanics
65+
3. Ignore all technical implementation details including:
66+
- Database implementations
67+
- WebSocket connections
68+
- API specifications
69+
- Server architecture
70+
- Programming languages
71+
- Framework choices
72+
- Deployment details
73+
- Technical stack mentions
74+
75+
4. Focus on:
76+
- Game mechanics and rules
77+
- Player interactions
78+
- Game objectives and win conditions
79+
- UI/UX requirements
80+
- Visual elements and themes
81+
- Game modes or difficulty levels
82+
- Player progression systems
83+
- Core features and functionality
84+
85+
5. Return your response in this exact JSON format:
86+
{{
87+
"summarized_text": "Clear, concise summary of the game requirements focusing on gameplay mechanics, features, and user experience",
88+
"game_name": "Identified game type or name (e.g., 'tic_tac_toe', 'snake_game', 'puzzle_game', 'platformer', etc.)"
89+
}}
90+
91+
EXAMPLES:
92+
93+
Input: "I want to build a tic-tac-toe game with React and Node.js backend, using WebSocket for real-time multiplayer and MongoDB for storing game states"
94+
Output: {{
95+
"summarized_text": "A classic tic-tac-toe game where two players take turns placing X's and O's on a 3x3 grid, with the goal of getting three marks in a row (horizontally, vertically, or diagonally). Features real-time multiplayer gameplay.",
96+
"game_name": "tic_tac_toe"
97+
}}
98+
99+
Input: "Create a snake game using Python with pygame, store high scores in SQLite database and implement collision detection algorithms"
100+
Output: {{
101+
"summarized_text": "A snake game where the player controls a growing snake to eat food while avoiding collisions with walls and the snake's own body. Features score tracking and high score system.",
102+
"game_name": "snake_game"
103+
}}
104+
105+
Now analyze the following user query and return the JSON response:
106+
107+
{user_query}"""
108+
109+
110+
sample_prompt = """You are an expert Next.js developer. continue a incomplete game development project following the guidelines.
111+
112+
**user_query:** {requirements}
113+
114+
Return a JSON object with this exact structure. No string literal output. The files field should be a list not a string literal. Also the object inside the file list should not be string json text. It should be a JSON type object:
115+
116+
```json
117+
{{
118+
"description": "Brief project description",
119+
"development_plan": "Development plan overview",
120+
"directories": ["app/components", "app/hooks", "app/types"],
121+
"files": [
122+
{{
123+
"path": "app/file1.tsx",
124+
"description": "File description",
125+
"content": "complete functional code"
126+
}}
127+
],
128+
"packages": [
129+
{{
130+
"name": "package-name",
131+
"dev": false
132+
}}
133+
]
134+
}}
135+
```
136+
137+
***Guidelines***
138+
***CRITICAL***
139+
Your goal is to continue from the avialble web socket connection.
140+
141+
142+
**Game Logic & Features:**
143+
- continue game implementaion. creat components like, types and page.tsx,
144+
- db connection already implemented.
145+
- AI opponents with multiple difficulty levels (Easy, Medium, Hard)
146+
- Single-Player vs AI and - Multi player options
147+
- multiplayer option feature should work without connecting to web Socket
148+
- Create seperate componenets, type defenitions
149+
- componenets folder, types folder, hooks folder, page.tsx must be inside the app folder.
150+
- Multiplayer game isn't not playing from the same device. It is playing from two devices
151+
- Win/lose/draw condition detection with pixel-perfect accuracy
152+
- Comprehensive error handling for all edge cases
153+
- Player statistics and scoring system
154+
- Eliminate lynting error and type defining errors
155+
156+
## UI/UX PRIORITY SPECIFICATIONS:
157+
158+
**Visual Design:**
159+
- Modern, sleek interface with smooth micro-animations
160+
- CRITICAL : Text colors, UI componenet allignments, spacing, utilizing the space as UX professionals.
161+
- the playing areas should designed perfectly as match per the requested game.
162+
- Space utilisation, deciding the size of each component, allignments, positioning should be world class
163+
- No instructions and No dcumentaions.
164+
- Eye catching Gradient backgrounds with dynamic color transitions
165+
- Eye-catching color palettes with strategic color mixing
166+
- Glassmorphism effects and card-based layouts
167+
- Subtle shadows, borders, and depth effects
168+
- Hover animations and interactive feedback
169+
- Loading spinners, success states, and error notifications
170+
- Minimal text, no guidelines or explanations
171+
- Player turn indicators must be clear and immediate
172+
173+
174+
##Important for MULTIPLAYER IMPLEMENTATION:
175+
I'll provide an example codes how the multiplayer game is implemented. you want to use exact websocket and api related concept variables names as exactly as same.
176+
see the example code below to handle states in each player device with multiplayer support. The example is to guioide to the multiplayer connection setup. the game play and componenet should design according the required game
177+
178+
{main_page}
179+
180+
181+
182+
## **CRITICAL FOR MULTIPLAYER OPTION - **
183+
- Multiplayer games ONLY via WebSocket on multiple devices (not same device)
184+
- NO join room UI - assume game room already created when opened
185+
- Use EXACTLY the same payload variables, state variables, API names, event names as reference example
186+
- Handle all socket events in page.tsx according to requested game
187+
- gameSessionUUID value must be parsed from params in page.tsx
188+
- Define all type definitions in page.tsx
189+
- Do NOT create additional APIs
190+
- Player names should display by actual name and profile accordingly
191+
192+
## PLAYER TURN DISPLAY
193+
- When player turns change, display logically updates on each user's screen
194+
- UI states update through WebSocket across both players' screens simultaneously
195+
196+
197+
## IMPLEMENTATION
198+
- Extract gameSessionUUID by parsing URL parameters in page.tsx
199+
- Create game components in component folder
200+
- Game logic and UI adapt to requested game while maintaining WebSocket structure
201+
- Real-time state synchronization between separate devices
202+
"""
203+
204+
205+
206+
fixer_prompt = """You are a Next.js/TypeScript code fixer. You MUST generate fix actions.
207+
208+
BUILD ERROR: {error}
209+
ROOT CAUSE: {root_cause}
210+
CURRENT CODE: {current_code}
211+
212+
CRITICAL RULE: Since an error exists, you MUST provide at least one action. Empty actions = system failure.
213+
214+
MANDATORY OUTPUT STRUCTURE:
215+
{{
216+
"summary": "Error type and fix method",
217+
"actions": [REQUIRED - CANNOT BE EMPTY]
218+
}}
219+
220+
FORCE ACTION GENERATION:
221+
If you identify the fix but hesitate to provide actions, you MUST still provide them.
222+
If you're unsure of exact content, provide your best attempt rather than empty actions.
223+
If you can't determine the exact file, use the most likely file path from the error.
224+
225+
COMMON ERROR → ACTION MAPPING:
226+
- Type error → write_file with type fix
227+
- Import error → write_file with correct imports
228+
- Missing package → install_package
229+
- Syntax error → write_file with syntax fix
230+
- Any other error → write_file with attempted fix-
231+
- Hardly skip warnings. No need to fix
232+
- You have two task mainly
233+
1 - fix the error.
234+
2 - Must provide the rewrite content with fix in actions key
235+
236+
EMERGENCY FALLBACK (if no specific fix identified):
237+
Always include at least this action:
238+
{{"tool": "write_file", "args": {{"path": "[most_likely_file_from_error]", "content": "[current_code_with_obvious_fix_attempt]"}}
239+
240+
VALIDATION CHECK:
241+
- Before responding, verify actions array is NOT empty
242+
- If actions is empty, add a fallback write_file action
243+
- Never explain why you can't fix - just provide your best fix attempt
244+
245+
RESPONSE (JSON only):
246+
{{
247+
"summary": "Brief fix description",
248+
"actions": [{{"tool": "write_file", "args": {{"path": "file.ts", "content": "complete fixed file content"}}]
249+
}}"""
250+
251+
252+
improver_prompt = """
253+
You are an expert Next.js developer with 10+ years of experience building production-grade applications. You specialize in game development and have a track record of maintaining high-quality, stable codebases.
254+
255+
## CONTEXT
256+
- Initial Project: {instructions}
257+
- Change Request: {requirement}
258+
- Target Code: {codes}
259+
260+
## YOUR MISSION
261+
Analyze the provided code and implement the requested changes with surgical precision. This is a WORKING system that requires minimal, targeted modifications.
262+
263+
## CRITICAL CONSTRAINTS
264+
1. **Preserve Functionality**: The current code is stable and functional - make only necessary changes
265+
2. **Minimal Impact**: Avoid refactoring or "improvements" beyond the specific requirement
266+
3. **Precision Over Perfection**: Focus on the exact change requested, not code optimization
267+
4. **Risk Assessment**: If the change could break existing functionality, explain the risks
268+
269+
## ANALYSIS PROCESS
270+
1. **Understand**: What specific functionality needs to change?
271+
2. **Locate**: Which exact files/sections require modification?
272+
3. **Isolate**: What's the minimal change that satisfies the requirement?
273+
4. **Implement**: Apply changes while preserving existing code patterns
274+
5. **Do not** change any route.ts file if provided in any case. They are provided to as helpers to change other required files
275+
276+
## RESPONSE FORMAT
277+
The √ name should return as it is provided in the Target code section.
278+
You MUST respond with a valid JSON object in this exact format:
279+
280+
{{
281+
"changes": [
282+
{{
283+
"file_path": "file_path_1",
284+
"content": "complete_rewritten_file_content_with_changes_applied"
285+
}},
286+
{{
287+
"file_path": "file_path",
288+
"content": "complete_rewritten_file_content_with_changes_applied"
289+
}}
290+
],
291+
"description": "Brief explanation of changes made or additional information needed"
292+
}}
293+
294+
## SPECIAL CASES
295+
If the change requested cannot be achieved by modifying the target code (it might require additional files, dependencies, or information not provided), respond with an empty changes list and use the description field to request the additional information needed to complete the task.
296+
297+
Example for cases requiring additional information:
298+
{{
299+
"changes": [],
300+
"description": "Cannot complete the requested change. Additional information needed: [specify what's missing - e.g., missing component files, required dependencies, configuration files, etc.]"
301+
}}
302+
"""

app/main.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
from typing import Dict, Any
2+
from flask import Flask, request, jsonify
3+
4+
from langgraph.checkpoint.memory import MemorySaver
5+
from src.agents.game_dev_agent.graph_builder import GraphBuilder
6+
from langchain_core.messages import HumanMessage
7+
from src.utils.deploy import push_workspace_to_github
8+
9+
app = Flask(__name__)
10+
11+
checkpointer = MemorySaver()
12+
graph_builder = GraphBuilder()
13+
app_graph = graph_builder.build_app(checkpointer=checkpointer)
14+
15+
16+
@app.route("/build", methods=["POST"])
17+
def build_game():
18+
try:
19+
payload: Dict[str, Any] = request.get_json(force=True)
20+
except Exception:
21+
return jsonify({"ok": False, "error": "Invalid JSON body"}), 400
22+
23+
thread_id = payload.get("thread_id")
24+
requirements = payload.get("requirements")
25+
26+
if not isinstance(thread_id, str) or not thread_id:
27+
return jsonify({"ok": False, "error": "`thread_id` (string) is required"}), 400
28+
if requirements is not None and not isinstance(requirements, str):
29+
return jsonify({"ok": False, "error": "`requirements` must be a string"}), 400
30+
31+
config = {"configurable": {"thread_id": thread_id}}
32+
33+
try:
34+
snapshot = app_graph.get_state(config)
35+
has_state = bool(getattr(snapshot, "values", None))
36+
except Exception:
37+
has_state = False
38+
snapshot = None
39+
40+
41+
if not has_state:
42+
43+
input_state = graph_builder.init_state(requirements=requirements)
44+
else:
45+
46+
input_state = {
47+
"messages": HumanMessage(content=requirements),
48+
}
49+
50+
51+
for chunk in app_graph.stream(input=input_state, config=config):
52+
print("---- CHUNK ----")
53+
print("---------------")
54+
55+
return jsonify({"Success": True, "message": "Build completed successfully"}), 200
56+
57+
58+
@app.route("/deploy" , methods = ["POST"])
59+
def deploy_to_github():
60+
try:
61+
payload: Dict[str, Any] = request.get_json(force=True)
62+
except Exception:
63+
return jsonify({"ok": False, "error": "Invalid JSON body"}), 400
64+
65+
github_repo = payload.get("thread_id")
66+
branch = payload.get("requirements")
67+
commit_message = payload.get("commit_message")
68+
69+
push_workspace_to_github(branch_name=branch , repo_url=github_repo, commit_message=commit_message)
70+
71+
if __name__ == "__main__":
72+
app.run(host="0.0.0.0", port=8000, debug=False)

0 commit comments

Comments
 (0)