Skip to content

Commit cf99a56

Browse files
authored
Merge pull request #5 from yug49/test
Gurukul updated, as well as some minor changes in the UI.
2 parents 3e7c3af + ca8ab62 commit cf99a56

12 files changed

Lines changed: 3647 additions & 450 deletions

File tree

frontend/GURUKUL_IMPLEMENTATION.md

Lines changed: 254 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,254 @@
1+
# Gurukul Functionality Implementation
2+
3+
## Overview
4+
This implementation adds comprehensive Gurukul (training academy) functionality to the Rann Web3 game, integrating with the NEAR AI personality updater agent to analyze psychological responses and update NFT character traits based on moral choices.
5+
6+
## Files Created/Modified
7+
8+
### 1. New API Route: `/api/gurukul-analysis/route.ts`
9+
- **Purpose**: Handles psychological analysis of user responses using NEAR AI
10+
- **Features**:
11+
- Integration with NEAR AI personality updater agent
12+
- Fallback to local intelligent analysis if NEAR AI is unavailable
13+
- Comprehensive psychological profiling based on moral choices
14+
- Trait calculation with realistic constraints (25-75 range)
15+
- Detailed reasoning for trait changes
16+
17+
### 2. Modified: `/app/gurukul/page.tsx`
18+
- **Purpose**: Updated the frontend to use the new API endpoint
19+
- **Changes**:
20+
- Replaced direct NEAR AI calls with API route calls
21+
- Improved error handling and fallback mechanisms
22+
- Enhanced user experience with better status messages
23+
- Maintained all existing functionality while adding new features
24+
25+
## Architecture
26+
27+
### NEAR AI Integration
28+
```typescript
29+
// Auth flow using NEAR wallet
30+
const auth = await nearWalletService.login();
31+
const authForApi = {
32+
signature: auth.signature,
33+
accountId: auth.accountId,
34+
publicKey: auth.publicKey,
35+
message: auth.message,
36+
nonce: auth.nonce.toString('base64'),
37+
recipient: auth.recipient,
38+
callbackUrl: auth.callbackUrl
39+
};
40+
```
41+
42+
### API Request Structure
43+
```typescript
44+
interface GurukulAnalysisRequest {
45+
auth: NearAuthData;
46+
tokenId: number;
47+
currentTraits: YodhaTraits;
48+
answers: QuestionAnswer[];
49+
}
50+
```
51+
52+
### Response Structure
53+
```typescript
54+
interface GurukulAnalysisResponse {
55+
success: boolean;
56+
tokenId: number;
57+
analysis: string;
58+
currentTraits: YodhaTraits;
59+
newTraits: YodhaTraits;
60+
traitChanges: TraitChanges;
61+
reasoning?: TraitReasoning;
62+
source: 'near-ai' | 'local-analysis';
63+
}
64+
65+
// NEAR AI returns values in contract format
66+
interface AIResponse {
67+
analysis: string;
68+
stats: {
69+
Strength: number; // Contract format (2500-10000)
70+
Wit: number; // Contract format (2500-10000)
71+
Charisma: number; // Contract format (2500-10000)
72+
Defence: number; // Contract format (2500-10000)
73+
Luck: number; // Contract format (2500-10000)
74+
};
75+
reasoning?: {
76+
strength: string;
77+
wit: string;
78+
charisma: string;
79+
defence: string;
80+
luck: string;
81+
};
82+
}
83+
```
84+
85+
## Key Features
86+
87+
### 1. Dual Analysis System
88+
- **Primary**: NEAR AI personality updater for sophisticated psychological analysis
89+
- **Fallback**: Local intelligent analysis using psychological pattern matching
90+
91+
### 2. Psychological Profiling
92+
The system analyzes moral choices across multiple dimensions:
93+
- **Courage**: Willingness to face danger and adversity
94+
- **Wisdom**: Strategic thinking and decision-making
95+
- **Empathy**: Compassion and understanding for others
96+
- **Justice**: Moral righteousness and fairness
97+
- **Loyalty**: Faithfulness and reliability
98+
- **Self-Preservation**: Survival instinct and caution
99+
- **Leadership**: Ability to guide and influence others
100+
- **Adaptability**: Flexibility in changing situations
101+
102+
### 3. Trait Calculation
103+
Each psychological metric influences specific traits:
104+
- **Strength**: Influenced by courage and justice
105+
- **Wit**: Enhanced by wisdom and adaptability
106+
- **Charisma**: Driven by empathy and leadership
107+
- **Defence**: Strengthened by loyalty and self-preservation
108+
- **Luck**: Balanced by overall moral character
109+
110+
### 4. AI-Driven Growth System
111+
- **NEAR AI returns values in contract format** (multiplied by 100, range 2500-10000)
112+
- **No artificial constraints** - AI determines appropriate trait progression
113+
- **Realistic growth patterns** based on psychological analysis
114+
- **Meaningful progression** that reflects warrior's moral development
115+
116+
## Usage Flow
117+
118+
1. **User selects Yodha NFT** in the Gurukul interface
119+
2. **NFT approval** for Gurukul contract interaction
120+
3. **Enter Gurukul** to receive assigned questions
121+
4. **Answer moral questions** that test psychological traits
122+
5. **Submit responses** for AI analysis
123+
6. **Receive analysis** with trait updates and explanations
124+
7. **Contract update** with new trait values using signed data
125+
126+
## NEAR AI Integration
127+
128+
### Enhanced AI Prompt
129+
The AI receives warrior data in contract format and is instructed to return values in the same format:
130+
- **Current traits sent as contract values** (strength * 100, etc.)
131+
- **AI returns contract-format values** (range 2500-10000)
132+
- **No artificial constraints** applied by the system
133+
- **AI determines appropriate progression** based on psychological analysis
134+
135+
### Primary Method: Chat Completions
136+
```typescript
137+
const analysisPrompt = `
138+
WARRIOR PROFILE:
139+
- Current Traits: Strength ${currentTraits.strength * 100}, Wit ${currentTraits.wit * 100}...
140+
141+
ANALYSIS REQUIREMENTS:
142+
Analyze these moral choices and provide new trait values in CONTRACT FORMAT (multiplied by 100):
143+
1. STRENGTH: Physical and mental fortitude (range: 2500-10000)
144+
2. WIT: Intelligence, strategic thinking (range: 2500-10000)
145+
...
146+
147+
RESPONSE FORMAT (JSON only):
148+
{
149+
"analysis": "Brief psychological analysis...",
150+
"stats": {
151+
"Strength": [integer 2500-10000],
152+
"Wit": [integer 2500-10000],
153+
...
154+
}
155+
}
156+
`;
157+
158+
const chatResponse = await fetch("https://api.near.ai/v1/chat/completions", {
159+
method: 'POST',
160+
headers: {
161+
'Authorization': authString,
162+
'Content-Type': 'application/json'
163+
},
164+
body: JSON.stringify({
165+
model: near_agent_personality_updater,
166+
messages: [{ role: "user", content: analysisPrompt }],
167+
max_tokens: 1500,
168+
temperature: 0.7
169+
})
170+
});
171+
```
172+
173+
### Fallback Method: Threads
174+
```typescript
175+
const thread = await openai.beta.threads.create();
176+
const run = await openai.beta.threads.runs.createAndPoll(thread.id, {
177+
assistant_id: near_agent_personality_updater,
178+
});
179+
```
180+
181+
## Local Analysis Algorithm
182+
183+
When NEAR AI is unavailable, the system performs sophisticated local analysis with enhanced growth potential:
184+
185+
1. **Pattern Recognition**: Analyzes question and answer text for psychological indicators
186+
2. **Metric Scoring**: Builds psychological profile across 8 dimensions
187+
3. **Enhanced Trait Mapping**: Converts psychological metrics to meaningful trait modifications
188+
4. **Growth-Oriented Calculation**: Removes artificial constraints to allow substantial character development
189+
190+
### Improved Calculations
191+
```typescript
192+
const strengthModifier = Math.floor((courage + justice) / 2) * 150; // More significant growth
193+
const witModifier = (wisdom + adaptability / 2) * 120;
194+
const charismaModifier = (empathy + leadership) * 130;
195+
const defenceModifier = (loyalty + selfPreservation / 2) * 140;
196+
const luckModifier = Math.floor((courage + wisdom + empathy) / 3) * 100;
197+
198+
// Apply modifications with growth potential (no upper limits)
199+
const newTraits = {
200+
strength: Math.max(25, currentTraits.strength + strengthModifier),
201+
wit: Math.max(25, currentTraits.wit + witModifier),
202+
// ... etc
203+
};
204+
```
205+
206+
## Error Handling
207+
208+
The implementation includes comprehensive error handling:
209+
- **Network failures**: Graceful degradation to local analysis
210+
- **Authentication errors**: Clear error messages and retry mechanisms
211+
- **Parsing errors**: Fallback to local analysis if AI response is malformed
212+
- **Contract errors**: Separate error handling for blockchain interactions
213+
214+
## Security Features
215+
216+
- **Wallet-based authentication**: Uses NEAR wallet signatures for security
217+
- **Server-side signing**: Trait updates are signed server-side with private key
218+
- **Input validation**: Comprehensive validation of all inputs
219+
- **Rate limiting**: Natural rate limiting through blockchain transaction requirements
220+
221+
## Testing
222+
223+
A test script is provided (`test-gurukul-api.js`) to verify the API structure and logic without making actual API calls.
224+
225+
## Configuration
226+
227+
The implementation uses constants from `constants.ts`:
228+
- `near_agent_personality_updater`: NEAR AI agent ID
229+
- `chainsToTSender`: Contract addresses for different networks
230+
- `GurukulAbi`: Smart contract ABI for interactions
231+
232+
## Performance Considerations
233+
234+
- **Caching**: Trait data is cached locally to minimize contract calls
235+
- **Batch operations**: Multiple trait updates are batched when possible
236+
- **Fallback performance**: Local analysis is optimized for quick response times
237+
- **Memory management**: Cleanup of temporary data structures
238+
239+
## Future Enhancements
240+
241+
1. **Machine Learning**: Train local models on user response patterns
242+
2. **Advanced Psychology**: Incorporate additional psychological frameworks
243+
3. **Social Features**: Compare trait evolution with other players
244+
4. **Achievement System**: Reward specific psychological growth patterns
245+
5. **Narrative Integration**: Use trait changes to influence game story
246+
247+
## Deployment Notes
248+
249+
- Ensure `NEAR_AI_PRIVATE_KEY` environment variable is set
250+
- Verify contract addresses are correct for the target network
251+
- Test NEAR AI connectivity before deployment
252+
- Monitor API response times and success rates
253+
254+
This implementation provides a robust, scalable, and user-friendly Gurukul system that enhances the Web3 gaming experience while maintaining high security and performance standards.

0 commit comments

Comments
 (0)