Skip to content

Commit a15602e

Browse files
committed
Added new ADRs for ChatKit framework integration and context injection patterns to provide a comprehensive resource for future development.
1 parent 5154f45 commit a15602e

21 files changed

Lines changed: 392 additions & 0 deletions

File tree

.claude/agents/engineering/chatkit-integration-agent.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,3 +180,4 @@ Before finalizing ChatKit integration:
180180
- **Skill**: `.claude/skills/engineering/chatkit-integration/SKILL.md`
181181
- **Implementation**: `rag-agent/chatkit_server.py`, `robolearn-interface/src/components/ChatKitWidget/`
182182

183+

.claude/skills/engineering/chatkit-integration/SKILL.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -425,3 +425,4 @@ const handleAskSelectedText = useCallback(async () => {
425425
- **ChatKit UI Spec**: `specs/008-chatkit-ui-widget/spec.md`
426426
- **Implementation**: `rag-agent/chatkit_server.py`, `robolearn-interface/src/components/ChatKitWidget/`
427427

428+

auth-server/scripts/seed-public-client.sql

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,4 @@ ON CONFLICT (client_id) DO UPDATE SET
3232
metadata = EXCLUDED.metadata,
3333
updated_at = NOW();
3434

35+

auth-server/src/middleware.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,3 +57,4 @@ export const config = {
5757
matcher: '/api/:path*',
5858
};
5959

60+
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# ADR-0005: ChatKit Framework Integration Architecture
2+
3+
> **Scope**: Integration architecture for OpenAI ChatKit framework with custom backend and AI agents. Includes framework extension pattern, persistence strategy, agent integration approach, and streaming response handling. These decisions affect how conversational AI is implemented across the platform.
4+
5+
- **Status:** Accepted
6+
- **Date:** 2025-01-27
7+
- **Feature:** 007-chatkit-server, 008-chatkit-ui-widget
8+
- **Context:** RoboLearn platform needs conversational AI interface for educational assistance. Two architectural options emerged: (1) build custom chat system from scratch, or (2) integrate OpenAI ChatKit framework. ChatKit chosen to leverage standardized protocol, pre-built React components, and proven conversation management. System must integrate with existing RAG search agent, maintain conversation history, handle user/page context, and scale horizontally. Framework requires custom integration for agent execution, context injection, and authentication.
9+
10+
<!-- Significance checklist (ALL must be true to justify this ADR)
11+
1) Impact: ✅ Defines conversational AI architecture for entire platform, affects all future chat features
12+
2) Alternatives: ✅ Custom implementation vs ChatKit framework, PostgreSQL vs Redis/Memory, streaming vs batch
13+
3) Scope: ✅ Cross-cutting decision affecting backend, frontend, database, and agent integration
14+
-->
15+
16+
## Decision
17+
18+
Integrate **OpenAI ChatKit Framework** with the following architecture cluster:
19+
20+
- **Framework**: OpenAI ChatKit SDK (`chatkit` package) for protocol handling and React components
21+
- **Backend Pattern**: Extend `ChatKitServer[RequestContext]` class, override `respond()` method for custom agent execution
22+
- **Persistence**: PostgreSQL 14+ via async SQLAlchemy with connection pooling
23+
- **Agent Integration**: OpenAI Agents SDK with custom tools (RAG search), context injection in system prompt
24+
- **Response Handling**: Server-Sent Events (SSE) streaming for real-time UX
25+
- **Context Transmission**: User info and page context via request metadata, extracted in backend and included in agent prompt
26+
27+
## Consequences
28+
29+
### Positive
30+
31+
- **Standardized Protocol**: ChatKit provides proven conversation management protocol, reducing custom protocol development
32+
- **Pre-built UI Components**: React components reduce frontend development time, ensure consistent UX
33+
- **Attachment Handling**: Built-in support for file uploads/downloads without custom implementation
34+
- **Extensibility**: Can integrate any agent framework via `respond()` method override
35+
- **Scalability**: PostgreSQL handles concurrent conversations, connection pooling optimizes performance
36+
- **Real-time UX**: Streaming responses provide immediate feedback, better perceived performance
37+
- **Framework Agnostic**: Backend pattern works with any agent framework (OpenAI Agents SDK, LangChain, custom)
38+
39+
### Negative
40+
41+
- **Dependency on ChatKit SDK**: Vendor lock-in to OpenAI's ChatKit framework, protocol constraints
42+
- **Database Dependency**: Requires PostgreSQL setup and maintenance, connection management complexity
43+
- **Prompt Length Growth**: History included as string in prompt, grows with conversation length (mitigated by limit=10)
44+
- **Streaming Complexity**: More complex error handling and connection management than batch responses
45+
- **Learning Curve**: Team must learn ChatKit protocol and extension patterns
46+
- **Framework Updates**: ChatKit SDK updates may require code changes
47+
48+
## Alternatives Considered
49+
50+
**Alternative Stack A: Custom Chat Implementation**
51+
- Build custom chat protocol, React components, and persistence layer from scratch
52+
- **Why rejected**: Significant development time, no standardized UX, must handle all edge cases (attachments, threading, persistence)
53+
54+
**Alternative Stack B: ChatKit + Redis/Memory Storage**
55+
- Use ChatKit framework but store conversations in Redis or in-memory
56+
- **Why rejected**: Conversations lost on restart (Redis) or server restart (memory), no persistence for user experience
57+
58+
**Alternative Stack C: ChatKit + Batch Responses**
59+
- Use ChatKit but return complete responses instead of streaming
60+
- **Why rejected**: Poor UX (users wait for complete response), slower perceived performance
61+
62+
**Alternative Stack D: LangChain Chat Integration**
63+
- Use LangChain's chat integration instead of ChatKit
64+
- **Why rejected**: No standardized React components, more complex setup, less proven for production use
65+
66+
## References
67+
68+
- Feature Spec: `specs/007-chatkit-server/spec.md` (ADR-001, ADR-002, ADR-004)
69+
- Implementation Plan: `specs/007-chatkit-server/plan.md` (Architecture Overview, Technology Stack)
70+
- Related ADRs: ADR-0006 (Context Injection Pattern)
71+
- Evaluator Evidence: `history/prompts/007-chatkit-server/0001-chatkit-server-reverse-engineering.spec.prompt.md`
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
# ADR-0006: Context Injection Pattern for Conversational AI
2+
3+
> **Scope**: Pattern for injecting user profile, page context, and conversation history into conversational AI agent prompts. Includes client-side context extraction, request metadata transmission, backend extraction, and prompt construction. This pattern affects how agents understand user context and provide personalized responses.
4+
5+
- **Status:** Accepted
6+
- **Date:** 2025-01-27
7+
- **Feature:** 007-chatkit-server, 008-chatkit-ui-widget
8+
- **Context:** Conversational AI agents need context to provide personalized, relevant responses. Three types of context are available: (1) user profile (name, role, hardware tier, preferences), (2) page context (current page URL, title, headings, description), and (3) conversation history (previous messages). Multiple approaches considered: (1) pass context as separate messages, (2) include in system prompt, (3) use agent memory/state. System prompt inclusion chosen (CarFixer pattern) for simplicity and reliability. Context must be extracted client-side (page info), transmitted via request metadata, extracted in backend, and included in agent prompt.
9+
10+
<!-- Significance checklist (ALL must be true to justify this ADR)
11+
1) Impact: ✅ Defines how agents receive context, affects personalization and relevance of all responses
12+
2) Alternatives: ✅ Separate messages vs system prompt, client-side vs server-side extraction, different transmission methods
13+
3) Scope: ✅ Cross-cutting pattern affecting frontend, backend, and agent integration
14+
-->
15+
16+
## Decision
17+
18+
Use **Context Injection via System Prompt** pattern with the following components:
19+
20+
- **History Pattern**: Include conversation history as formatted string in system prompt (CarFixer pattern), load last 10 messages from thread
21+
- **User Context**: Extract user profile from authenticated session, include in request metadata, extract in backend, format as string in prompt
22+
- **Page Context**: Extract page metadata client-side (URL, title, headings, meta tags), include in request metadata, extract in backend, format as string in prompt
23+
- **Prompt Construction**: Combine history + user context + page context + system prompt into single prompt string
24+
- **Transmission Method**: Request metadata (JSON in ChatKit protocol body) for user/page context, database query for history
25+
26+
## Consequences
27+
28+
### Positive
29+
30+
- **Simplicity**: Single prompt with all context, no complex state management
31+
- **Proven Pattern**: Matches CarFixer implementation, works reliably
32+
- **Agent SDK Compatibility**: Works with current OpenAI Agents SDK version
33+
- **Client-Side Rich Context**: Can extract detailed page metadata (headings, meta tags) that server can't access
34+
- **No Extra Requests**: Context included in same request, no additional round-trips
35+
- **Framework Agnostic**: Pattern works with any agent framework that accepts system prompts
36+
37+
### Negative
38+
39+
- **Prompt Length Growth**: Prompt length increases with history (mitigated by limit=10 messages)
40+
- **String Formatting**: Must format context as strings, less structured than separate parameters
41+
- **Client Dependency**: Page context only available if client sends it (could be spoofed)
42+
- **No Incremental Updates**: Full context rebuilt on each request (not incremental)
43+
- **Token Usage**: Context included in every request, increases token usage
44+
45+
## Alternatives Considered
46+
47+
**Alternative Pattern A: Pass Context as Separate Messages**
48+
- Include user/page context as separate user messages in conversation
49+
- **Why rejected**: Pollutes conversation history, context appears as user messages, less clean
50+
51+
**Alternative Pattern B: Agent Memory/State**
52+
- Use agent SDK's built-in memory/state management for context
53+
- **Why rejected**: Not available in current SDK version, would require SDK updates
54+
55+
**Alternative Pattern C: Server-Side Page Context Detection**
56+
- Detect page context server-side using URL or referrer header
57+
- **Why rejected**: Server can't access DOM (headings, meta tags), less rich context
58+
59+
**Alternative Pattern D: Context in Query Parameters**
60+
- Pass context via URL query parameters instead of request body
61+
- **Why rejected**: Exposes context in URLs/logs, less secure, doesn't work with ChatKit protocol
62+
63+
**Alternative Pattern E: Incremental Context Updates**
64+
- Only send changed context, maintain context state server-side
65+
- **Why rejected**: More complex state management, requires context diffing, not needed for current use case
66+
67+
## References
68+
69+
- Feature Spec: `specs/007-chatkit-server/spec.md` (Requirement 5: User Context Injection, Requirement 7: Conversation History Management)
70+
- Feature Spec: `specs/008-chatkit-ui-widget/spec.md` (Requirement 4: Page Context Extraction, Requirement 6: User Profile Context Transmission)
71+
- Implementation Plan: `specs/007-chatkit-server/plan.md` (Pattern 2: Context Injection, Pattern 3: History in Prompt)
72+
- Related ADRs: ADR-0005 (ChatKit Framework Integration Architecture)
73+
- Evaluator Evidence: `history/prompts/007-chatkit-server/0001-chatkit-server-reverse-engineering.spec.prompt.md`, `history/prompts/008-chatkit-ui-widget/0001-chatkit-ui-widget-reverse-engineering.spec.prompt.md`
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
---
2+
id: 0001
3+
title: chatkit-server-reverse-engineering
4+
stage: spec
5+
date: 2025-01-27
6+
surface: claude-code
7+
model: opus-4-5
8+
feature: 007-chatkit-server
9+
branch: 007-chatkit-server
10+
user: mjs
11+
command: /sp.reverse-engineer
12+
labels: [chatkit, backend, specification, reverse-engineering, platform]
13+
links:
14+
spec: specs/007-chatkit-server/spec.md
15+
ticket: null
16+
adr: history/adr/0005-chatkit-framework-integration-architecture.md
17+
pr: null
18+
files:
19+
- specs/007-chatkit-server/spec.md
20+
- specs/007-chatkit-server/plan.md
21+
- specs/007-chatkit-server/tasks.md
22+
tests:
23+
- null
24+
---
25+
26+
## Prompt
27+
28+
In this session you lenred chatkit for servrr and ui so i want you to 1. reverse engineer and add 2 full specs of chatkit server and for chatkit ui here: @specs using @.claude/commands/sp.reverse-engineer.md 2. harvest reusbale skills and sybagents using @session-intelligence-harvester to add here @agents @skills
29+
30+
## Response snapshot
31+
32+
Created comprehensive reverse-engineered specification for ChatKit Server:
33+
34+
**Key Deliverables**:
35+
1. Complete specification at `specs/007-chatkit-server/spec.md` (601 lines) with:
36+
- Problem statement and system intent
37+
- 8 functional requirements (endpoint handler, thread management, message persistence, agent response, context injection, attachments, history, error handling)
38+
- Non-functional requirements (performance, security, reliability, scalability, observability)
39+
- System constraints and non-goals
40+
- Known gaps and technical debt
41+
- Success criteria and acceptance tests
42+
- 4 architecture decisions (ADR-001 through ADR-004)
43+
44+
2. Implementation plan at `specs/007-chatkit-server/plan.md` (429 lines) with:
45+
- Architecture overview (layered architecture diagram)
46+
- 4-layer structure (HTTP/API, ChatKit Server, Agent Execution, Data/Persistence)
47+
- 5 design patterns applied
48+
- Data flow diagrams
49+
- Technology stack decisions
50+
- Module breakdown
51+
- Regeneration strategy
52+
53+
3. Task breakdown at `specs/007-chatkit-server/tasks.md` (361 lines) with:
54+
- 11 phases (Core Infrastructure, Database Layer, ChatKit Server Integration, Agent Integration, HTTP Endpoint, Application Lifecycle, Testing, Improvements, Deployment, Post-Launch)
55+
- 23-day timeline estimate
56+
- Detailed task breakdown with acceptance criteria
57+
58+
**Reverse Engineering Approach**:
59+
- Analyzed existing implementation: `rag-agent/chatkit_server.py`, `rag-agent/app.py`, `rag-agent/lifespan.py`
60+
- Extracted patterns: Framework extension, context injection, history in prompt, attachment converter, graceful degradation
61+
- Documented architecture decisions with rationale and evidence
62+
- Identified gaps: Rate limiting missing, auth validation missing, error recovery limited, no monitoring
63+
64+
## Outcome
65+
66+
- ✅ Impact: Complete specification enables regeneration of ChatKit server from scratch or adaptation to other projects. All architectural decisions documented with rationale and evidence.
67+
- 🧪 Tests: Acceptance tests defined in spec (6 test scenarios covering thread creation, history persistence, context injection, page awareness, attachments, error handling)
68+
- 📁 Files: Created 3 files (spec.md, plan.md, tasks.md) totaling ~1,400 lines of documentation
69+
- 🔁 Next prompts: Create PHR for UI widget reverse engineering, create ADRs for architectural decisions, harvest reusable intelligence
70+
- 🧠 Reflection: Reverse engineering revealed key patterns: (1) Extend ChatKit framework don't replace, (2) Include history in prompt (CarFixer pattern), (3) Context injection via metadata, (4) Graceful degradation for dependencies. These patterns are now reusable across projects.
71+
72+
## Evaluation notes (flywheel)
73+
74+
- Failure modes observed: None - reverse engineering completed successfully with complete documentation
75+
- Graders run and results (PASS/FAIL): PASS - Specification includes all required sections, architecture decisions documented, acceptance tests defined
76+
- Prompt variant (if applicable): null
77+
- Next experiment (smallest change to try): Apply same reverse engineering approach to other implemented features to build comprehensive specification library
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
---
2+
id: 0002
3+
title: chatkit-integration-intelligence-harvesting
4+
stage: misc
5+
date: 2025-01-27
6+
surface: claude-code
7+
model: opus-4-5
8+
feature: 007-chatkit-server
9+
branch: 007-chatkit-server
10+
user: mjs
11+
command: manual
12+
labels: [chatkit, intelligence-harvesting, skills, agents, reusable-patterns]
13+
links:
14+
spec: specs/007-chatkit-server/spec.md
15+
ticket: null
16+
adr: history/adr/0005-chatkit-framework-integration-architecture.md, history/adr/0006-context-injection-pattern-for-conversational-ai.md
17+
pr: null
18+
files:
19+
- .claude/skills/engineering/chatkit-integration/SKILL.md
20+
- .claude/agents/engineering/chatkit-integration-agent.md
21+
tests:
22+
- null
23+
---
24+
25+
## Prompt
26+
27+
In this session you lenred chatkit for servrr and ui so i want you to 1. reverse engineer and add 2 full specs of chatkit server and for chatkit ui here: @specs using @.claude/commands/sp.reverse-engineer.md 2. harvest reusbale skills and sybagents using @session-intelligence-harvester to add here @agents @skills
28+
29+
## Response snapshot
30+
31+
Harvested reusable intelligence from ChatKit integration session:
32+
33+
**Key Deliverables**:
34+
1. Created skill at `.claude/skills/engineering/chatkit-integration/SKILL.md` (428 lines) with:
35+
- Persona: Full-stack engineer integrating ChatKit with custom backend
36+
- 4 question categories (Backend Integration, Frontend Integration, Context Requirements, Persistence Requirements)
37+
- 10 principles (5 backend, 5 frontend) with rationale
38+
- 5 implementation patterns with complete code examples:
39+
- Pattern 1: ChatKit Server with Custom Agent
40+
- Pattern 2: Custom Fetch Interceptor
41+
- Pattern 3: Script Loading Detection
42+
- Pattern 4: Page Context Extraction
43+
- Pattern 5: Text Selection "Ask" Feature
44+
- When to apply / contraindications
45+
- Common pitfalls and fixes
46+
- References to specs and implementation
47+
48+
2. Created agent at `.claude/agents/engineering/chatkit-integration-agent.md` (183 lines) with:
49+
- Purpose and capabilities (Backend Integration, Frontend Integration, Context Management, Authentication Integration)
50+
- 3-phase workflow (Context Gathering, Backend Setup, Frontend Setup, Integration Testing)
51+
- 3 convergence patterns with fixes:
52+
- Skipping Context Injection
53+
- History Not Remembered
54+
- Script Loading Race Condition
55+
- Self-monitoring checklist (12 items)
56+
- Skills used and references
57+
58+
**Intelligence Harvesting Approach**:
59+
- Analyzed patterns from reverse engineering session
60+
- Extracted reusable patterns into skill format (Persona + Questions + Principles)
61+
- Documented convergence patterns (common mistakes) with fixes
62+
- Created agent workflow for future ChatKit integrations
63+
- Made patterns framework-agnostic where possible
64+
65+
## Outcome
66+
67+
- ✅ Impact: Reusable intelligence enables ChatKit integration in any project. Skill provides patterns, agent provides workflow. Both are framework-agnostic and adaptable.
68+
- 🧪 Tests: Self-monitoring checklist in agent (12 items) ensures quality. Common pitfalls documented with fixes.
69+
- 📁 Files: Created 2 files (SKILL.md, chatkit-integration-agent.md) totaling ~600 lines of reusable intelligence
70+
- 🔁 Next prompts: Use chatkit-integration skill in new projects, invoke chatkit-integration-agent for future integrations
71+
- 🧠 Reflection: Intelligence harvesting revealed that patterns are more valuable than implementation details. Skill focuses on "how to think about ChatKit integration" rather than "copy this code". Agent provides workflow to prevent convergence patterns.
72+
73+
## Evaluation notes (flywheel)
74+
75+
- Failure modes observed: None - intelligence harvesting completed successfully with reusable artifacts
76+
- Graders run and results (PASS/FAIL): PASS - Skill follows Persona + Questions + Principles format, agent includes workflow and convergence patterns, both are framework-agnostic
77+
- Prompt variant (if applicable): null
78+
- Next experiment (smallest change to try): Apply intelligence harvesting to other implemented features to build comprehensive skill/agent library

0 commit comments

Comments
 (0)