From bc75ce30c2da60adeca9834a7455b832f8f75c99 Mon Sep 17 00:00:00 2001 From: Marius Date: Tue, 21 Oct 2025 16:07:35 +0300 Subject: [PATCH] Add chatbot documentation and Claude agent SDK resources --- chatbot/prd.md | 561 ++++++ chatbot/v1-arhitectura.md | 131 ++ chatbot/v2-arhitectura.md | 125 ++ input/claude-agent-sdk/README.md | 148 ++ .../claude-agent-sdk-documentation.md | 1542 +++++++++++++++++ 5 files changed, 2507 insertions(+) create mode 100644 chatbot/prd.md create mode 100644 chatbot/v1-arhitectura.md create mode 100644 chatbot/v2-arhitectura.md create mode 100644 input/claude-agent-sdk/README.md create mode 100644 input/claude-agent-sdk/claude-agent-sdk-documentation.md diff --git a/chatbot/prd.md b/chatbot/prd.md new file mode 100644 index 0000000..21847ce --- /dev/null +++ b/chatbot/prd.md @@ -0,0 +1,561 @@ +# Product Requirements Document (PRD) +## Chatbot de Suport Tehnic RAG pentru ROMFAST + +## 1. OVERVIEW ȘI OBIECTIVE + +### 1.1 Problem Statement +ROMFAST necesită un sistem de suport tehnic 24/7 care poate: +- Răspunde la întrebări tehnice ale clienților +- Oferi soluții bazate pe documentația existentă +- Menține conversații context-aware +- Funcționa independent de orice suport uman +- Integrare perfectă cu website-ul existent + +### 1.2 Goals/Objectives +**Business Goals:** +- Reducerea costurilor de suport cu 50-70% +- Îmbunătățirea satisfacției clienților (>4.0/5) +- Timp de răspuns < 5 secunde +- Disponibilitate 24/7 + +**Technical Goals:** +- Arhitectură scalabilă și maintainabilă +- Upgrade de la Flowise + Groq la Claude Agent SDK +- Implementare RAG (Retrieval-Augmented Generation) +- Session persistence și context awareness + +### 1.3 Success Metrics +- **Response accuracy**: > 90% pe întrebări tehnice +- **First query resolution**: > 75% +- **User satisfaction**: > 4.0/5 rating +- **System uptime**: > 99.5% +- **Response time**: < 5 secunde (RAG + Claude) +- **Page load time**: < 3 secunde (frontend) + +## 2. USER PERSONAS ȘI USE CASES + +### 2.1 Primary User Personas + +**Persona 1: Client Final** +- Nume: Ion Popescu +- Rol: Utilizator final al software-ului ROMFAST +- Technical skill: Limited +- Goals: Rezolvare rapidă a problemelor tehnice +- Frustrations: Așteptarea lungă pentru suport, termeni tehnici complecși +- Preferred communication: Limbaj simplu, soluții concrete + +**Persona 2: Administrator IT** +- Nume: Maria Ionescu +- Rol: IT Administrator la client ROMFAST +- Technical skill: Advanced +- Goals: Soluții tehnice detaliate, troubleshooting avansat +- Frustrations: Răspunsuri generice, lipa detaliilor tehnice +- Preferred communication: Documentație tehnică, pași detaliați + +**Persona 3: Contabil** +- Nume: Elena Vasile +- Rol: Utilizator aplicație contabilitate ROMFAST +- Technical skill: Basic +- Goals: Rezolvare rapidă erori de conectare/date +- Preferred communication: Instrucțiuni step-by-step + +### 2.2 Primary Use Cases + +**UC1: Erori de Conexiune** +- User întâmpină eroare la conectare +- caută soluții rapide și clare +- necesită pași concreți de rezolvare + +**UC2: Întrebări Tehnice Generale** +- User întreabă despre funcționalități +- necesită explicații detaliate +- vrea exemple concrete de utilizare + +**UC3: Problema Specifică Software** +- User raportează bug/error mesaj specific +- necesită identificarea cauzei +- vrea soluție/workaround + +**UC4: Integrare și Setup** +- Administrator necesită configurare sistem +- vrea documentație tehnică detaliată +- necessită best practices și configurații + +### 2.2 Telegram Use Cases + +**TU1: Quick Commands Access** +- User deschide Telegram bot +- Accesează rapid meniul principal cu `/menu` +- Navighează prin categorii predefined +- Selectează acțiuni rapide fără typing + +**TU2: Session Management** +- User începe conversație pe website, continuă pe Telegram +- Utilizează `/clear` pentru reset sesiune +- Accesează istoric cu `/history` +- Menține context între platforme + +**TU3: Structured Problem Reporting** +- User folosește menu pentru a selecta categoria problemei +- Bot adresează întrebări specifice pentru diagnostic +- Oferă solutions step-by-step +- Permite escalare către suport uman dacă needed + +**TU4: On-the-Go Assistance** +- Mobile user în teren întâmpină problemă +- Folosește Telegram pentru quick help +- Primește concise, mobile-friendly responses +- Generează documentație offline format pentru download + +## 3. FUNCTIONAL REQUIREMENTS + +### 3.1 Core Chatbot Functionality +**FR1: Question Processing** +- Accept întrebări în limbaj natural (română/engleză) +- Parse și understand intent-ul utilizatorului +- Extract key terms pentru better RAG retrieval +- Handle typos și spelling errors + +**FR2: RAG Integration** +- Search în knowledge base pentru relevant content +- Ranking results după relevance score +- Include source citations în răspunsuri +- Handle cases where no relevant info found + +**FR3: Response Generation** +- Generate contextual responses folosind Claude Agent SDK +- Include step-by-step solutions pentru probleme tehnice +- Maintain consistent brand voice (ROMFAST style) +- Provide alternative solutions dacă primary nu funcționează + +**FR4: Session Management** +- Maintain conversation context across multiple turns +- Remember previous questions și answers +- Reference earlier conversation în current responses +- Session persistence across browser refresh + +### 3.2 User Interface Requirements +**FR5: Chat Interface** +- Clean, professional UI design matching ROMFAST branding +- Responsive design (mobile & desktop) +- Real-time typing indicators +- Message history scrollable +- Input field with character limit + +**FR6: Accessibility Features** +- Keyboard navigation support +- Screen reader compatibility +- High contrast mode option +- Font size adjustment + +**FR7: Message Display** +- Clear distinction între user și bot messages +- Timestamps pentru fiecare message +- Source citations displayed clearly +- Error messages displayed user-friendly + +### 3.3 Integration Requirements +**FR8: URL Parameter Support** +- Support `?message=intrebare` parameter +- Auto-fill input field cu parameter +- Auto-send message după page load +- Handle URL encoding/decoding properly + +**FR9: Cross-Origin Communication** +- API calls către backend LXC container +- CORS configuration pentru cross-origin requests +- HTTPS encryption pentru API calls +- Error handling pentru network issues + +**FR10: Local Storage Management** +- Store session ID în localStorage +- Persistent conversation history +- Auto-cleanup după X days +- Privacy-compliant data storage + +### 3.3 Telegram Bot Functionality +**FR11: Command Processing** +- Handle slash commands (/menu, /clear, /help, /start, /history) +- Parse và process bot commands cu python-telegram-bot +- Command descriptions displayed în help menu +- Context-aware command availability + +**FR12: Interactive Menu System** +- Hierarchical menu structure cu inline keyboards +- Category navigation (Conectare, Erori, Configurare, etc.) +- Quick action buttons pentru common issues +- Back navigation în menu hierarchy +- Dynamic menu updates based on context + +**FR13: Session Management (Telegram)** +- User session tracking prin Telegram user_id +- Cross-platform session synchronization +- Session persistence across bot restarts +- Private session storage pentru confidentiality + +**FR14: Response Formatting pentru Telegram** +- Markdown formatting pentru rich text responses +- Code blocks pentru technical instructions +- Inline URL generation pentru documentation links +- Message length optimization (Telegram 4096 char limit) +- Support pentru media attachments (PDF, images) + +**FR15: Error Handling și Recovery (Telegram)** +- Graceful error handling pentru API failures +- User-friendly error messages în Telegram +- Retry mechanisms pentru failed requests +- Escalation options pentru complex issues +- Fallback messages când RAG returns no results + +## 4. NON-FUNCTIONAL REQUIREMENTS + +### 4.1 Performance Requirements +**NFR1: Response Time** +- API response < 5 secunde (including RAG retrieval) +- Frontend load time < 3 secunde +- UI interaction response < 200ms +- Real-time typing indicators < 100ms delay + +**NFR2: Scalability** +- Support concurrent 100+ users +- Handle 1000+ questions per day +- Backend auto-scaling cu Docker +- Database optimization pentru fast retrieval + +**NFR3: Reliability** +- System uptime > 99.5% +- Graceful degradation pentru partial failures +- Automatic error recovery +- Backup și recovery procedures + +### 4.2 Security Requirements +**NFR4: Data Privacy** +- No personal data storage beyond session +- Encrypted API communications +- Rate limiting pentru abuse prevention +- Input validation pentru XSS prevention + +**NFR5: Authentication** +- No user authentication required (anonymous sessions) +- Session ID generation secure enough +- Protection against session hijacking +- CSRF protection pentru API calls + +### 4.3 Maintainability +**NFR6: Code Quality** +- Clean, documented code +- Separation of concerns +- Unit tests pentru critical components +- CI/CD pipeline pentru deployments + +**NFR7: Monitoring și Debugging** +- Comprehensive logging +- Performance metrics collection +- Error tracking și alerting +- User interaction analytics + +## 5. TECHNICAL ARCHITECTURE + +### 5.1 Frontend Requirements +**TR1: Technology Stack** +- HTML5 semantic markup +- ES6+ JavaScript (vanilla, no frameworks) +- CSS3 cu modern layout (Grid/Flexbox) +- Fetch API pentru backend communication + +**TR2: Component Architecture** +- Modular JavaScript structure +- Event-driven architecture +- Component-based UI elements +- Plugin-ready architecture pentru future extensions + +### 5.2 Backend Requirements +**TR3: API Layer** +- FastAPI RESTful endpoints +- JSON request/response format +- HTTP status codes standard +- OpenAPI documentation + +**TR4: AI/ML Integration** +- Claude Agent SDK integration +- RAG pipeline cu Chroma vector DB +- Embedding models pentru text processing +- Context management pentru conversations + +**TR5: Data Layer** +- ChromaDB pentru vector storage +- In-memory session store +- File-based knowledge base storage +- Backup procedures pentru data persistence + +### 5.3 Infrastructure Requirements +**TR6: Deployment Architecture** +- Docker containerization +- Proxmox LXC deployment +- Static IP configuration +- SSL certificate management + +**TR7: Network Requirements** +- Public IP exposure pentru API +- Firewall configuration +- DDoS protection setup +- CDN integration caching (opțional) + +### 5.4 Telegram Integration Architecture** +**TR8: Telegram Bot Requirements** +- **Bot Framework**: python-telegram-bot library +- **Bot Commands**: Structured commands cu slash (/menu, /clear, /help) +- **Menu System**: Interactive inline keyboards pentru navigation +- **Session Management**: Per-user session persistence +- **Message Types**: Support text, commands, și callback queries + +**TR9: Claude Agent SDK Integration cu Telegram** +- **Message Processing**: Claude responses adapted pentru Telegram format +- **Tool Integration**: MCP servers accessible din Telegram context +- **Session Continuity**: Same session across website și Telegram +- **Context Preservation**: Conversation history maintained platform-agostic + +**TR10: Backend Communication** +- **Shared Service**: Common backend service pentru website și Telegram +- **Session Synchronization**: Sync sessions între platforms +- **Response Formatting**: Platform-specific response formatting +- **Error Handling**: Graceful degradation pentru Telegram limitations + +**TR11: Telegram-Specific Features** +- **Command Handlers**: /start, /help, /menu, /clear, /history +- **Interactive Menus**: Category navigation, quick actions +- **Callback Queries**: Menu selections, confirmations +- **Status Messages**: Typing indicators, processing states + +## 6. USER EXPERIENCE REQUIREMENTS + +### 6.1 Interaction Design +**UX1: Conversation Flow** +- Natural conversatională flow +- Proactive suggestions pentru follow-up +- Clear confirmation messages +- graceful handling pentru misunderstood questions + +**UX2: Error Management** +- Friendly error messages +- Alternative suggestions când nu înțeleg +- Option to rephrase questions +- Human hand-off option (future) + +**UX3: Visual Design** +- ROMFAST brand alignment (colors, fonts) +- Professional appearance +- Intuitive UI elements +- Consistent spacing și typography + +### 6.2 Telegram User Experience +**UX6: Telegram Bot Interface** +- Intuitive command menu structure +- Clear menu labels și descriptions +- Consistent button design și placement +- Responsive layout pentru mobile screens + +**UX7: Telegram Commands Design** +- **/start**: Welcome message și quick tutorial +- **/menu**: Interactive menu cu main categories +- **/clear**: Clear current session și start fresh +- **/help**: List all available commands și usage +- **/history**: Show conversation history summary + +**UX8: Telegram Navigation Patterns** +- Hierarchical menu flow cu back buttons +- Quick return to main menu option +- Context-sensitive menu items +- Visual feedback pentru button clicks + +**UX9: Telegram Response Structure** +- Short, mobile-friendly responses +- Bulleted lists pentru step-by-step instructions +- Code blocks formatted properly +- Emojis în moderation în brand consistency + +### 6.4 Accessibility și Usability +**UX5: Mobile Experience** +- Touch-friendly interface +- Optimized pentru smartphones +- Vertical layout preference +- Voice input support (future) + +**UX6: Localization** +- Limbavă română primary +- English as secondary +- Date/times local format +- Currency formatting (dacă relevant) + +## 7. CONSTRAINTS ȘI ASSUMPTIONS + +### 7.1 Technical Constraints +**C1: Hosting Environment** +- Frontend: Shared hosting (no server-side access) +- Backend: LXC Docker container limits +- No direct database access from frontend +- Static file serving constraints + +**C2: Budget Constraints** +- Claire Max subscription cost limits +- LXC resource limits (CPU/RAM) +- Third-party service dependencies +- Maintenance cost considerations + +### 7.2 Business Constraints +**C3: Timeline** +- Maximum 5 days pentru implementation +- Parallel development possible +- Phased roll-out approach +- Minimal disruption la existing services + +**C4: Compliance** +- GDPR compliance pentru user data +- No sensitive data storage +- Data retention policies +- User consent requirements + +### 7.3 Assumptions +**A1: User Behavior** +- Users comfortable cu chat interfaces +- Basic computer literacy +- Access la modern browsers +- Stable internet connection + +**A2: Technical Environment** +- Modern browser support (last 2 versions) +- JavaScript enabled +- HTTPS support +- Mobile browser compatibility +- Telegram app access (mobile și desktop) +- Stable internet connection pentru API calls + +## 8. SUCCESS CRITERIA ȘI LAUNCH REQUIREMENTS + +### 8.1 MVP Definition +**Minimum Viable Product includes:** +- Basic chat interface with RAG responses +- Session persistence +- URL parameter support +- Mobile responsive design +- Basic error handling + +### 8.2 Launch Criteria +**Technical readiness:** +- All functional requirements implemented +- Security testing completed +- Performance benchmarks met +- Backup procedures documented + +**Business readiness:** +- Knowledge base populated cu relevant content +- Support team trained pe system +- User documentation prepared +- Communication plan ready +- Telegram bot published și functional +- Cross-platform session testing completed + +### 8.3 Post-Launch Requirements +**PL1: Monitoring și Analytics** +- User interaction tracking +- Response quality metrics +- System performance monitoring +- Error rate tracking + +**PL2: Iteration Plan** +- Weekly performance reviews +- Monthly content updates +- Quarterly feature enhancements +- Annual architecture review + +## 9. RISK ASSESSMENT ȘI MITIGATION + +### 9.1 Technical Risks +**Risk 1: Claude API Limits** +- Impact: Service degradation +- Probability: Medium +- Mitigation: Local fallbacks, graceful degradation + +**Risk 2: Cross-Origin Issues** +- Impact: Frontend-backend communication failure +- Probability: High +- Mitigation: CORS testing, fallback mechanisms + +**Risk 3: Knowledge Base Incomplet** +- Impact: Poor response quality +- Probability: Medium +- Mitigation: Content gaps analysis, gradual population + +### 9.2 Business Risks +**Risk 4: User Adoption Low** +- Impact: Investment not justified +- Probability: Medium +- Mitigation: User training, promotional activities + +**Risk 5: Performance Issues** +- Impact: Poor user experience +- Probability: Medium +- Mitigation: Performance testing, optimization + +## 10. FUTURE ROADMAP (Post-Launch) + +### 10.1 Phase 1 (1-3 months) +- **Telegram Bot Launch**: Complete Telegram integration +- **Advanced Commands**: /ticket, /escalate, /feedback +- **Media Support**: File upload/download capabilities +- **Analytics Dashboard**: Admin interface pentru insights +- **Knowledge Base Admin**: easier content management + +### 10.2 Phase 2 (3-6 months) +- **Multi-platform Sync**: Seamless session sync website ↔ Telegram +- **Voice Input Support**: Dictation features pentru mobile +- **Integration APIs**: Connect cu CRM/ticket systems +- **Advanced Personalization**: User profiles și preferences +- **Telegram Channels**: Broadcast announcements și updates + +### 10.3 Phase 3 (6-12 months) +- **Video Tutorials**: Embedded video content în responses +- **Community Q&A**: Social features pentru peer support +- **Analytics Dashboard**: Advanced tracking și insights +- **Integration APIs**: Connect cu CRM/ticket systems + +### 10.4 Long-term Vision +- **Mobile App**: Native iOS/Android applications +- **Voice Assistant**: Phone bot integration +- **AI Agent Tools**: Diagnostic și troubleshooting automation +- **Predictive Support**: Proactive issue identification + +--- + +## ACCEPTANCE CRITERIA + +### Functional Acceptance +- [ ] Chatbot answers 90% of technical questions accurately based on knowledge base +- [ ] System maintains context across conversation turns +- [ ] URL parameter auto-fills and auto-sends messages +- [ ] Sessions persist across browser refreshes +- [ ] Mobile responsive design works on all major devices +- [ ] Error handling provides user-friendly messages + +### Technical Acceptance +- [ ] API response time < 5 seconds including RAG +- [ ] Frontend loads in < 3 seconds +- [ ] System handles 100+ concurrent users +- [ ] CORS communication works properly +- [ ] SSL encryption implemented for API calls +- [ ] Session persistence works reliably + +### Business Acceptance +- [ ] User satisfaction score > 4.0/5 +- [ ] Support cost reduction measurable +- [ ] System uptime > 99.5% +- [ ] Knowledge base populated with essential documentation +- [ ] Support team trained on system operation + +--- + +*Document Version: 1.1* +*Created: 24 Octombrie 2025* +*Last Updated: 24 Octombrie 2025* +*Status: Ready for Implementation* +*Changes: Added Telegram Bot Integration Section* diff --git a/chatbot/v1-arhitectura.md b/chatbot/v1-arhitectura.md new file mode 100644 index 0000000..cfe4077 --- /dev/null +++ b/chatbot/v1-arhitectura.md @@ -0,0 +1,131 @@ +# Plan: Chatbot RAG pentru romfast.ro + +## ARHITECTURĂ GENERALĂ + +``` +Website romfast.ro (shared hosting) → HTTPS API calls → Backend Docker LXC → Claude Agent SDK + RAG + ↑ + chatbot.html (static + JS) +``` + +## STRUCTURA SOLUȚIEI + +### Frontend (pe shared hosting romfast.ro) +- **chatbot.html**: Pagină statică minimală (skeleton HTML) +- **chatbot.js**: Tot codul JavaScript (generează HTML dinamic, face API calls) +- **CSS injectat**: Generate dinamic prin JavaScript +- **localStorage**: Pentru session persistence + +### Backend (Docker în LXC Proxmox) +- **FastAPI**: Doar 2 endpoints (`/ask` și health check) +- **Claude Agent SDK**: Integrare pentru răspunsuri inteligente +- **RAG System**: Chroma + embeddings pentru knowledge base +- **No web serving**: Doar backend API + +### Comunicare +- **HTTPS API calls**: Direct de la browser către IP-ul LXC +- **CORS**: Configurat în FastAPI pentru cross-origin +- **JSON communication**: Standard REST API + +## IMPLEMENTARE + +### Faza 1: Backend LXC (2-3 zile) +1. **Setup LXC**: Ubuntu 22.04 cu Docker +2. **Build backend**: FastAPI + Claude SDK + RAG +3. **Knowledge base**: Upload documente tehnice +4. **Test endpoints**: `/ask` și health check + +### Faza 2: Frontend Integration (1-2 zile) +1. **chatbot.html**: Adaugă pe website-ul romfast.ro +2. **chatbot.js**: JavaScript complete pentru UI și API calls +3. **Test communication**: Cross-origin API calls +4. **Mobile responsive**: Adaptare pentru mobile + +### Faza 3: Production Setup (1 zi) +1. **IP public**: Asigură acces la LXC container +2. **Security**: Rate limiting, CORS settings +3. **Testing**: Functionality și performance +4. **Documentation**: Setup instructions + +## UTILIZARE + +### Access Patterns +- **Direct URL**: `romfast.ro/chatbot.html?message=eroare+conexiune` +- **Empty start**: `romfast.ro/chatbot.html` +- **Link integration**: Din alte pagini cu parameters predefinite + +### User Flow +1. **User opens** chatbot.html (cu sau fără message) +2. **JavaScript generează** UI-ul dinamic +3. **API call către backend** întrebarea +4. **Backend procesează** cu Claude + RAG +5. **JavaScript afișează** răspunsul și sursele +6. **Session persist** în localStorage + +## TECH STACK + +### Frontend (Shared Hosting) +- **HTML5** static +- **Vanilla JavaScript** (ES6+) +- **CSS** generated via JS +- **localStorage** pentru sessions +- **Fetch API** pentru backend calls + +### Backend (LXC Docker) +- **FastAPI** (Python 3.11) +- **Claude Agent SDK** +- **ChromaDB** (vector storage) +- **Uvicorn** (ASGI server) +- **Docker** pentru containerization + +### Infrastructure +- **Proxmox LXC**: 2 CPU, 2GB RAM, 20GB SSD +- **Public IP**: Pentru API access +- **HTTPS**: Certificat SSL pentru API +- **No reverse proxy**: Direct exposure (simplificat) + +## BENEFICII + +### ✅ Technical +- **Fără dependențe de hosting infrastructure** +- **Separation of concerns**: UI vs backend +- **Scalable backend** independent de frontend +- **Easy updates**: Frontend direct pe website + +### ✅ Business +- **Zero additional hosting costs** +- **Full control** asupra backend +- **Professional appearance** pentru clienți +- **Multiple entry points**: GET parameters, direct access + +### ✅ Maintenance +- **Simple stack**: JS + FastAPI +- **Independent deployments** +- **Easy debugging** și testing +- **Standard web technologies** + +## CONSTRAINTS & SOLUTIONS + +### Constraint: No Nginx access +**Solution**: Direct HTTPS API calls către LXC IP + +### Constraint: Shared hosting +**Solution**: Frontend static, backend separate + +### Security: Cross-origin requests +**Solution**: CORS configuration în FastAPI + +## SUCCESS METRICS + +- **Setup time**: < 5 zile total +- **Page load**: < 3 secunde (HTML static) +- **API response**: < 5 secunde (RAG + Claude) +- **Mobile support**: 100% responsive +- **Session persistence**: > 95% reliability + +Acest plan oferă o soluție **practică și implementabilă** în condițiile de shared hosting, cu **arhitectură clar separată** și **deploy minim complex**. + +--- + +*Creat: 24 Octombrie 2025* +*Status: Plan de arhitectură - așteptare aprobare* diff --git a/chatbot/v2-arhitectura.md b/chatbot/v2-arhitectura.md new file mode 100644 index 0000000..c402f72 --- /dev/null +++ b/chatbot/v2-arhitectura.md @@ -0,0 +1,125 @@ +## 1. Introducere și Context +Chatbot-ul de suport tehnic ROMFAST va oferi răspunsuri asistate de RAG și Claude Agent SDK atât pe website, cât și în Telegram. Arhitectura propusă trebuie să asigure timpul de răspuns sub 5 secunde, disponibilitate ridicată, persistența sesiunilor și integrarea cu infrastructura existentă (Docker în LXC Proxmox). + +## 2. Mapare Cerințe → Soluții Arhitecturale +| Cerință cheie | Soluție arhitecturală | +| --- | --- | +| FR1, FR2, FR3 | Pipeline RAG (ChromaDB + Claude Agent SDK) cu preprocesare întrebări și scorare rezultate | +| FR4, FR10 | Session store (Redis sau SQLite in-memory backup) accesat de frontend, backend și Telegram | +| FR5–FR7 | Frontend web modular (HTML/JS/CSS) + API JSON standard | +| FR8, FR9 | FastAPI gateway cu CORS, HTTPS și suport query param `message` | +| FR11–FR15 | Microserviciu Telegram bazat pe python-telegram-bot conectat la același backend | +| NFR1–NFR3 | Containere Docker separate, auto-restart Proxmox, load shedding și cache răspunsuri | +| NFR4–NFR7 | TLS end-to-end, rate limiting, observability (logging centralizat, metrics, alerting) | + +## 3. Vedere Arhitecturală de Nivel Înalt +- **Client Web**: UI chat responsiv, gestionează sesiuni locale și comunică cu backend via Fetch API. +- **Gateway API (FastAPI)**: Orchestrare request-uri, autentificare sesiunilor anonime, fan-out către servicii interne. +- **Serviciu RAG**: Normalizare întrebări, căutare vectorială în ChromaDB, construirea contextului și apel Claude. +- **ChromaDB + Knowledge Store**: Vectori și metadate pentru documentația ROMFAST, pipeline ingestie periodică. +- **Session Store**: Stocare conversații și context (Redis/SQLite replicat) pentru persistență cross-platform. +- **Telegram Bot Service**: Handler comenzi, UI prin inline keyboards, sincronizare sesiuni cu gateway-ul. +- **Observability Stack**: Logging structurat, export metrics (Prometheus compatible) și alerting. +- **Infrastructură Docker pe Proxmox LXC**: Containere orchestrate manual sau cu docker-compose, SSL terminat via Traefik/nginx reverse proxy. + +## 4. Descriere Componentă cu Componentă +### 4.1 Client Web +- **Responsabilități**: UI chat, tip indicators, gestionare localStorage (ID sesiune, istoric recent), trimis întrebări, afișare surse. +- **Tehnologii**: HTML5, CSS3 (Flex/Grid), ES6 modules, Fetch API, Web Workers opțional pentru preprocesare. +- **Interfețe**: API REST `/api/chat`, `/api/session`, evenimente SSE/WebSocket pentru actualizări opționale. +- **Scalare**: Servire statică prin CDN/lightweight web server; caching agresiv pentru assets. + +### 4.2 Gateway API (FastAPI) +- **Responsabilități**: Validare input, rate limiting, orchestrare RAG, management erori, transformare răspunsuri. +- **Tehnologii**: FastAPI, Uvicorn, Pydantic, middleware CORS/HTTPS, JWT stateless pentru sesiuni anonime (semnare internă). +- **Interfețe**: REST endpoints `/chat`, `/session`, `/history`, `/health`; webhook Telegram `/telegram/webhook`. +- **Scalare**: Replicare container, load balancing prin reverse proxy, timeouts stricte, circuit breaker către Claude API. + +### 4.3 Serviciu RAG +- **Responsabilități**: Curățare întrebări, vectorizare (embedding), căutare top-k în ChromaDB, compunere context și prompt engineering pentru Claude. +- **Tehnologii**: Python, Claude Agent SDK, sentence-transformers (embedding), langchain-like orchestrator. +- **Interfețe**: gRPC/REST intern expus gateway-ului, contract clar pentru request/response (query, session_id, metadata). +- **Scalare**: Worker pool asincron, caching răspunsuri populare, fallback la knowledge base static în caz de indisponibilitate Claude. + +### 4.4 ChromaDB și Knowledge Store +- **Responsabilități**: Stocare vectori, metadate, versiuni documentație. +- **Tehnologii**: ChromaDB container, storage montat persistent (volume Proxmox), pipeline ingestie (Python ETL) cu scheduler. +- **Interfețe**: API nativ Chroma, scripturi ingestie (loaders), export pentru backup. +- **Scalare**: Partajare colecții pe namespace, sharding logic pentru domenii (Contabilitate, Admin, etc.), snapshot backup zilnic. + +### 4.5 Session Store +- **Responsabilități**: Persistență context conversație, state comenzi Telegram, token TTL. +- **Tehnologii**: Redis (preferat) cu fallback SQLite on-disk, replică la cald. +- **Interfețe**: API key/value, TTL, liste pentru istoricul recent; acces prin SDK Python și JS. +- **Scalare**: Master/replica, persistare RDB/AOF, monitorizare memorie. + +### 4.6 Telegram Bot Service +- **Responsabilități**: Gestionare comenzi `/start`, `/menu`, etc., generare inline keyboard, relay întrebări către gateway, formatting Markdown. +- **Tehnologii**: python-telegram-bot, async handlers, job queue pentru retry. +- **Interfețe**: Webhook către gateway, REST fallback polling, servicii interne pentru sesiuni. +- **Scalare**: Replici multiple cu queue deduplicare (Redis Streams), respectarea rate limit Telegram. + +### 4.7 Observability și DevOps +- **Responsabilități**: Logging centralizat, metrics (latency, usage), alerting, CI/CD pipelines. +- **Tehnologii**: Elastic Stack sau Loki+Grafana, Prometheus exporters, Sentry/Opentelemetry pentru tracing. +- **Interfețe**: Dashboards Grafana, webhook alerting (Slack/Email), pipeline GitHub Actions. +- **Scalare**: Retenție loguri 30 zile, sampling tracing, rotație indices. + +### 4.8 Infrastructură și Securitate +- **Responsabilități**: Orchestrare containere, management certificate, firewall, backup. +- **Tehnologii**: Docker, docker-compose, Traefik/nginx, Proxmox backup server, CrowdSec/Fail2ban. +- **Interfețe**: Reverse proxy, Let’s Encrypt ACME, scripturi deployment. +- **Scalare**: Vertical scaling LXC, pregătire migrare spre Kubernetes/Nomad dacă load crește. + +## 5. Fluxuri de Date și Sequencing +### 5.1 Întrebare din Client Web +1. UI trimite request `POST /api/chat` cu mesaj și session_id. +2. Gateway validează, atașează metadata (persona, limbă) și trimite către serviciul RAG. +3. Serviciul RAG vectorizează, interoghează ChromaDB, compune prompt cu surse. +4. Claude Agent SDK generează răspuns, gateway-l adnotează cu surse și pași. +5. Răspunsul este salvat în session store și returnat UI-ului pentru afișare. + +### 5.2 Întrebare din Telegram +1. Bot primește mesaj/comandă și trimite payload la webhook-ul gateway-ului. +2. Gateway mapează Telegram user_id la session_id comun și procesează similar cu fluxul web. +3. Răspunsul este formatat Markdown, validat sub 4096 caractere și trimis înapoi prin bot. +4. Istoricul este sincronizat în session store pentru acces cross-platform. + +### 5.3 Manevrarea Erorilor/Fallback +1. Dacă Claude sau Chroma sunt indisponibile, gateway revine la răspunsuri cached sau FAQ static. +2. În caz de eroare critică, gateway trimite mesaj prietenos utilizatorului și loghează incidentul. +3. Scheduler declanșează alerting și reinstanțează containerul afectat. + +## 6. Persistență și Management Date +- **Sesiuni**: session store cu TTL configurabil (7 zile), replicat, curățare periodică. +- **Vectori**: ChromaDB cu versiuni documente, index rebuild săptămânal, backup incremental. +- **Knowledge base raw**: Fișiere markdown/PDF într-un storage versionat (Git + backup Proxmox). +- **Loguri și Metrics**: Centralizare în Loki/Elastic, metrics în Prometheus, retenție 30 zile. + +## 7. Integrare Telegram Specifică +- Webhook securizat (secret token) expus prin reverse proxy HTTPS. +- Mapare user_id ↔ session_id în session store pentru continuitate conversații. +- Gestionare rate limiting Telegram cu queue și exponential backoff. +- Menu builder modular pentru categorii (Conectare, Erori, Configurare) configurabile din metadata. +- Fallback la notificare suport uman prin integrare viitoare (webhook spre ticketing). + +## 8. Securitate, Conformitate și Observabilitate +- **Transport**: TLS end-to-end, HSTS, certificate auto-întreținute. +- **Rate limiting**: NGINX/Traefik + Redis counters pentru prevenire abuz. +- **Validare input**: Sanitizare text, limită caractere, filtrare cod malițios. +- **Privacy**: Stocare minimă, criptare at rest pentru vectori și backup, politici GDPR (drept de ștergere). +- **Monitoring**: Health checks `/healthz`, dashboards latență, error rate, uptime. +- **Alerting**: Prag >3% erori, răspuns >4 secunde, spațiu disk <15% liber. + +## 9. Scalabilitate și Reziliență +- Containere separate pentru gateway, RAG, Chroma, Telegram cu resurse dedicate. +- Auto-restart și watchdog scripts în Proxmox, backup zilnic volume critice. +- Circuit breakers și retry policy către Claude API, degrade gracefully la fallback static. +- Posibilă introducere CDN pentru livrare statice și caching răspunsuri frecvente. + +## 10. Roadmap Tehnic (0–6 luni) +- **Luna 0–1**: Implementare client web + gateway API + RAG minim (Chroma + Claude), ingestie documentație de bază. +- **Luna 1–2**: Adăugare session store distribuit, logging centralizat, pipeline ingestie automat. +- **Luna 2–3**: Lansare Telegram bot cu comenzi de bază, sincronizare sesiuni, fallback complet erori. +- **Luna 3–4**: Introducere metrics/alerting, optimizare performanță, cache răspunsuri. +- **Luna 4–6**: Extindere knowledge base, analytics dashboard, pregătire pentru scaling (replici, load balancing). diff --git a/input/claude-agent-sdk/README.md b/input/claude-agent-sdk/README.md new file mode 100644 index 0000000..89c4fcb --- /dev/null +++ b/input/claude-agent-sdk/README.md @@ -0,0 +1,148 @@ +# Claude Agent SDK - Documentație pentru Proiecte + +Acest director conține documentație despre **Claude Agent SDK** și utilizarea acestuia în diverse contexte și proiecte. + +## Fișiere Disponibile + +### 📘 [claude-agent-sdk-documentation.md](./claude-agent-sdk-documentation.md) + +Documentație completă despre Claude Agent SDK, inclusiv: + +- **Overview**: Ce este și de ce este important +- **Instalare și Setup**: Configurare pentru Python și TypeScript +- **Arhitectură**: Concepte cheie (message blocks, query function, options) +- **Features**: Tools, permissions, MCP servers, context management +- **Cazuri de Utilizare**: + - Knowledge Management (Obsidian) + - Personal Assistants + - Custom Coding Assistants + - Customer Support + - Finance & Investment Agents + - SRE & DevOps Automation + - Research & Content Creation + - Telegram/Slack Bots +- **Exemple de Cod Detaliate**: + - Simple Query + - Custom CLI + - Obsidian Integration + - Telegram Bot cu Remote Coding + - MCP Server Setup + - Session Management + - Error Handling +- **Integrări Posibile**: Development tools, communication platforms, productivity tools +- **Monitoring**: Sentry integration, custom logging +- **Best Practices**: Security, permissions, testing, deployment +- **Resurse**: Links către documentație oficială, tutorials, community + +## Quick Links + +### Documentație Oficială Anthropic +- [Agent SDK Overview](https://docs.claude.com/en/api/agent-sdk/overview) +- [GitHub Python SDK](https://github.com/anthropics/claude-agent-sdk-python) +- [Building Agents Blog Post](https://www.anthropic.com/engineering/building-agents-with-the-claude-agent-sdk) + +### Instalare Rapidă + +**Python:** +```bash +pip install claude-agent-sdk +``` + +**TypeScript:** +```bash +npm install @anthropic-ai/claude-agent-sdk +``` + +### Example Rapid + +```python +from claude_agent_sdk import query + +options = { + "systemPrompt": "You are a helpful assistant.", + "cwd": "/workspace" +} + +messages = [{"role": "user", "content": "Help me with X"}] + +for message in query(messages=messages, options=options): + print(message) +``` + +## Utilizare în Proiecte + +### Pentru Proiecte Noi + +1. **Citește documentația completă** în `claude-agent-sdk-documentation.md` +2. **Identifică use case-ul** (coding, automation, knowledge management, etc.) +3. **Configurează agent options** (system prompt, permissions, MCP servers) +4. **Setup monitoring** (Sentry pentru production) +5. **Deploy** (Docker, serverless, etc.) + +### Exemple de Aplicații + +Din documentație poți învăța să construiești: + +- 🤖 **Telegram/Slack bots** pentru remote coding +- 📓 **Obsidian/Notion integrations** pentru knowledge management +- 👨‍💻 **Custom coding assistants** pentru tech stack-ul tău +- 🔧 **DevOps automation** pentru infrastructure management +- 💬 **Customer support bots** cu acces la CRM/database +- 📊 **Finance analysis agents** cu API integrations +- 🔍 **Research assistants** pentru content creation + +## Note Importante + +### Security Best Practices + +✅ **DO:** +- Use granular permissions (`allowedTools: ["read", "glob"]`) +- Limit working directory (`cwd: "/safe/path"`) +- Use environment variables pentru secrets +- Setup monitoring (Sentry, logs) +- Test în non-production environment first + +❌ **DON'T:** +- Use `allowedTools: "*"` în production fără review +- Set `cwd: "/"` (root access) +- Hardcode API keys/tokens în code +- Deploy without monitoring +- Give bash access without command restrictions + +### Cost Management + +- Monitor token usage (vezi Sentry integration) +- Truncate conversation history când devine prea mare +- Use prompt caching (automatic în SDK) +- Consider Claude subscription vs API credits + +### Production Readiness Checklist + +- [ ] System prompt optimizat pentru use case +- [ ] Granular permissions configurate +- [ ] MCP servers necesari setup +- [ ] Error handling implementat +- [ ] Monitoring configured (Sentry/logs) +- [ ] Session management pentru conversații +- [ ] Docker/deployment configuration +- [ ] Environment variables pentru secrets +- [ ] Testing suite pentru agent behavior +- [ ] Documentation pentru team + +## Contribuții și Updates + +Documentația este bazată pe: +- **Transcript**: "Claude Code's Real Purpose (It's Bigger Than You Think)" +- **Documentație oficială**: Anthropic Claude Agent SDK (Ianuarie 2025) +- **Web research**: Tutorials, examples, community resources + +Pentru updates: +- Verifică [documentația oficială](https://docs.claude.com/en/api/agent-sdk/overview) +- Urmărește [Anthropic blog](https://www.anthropic.com/news) +- GitHub repositories: [Python SDK](https://github.com/anthropics/claude-agent-sdk-python) + +--- + +**Happy Building!** 🚀 + +*Pentru întrebări sau clarificări, consultă documentația completă sau resursele oficiale Anthropic.* diff --git a/input/claude-agent-sdk/claude-agent-sdk-documentation.md b/input/claude-agent-sdk/claude-agent-sdk-documentation.md new file mode 100644 index 0000000..cf16c42 --- /dev/null +++ b/input/claude-agent-sdk/claude-agent-sdk-documentation.md @@ -0,0 +1,1542 @@ +# Claude Agent SDK - Documentație Completă + +## Cuprins + +1. [Overview](#overview) +2. [Ce este Claude Agent SDK](#ce-este-claude-agent-sdk) +3. [Instalare și Setup](#instalare-și-setup) +4. [Arhitectură și Concepte Cheie](#arhitectură-și-concepte-cheie) +5. [Features Principale](#features-principale) +6. [Cazuri de Utilizare](#cazuri-de-utilizare) +7. [Exemple de Cod](#exemple-de-cod) +8. [Integrări Posibile](#integrări-posibile) +9. [Monitoring și Debugging](#monitoring-și-debugging) +10. [Best Practices](#best-practices) +11. [Resurse și Referințe](#resurse-și-referințe) + +--- + +## Overview + +**Claude Agent SDK** este SDK-ul oficial de la Anthropic care permite dezvoltatorilor să construiască agenți AI custom folosind aceeași arhitectură și tooling care stau la baza **Claude Code**. + +### Insight Principal +> **Claude Code nu este doar pentru coding!** Este un "agent harness" puternic care poate fi folosit pentru orice tip de task automat: knowledge management, customer support, research, automation workflows, și mult mai mult. + +### De ce este Important? +- **Flexibility**: Construiește agenți custom pentru orice use case +- **Production-Ready**: Include context management, permissions, error handling out-of-the-box +- **Extensible**: Suport complet pentru MCP (Model Context Protocol) servers +- **Programmable**: Integrează-l în orice workflow, application sau automation + +--- + +## Ce este Claude Agent SDK + +### Evoluția Numelui +- **Înainte**: Claude Code SDK +- **Acum**: Claude Agent SDK (redenumit în 2025) +- **Motiv**: SDK-ul poate fi folosit pentru mult mai mult decât coding + +### Arhitectura Core +Claude Agent SDK este construit peste "agent harness" care alimentează Claude Code CLI. Oferă: + +``` +┌─────────────────────────────────────┐ +│ Your Custom Application/Workflow │ +│ (Telegram, Obsidian, Email, etc.) │ +└──────────────┬──────────────────────┘ + │ +┌──────────────▼──────────────────────┐ +│ Claude Agent SDK (Python/TS) │ +│ • Context Management │ +│ • Tool Execution │ +│ • Permission System │ +│ • MCP Integration │ +└──────────────┬──────────────────────┘ + │ +┌──────────────▼──────────────────────┐ +│ Claude API (Anthropic) │ +│ Claude Sonnet 4.5 / Opus │ +└─────────────────────────────────────┘ +``` + +--- + +## Instalare și Setup + +### Cerințe +- **Python**: 3.10+ +- **Node.js**: Necesar pentru unele features +- **API Key**: Anthropic API key SAU Claude subscription (Pro/Max plan) + +### Instalare Python + +```bash +# Instalare SDK +pip install claude-agent-sdk + +# Verificare instalare +python -c "from claude_agent_sdk import query; print('OK')" +``` + +### Instalare TypeScript/Node.js + +```bash +# Instalare SDK +npm install @anthropic-ai/claude-agent-sdk + +# SAU cu yarn +yarn add @anthropic-ai/claude-agent-sdk +``` + +### Autentificare + +**Opțiunea 1: Anthropic API Key** (plătești per token) +> Configurează variabila de mediu ANTHROPIC_API_KEY folosind mecanismul specific shell-ului tău (ex.: comanda `export`). + +**Opțiunea 2: Claude Subscription** (recomandat pentru development) +```bash +# Folosește Claude Pro/Max plan +claude-code login +``` + +Avantaj Opțiunea 2: Nu plătești API credits separat dacă ai deja subscription. + +--- + +## Arhitectură și Concepte Cheie + +### 1. Message Blocks + +Claude Agent SDK funcționează pe conceptul de **message blocks** - nu streamează token-by-token, ci returnează blocuri complete de acțiuni: + +``` +User Request + ↓ +[Block 1] Text: "I'll help you with that" + ↓ +[Block 2] Tool Use: Reading file xyz.py + ↓ +[Block 3] Text: "I found the issue" + ↓ +[Block 4] Tool Use: Editing file xyz.py + ↓ +[Block 5] Text: "Done! Here's what I changed..." + ↓ +[Final Block] Result: Task completed +``` + +### 2. Query Function + +Funcția centrală pentru interacțiunea cu agentul: + +```python +from claude_agent_sdk import query + +# Query returnează un iterator de message blocks +messages = query( + messages=[{"role": "user", "content": "Your request"}], + options=agent_options +) + +# Iterează prin blocks +for message in messages: + # Process each block + print(message) +``` + +### 3. Agent Options + +Configurarea agentului prin `options`: + +```python +agent_options = { + "systemPrompt": "You are a helpful assistant...", + "cwd": "/path/to/working/directory", + "allowedTools": ["read", "write", "bash", "glob"], + "mcpServers": { + "server-name": { + "command": "node", + "args": ["server.js"] + } + } +} +``` + +### 4. Context Management Automat + +SDK-ul gestionează automat: +- **Context overflow prevention**: Compactare automată când contextu devine prea mare +- **Session management**: Păstrează history-ul conversației +- **Caching**: Automatic prompt caching pentru performanță + +--- + +## Features Principale + +### 1. Rich Tool Ecosystem + +**Built-in Tools:** +- **File Operations**: Read, Write, Edit, Glob (pattern matching) +- **Code Execution**: Bash commands, Python scripts +- **Web Search**: Integrare cu search engines +- **Web Fetch**: Descarcă și procesează conținut web + +**Example:** +```python +agent_options = { + "allowedTools": [ + "read", # Citire fișiere + "write", # Scriere fișiere + "edit", # Editare fișiere (find & replace) + "glob", # Găsire fișiere prin pattern + "bash", # Execuție comenzi + "websearch", # Căutare web + "webfetch" # Fetch URL-uri + ] +} +``` + +### 2. Granular Permissions + +Control fin asupra ce poate face agentul: + +```python +# Permisiuni stricte +permissions = { + "allowedTools": ["read", "glob"], # Doar citire, fără modificări + "cwd": "/safe/directory", # Limitează la un director +} + +# Permisiuni complete +permissions = { + "allowedTools": "*", # Toate tool-urile + "bash": { + "allowedCommands": ["git", "npm", "pytest"] # Doar comenzi specifice + } +} +``` + +### 3. MCP Server Integration + +**Model Context Protocol (MCP)** permite extinderea capabilities: + +```python +mcp_config = { + "mcpServers": { + # Standard I/O server + "sequential-thinking": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-sequential-thinking"] + }, + + # SSE server + "custom-api": { + "url": "http://localhost:3000/sse", + "transport": "sse" + }, + + # Asana integration (project management) + "asana": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-asana"] + } + } +} +``` + +**Popular MCP Servers:** +- `sequential-thinking`: Extended thinking/reasoning +- `filesystem`: Advanced file operations +- `github`: GitHub API integration +- `slack`: Slack integration +- `google-drive`: Google Drive access +- `database`: SQL database access + +### 4. Streaming vs Single-Shot Mode + +**Streaming Mode** (default): +```python +# Primești blocks incremental pe măsură ce sunt generate +for message in query(messages, options): + print(message) # Block disponibil imediat +``` + +**Single-Shot Mode** (pentru batch processing): +```python +# Așteaptă completion complet +result = query_sync(messages, options) +all_blocks = list(result) +``` + +### 5. Custom System Prompts + +Definește comportamentul agentului: + +```python +options = { + "systemPrompt": """You are an expert DevOps engineer specializing in: + - Infrastructure as Code (Terraform, CloudFormation) + - CI/CD pipelines (GitHub Actions, GitLab CI) + - Container orchestration (Kubernetes, Docker) + + When solving problems: + 1. Always explain your reasoning + 2. Provide production-ready solutions + 3. Include error handling + 4. Follow security best practices + + Current project: Kubernetes migration for e-commerce platform + """ +} +``` + +--- + +## Cazuri de Utilizare + +### 1. Knowledge Management & Note-Taking + +**Use Case**: Automatizare work cu knowledge bases (Obsidian, Notion) + +**Exemplu din Transcript:** +- Integrare Claude în Obsidian vault +- Editare automată a note-urilor și scripturi YouTube +- Acces de pe telefon prin Telegram + +**Beneficii:** +- Search inteligent prin notes +- Organizare automată +- Generare conținut structurat +- Sync între multiple devices + +### 2. Personal AI Assistants + +**Use Case**: Asistenți personali pentru task automation + +**Capabilities:** +- 📅 Calendar management +- ✈️ Travel planning +- 📧 Email handling +- 📝 Meeting notes +- 🔍 Research și briefing + +**Exemplu:** +```python +# Personal assistant cu acces la calendar și email +options = { + "systemPrompt": "You are my personal assistant. Help with scheduling, emails, and research.", + "mcpServers": { + "google-calendar": {...}, + "gmail": {...} + } +} +``` + +### 3. Custom Coding Assistants + +**Use Case**: AI coding assistants customizați pentru proiectele tale + +**Diferențe față de Claude Code standard:** +- ✅ Custom system prompts pentru tech stack-ul tău +- ✅ Pre-configured MCP servers pentru API-urile tale +- ✅ Custom permissions și safety rules +- ✅ Integration în CI/CD pipeline +- ✅ Monitoring și logging custom + +**Exemplu:** +```python +# Coding assistant pentru Django projects +options = { + "systemPrompt": """Expert Django developer. + Tech stack: Django 5.0, PostgreSQL, Redis, Celery + Always follow: Django best practices, write tests, type hints""", + + "cwd": "/path/to/django/project", + + "allowedTools": ["read", "write", "edit", "bash", "grep"], + + "mcpServers": { + "postgres": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-postgres"], + "env": {"DATABASE_URL": "postgresql://..."} + } + } +} +``` + +### 4. Customer Support Automation + +**Use Case**: Agenți pentru customer support + +**Features:** +- Handle ambiguous user requests +- Access customer data (CRM integration) +- Multi-turn conversations +- Escalation la human când e necesar +- Multi-language support + +**Exemplu Workflow:** +``` +Customer Question + → Agent retrieves order history (MCP: Database) + → Agent checks shipping status (MCP: Shipping API) + → Agent provides personalized answer + → If complex: Escalate to human + provide context +``` + +### 5. Finance & Investment Agents + +**Use Case**: Analiza financiară și investment research + +**Capabilities:** +- Portfolio analysis +- Market data retrieval +- Investment calculations +- Risk assessment +- Report generation + +**Exemplu:** +```python +options = { + "systemPrompt": "Financial analyst. Analyze portfolios and provide investment insights.", + "mcpServers": { + "alpha-vantage": {...}, # Stock data + "fred": {...} # Economic data + }, + "allowedTools": ["read", "write", "python"] # Pentru calculations +} +``` + +### 6. SRE & DevOps Automation + +**Use Case**: Site Reliability Engineering tasks + +**Applications:** +- Incident diagnosis +- Log analysis +- Infrastructure changes +- Deployment automation +- Health check monitoring + +**Exemplu:** +```python +# SRE agent pentru production troubleshooting +options = { + "systemPrompt": """SRE agent. Diagnose and fix production issues. + Access: Kubernetes cluster, logs, metrics dashboards + Never: Make destructive changes without confirmation""", + + "mcpServers": { + "kubernetes": {...}, + "datadog": {...}, + "pagerduty": {...} + } +} +``` + +### 7. Research & Content Creation + +**Use Case**: Deep research și video/content creation + +**Din Transcript:** +- Anthropic folosește Claude Code pentru video creation +- Research automation +- Content organization + +**Workflow:** +``` +Research Topic + → Web search + article fetching + → Summary generation + → Organize findings în structure + → Generate script/outline + → Export în format final (MD, PDF, etc.) +``` + +### 8. Telegram/Slack Bots + +**Use Case**: Conversational interfaces în messaging apps + +**Din Transcript:** +- Telegram bot cu Claude Code integration +- Remote code execution de pe telefon +- Real-time file editing + +**Features:** +- Multi-user support +- Persistent sessions +- Command system +- File upload/download +- Monitoring dashboard + +--- + +## Exemple de Cod + +### Exemplu 1: Simple Query (Minimal) + +```python +from claude_agent_sdk import query + +# Definire options +options = { + "systemPrompt": "You are a helpful coding assistant." +} + +# Mesaje +messages = [ + {"role": "user", "content": "What is Python list comprehension?"} +] + +# Query agent +for message in query(messages=messages, options=options): + # Fiecare message este un block + if hasattr(message, 'content'): + print(message.content) +``` + +**Output:** +``` +[System Prompt Block] +[Response Block]: Python list comprehension is a concise way to create lists... +[Final Result Block]: Task completed +``` + +### Exemplu 2: Custom CLI Agent + +```python +from claude_agent_sdk import AgentClient +import os + +# Agent options +options = { + "systemPrompt": "You are an expert Python developer.", + "cwd": os.getcwd(), + "allowedTools": ["read", "write", "edit", "bash", "glob"], +} + +# Create client (reusable pentru multiple queries) +client = AgentClient(options) + +# Conversation history +conversation = [] + +print("Custom Claude CLI - Type 'exit' to quit\n") + +while True: + # User input + user_input = input("You: ").strip() + + if user_input.lower() in ['exit', 'quit']: + break + + # Add user message + conversation.append({"role": "user", "content": user_input}) + + # Query agent + assistant_response = "" + + for message in client.query(conversation): + # Handle different message types + if message.type == "text": + print(f"Assistant: {message.content}") + assistant_response += message.content + + elif message.type == "tool_use": + print(f"[Using tool: {message.tool_name}]") + + elif message.type == "final_result": + print("[Done]\n") + + # Add assistant response to conversation + if assistant_response: + conversation.append({"role": "assistant", "content": assistant_response}) +``` + +**Usage:** +```bash +$ python custom_cli.py + +Custom Claude CLI - Type 'exit' to quit + +You: List Python files in current directory +[Using tool: bash] +Assistant: You have 3 Python files: cli.py, agent.py, utils.py +[Done] + +You: Read agent.py +[Using tool: read] +Assistant: Here's the content of agent.py... +[Done] +``` + +### Exemplu 3: Obsidian Integration + +**Use Case**: Claude Code integration în Obsidian pentru knowledge management + +```python +from fastapi import FastAPI, Request +from claude_agent_sdk import AgentClient +import json + +app = FastAPI() + +# Obsidian vault path +VAULT_PATH = "/home/user/ObsidianVault" + +# Agent configuration +agent_options = { + "systemPrompt": """You are a knowledge management assistant for Obsidian. + Help organize notes, create summaries, and maintain the knowledge base. + Always preserve markdown formatting and internal links.""", + + "cwd": VAULT_PATH, + + "allowedTools": ["read", "write", "edit", "glob", "grep"], + + # Sequential thinking MCP pentru better reasoning + "mcpServers": { + "sequential-thinking": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-sequential-thinking"] + } + } +} + +# Create reusable client +agent = AgentClient(agent_options) + +# OpenAI-compatible endpoint (pentru Obsidian Copilot plugin) +@app.post("/v1/chat/completions") +async def chat_completions(request: Request): + body = await request.json() + + # Extract messages from OpenAI format + messages = body.get("messages", []) + + # Convert to Claude format + claude_messages = [ + {"role": msg["role"], "content": msg["content"]} + for msg in messages + ] + + # Query agent + response_text = "" + + for message in agent.query(claude_messages): + if message.type == "text": + response_text += message.content + + # Return în OpenAI format (pentru compatibility cu Copilot) + return { + "choices": [{ + "message": { + "role": "assistant", + "content": response_text + } + }] + } + +if __name__ == "__main__": + import uvicorn + uvicorn.run(app, host="0.0.0.0", port=8080) +``` + +**Setup Obsidian:** +1. Instalează "Copilot" community plugin +2. Settings → Copilot → Custom API +3. Base URL: `http://localhost:8080/v1` +4. Model: `claude` (orice string) + +**Usage în Obsidian:** +``` +User: My AI automations list is too long. Make it shorter. + +Agent: +[Using Glob tool to find file] +[Reading AI automations note] +[Editing file - condensing bullet points] +Done! I've shortened your list from 15 to 8 key items. +``` + +### Exemplu 4: Telegram Bot with Remote Coding + +**Use Case**: Control Claude Code remote prin Telegram (din telefon!) + +```python +import os +from telegram import Update +from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes +from claude_agent_sdk import AgentClient + +# Telegram bot token +BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN") + +# Global agent client (updated când user schimbă directory) +current_cwd = os.getcwd() +agent_client = None + +def create_agent(cwd: str, system_prompt: str = None): + """Create or update agent cu noul working directory""" + global agent_client + + options = { + "systemPrompt": system_prompt or "You are a helpful coding assistant.", + "cwd": cwd, + "allowedTools": ["read", "write", "edit", "bash", "glob", "grep"], + + # MCP servers + "mcpServers": { + "sequential-thinking": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-sequential-thinking"] + } + } + } + + agent_client = AgentClient(options) + return agent_client + +# Initialize agent +create_agent(current_cwd) + +# Command: /setdir +async def set_directory(update: Update, context: ContextTypes.DEFAULT_TYPE): + """Change working directory pentru agent""" + global current_cwd + + if not context.args: + await update.message.reply_text(f"Current directory: {current_cwd}") + return + + new_dir = " ".join(context.args) + + if os.path.isdir(new_dir): + current_cwd = new_dir + create_agent(current_cwd) + await update.message.reply_text(f"✅ Working directory set to: {new_dir}") + else: + await update.message.reply_text(f"❌ Directory not found: {new_dir}") + +# Command: /status +async def status(update: Update, context: ContextTypes.DEFAULT_TYPE): + """Show agent status""" + await update.message.reply_text(f""" +📊 Agent Status: +• Working Directory: {current_cwd} +• Tools: read, write, edit, bash, glob, grep +• MCP Servers: sequential-thinking + """) + +# Handle normal messages (queries to Claude) +async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE): + """Handle user messages - send to Claude Agent""" + user_message = update.message.text + + # Send "typing" indicator + await update.message.chat.send_action("typing") + + # Query agent + messages = [{"role": "user", "content": user_message}] + + response_blocks = [] + tool_uses = [] + + for message in agent_client.query(messages): + if message.type == "text": + response_blocks.append(message.content) + + elif message.type == "tool_use": + tool_uses.append(f"🔧 {message.tool_name}") + + # Combine response + full_response = "\n\n".join(response_blocks) + + if tool_uses: + tools_used = "\n".join(tool_uses) + full_response = f"{tools_used}\n\n{full_response}" + + # Send back to user + await update.message.reply_text(full_response) + +# Main +def main(): + app = ApplicationBuilder().token(BOT_TOKEN).build() + + # Handlers + app.add_handler(CommandHandler("setdir", set_directory)) + app.add_handler(CommandHandler("status", status)) + app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message)) + + print("🤖 Telegram bot started!") + app.run_polling() + +if __name__ == "__main__": + main() +``` + +**Usage (din Telegram pe telefon):** + +``` +User: /status +Bot: 📊 Agent Status: + • Working Directory: /home/user/projects + • Tools: read, write, edit, bash, glob, grep + • MCP Servers: sequential-thinking + +User: /setdir /home/user/django-app +Bot: ✅ Working directory set to: /home/user/django-app + +User: Add a TODO comment in views.py to refactor the login function +Bot: 🔧 glob + 🔧 read + 🔧 edit + + Done! I've added a TODO comment in views.py at line 45 above the login function. + +User: Use sequential thinking to give me 5 ideas for improving the app +Bot: 🔧 sequential-thinking + 🔧 sequential-thinking + 🔧 read + + Here are 5 improvement ideas: + 1. Add Redis caching for database queries... + 2. Implement rate limiting on API endpoints... + ... +``` + +**Din Transcript - Self-Improving Agent:** +``` +# Agent-ul își modifică propriul cod pentru a adăuga MCP server! +User (via Telegram): Add the sequential-thinking MCP server to my Claude agent + +Agent: +[Reads current bot code] +[Finds MCP configuration section] +[Edits bot.py to add sequential-thinking config] +✅ Done! Sequential thinking MCP server added. Restart the bot to use it. +``` + +### Exemplu 5: MCP Server Setup + +**Different Types of MCP Servers:** + +```python +mcp_configs = { + # 1. Standard I/O Server (most common) + "filesystem": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"], + "transport": "stdio" + }, + + # 2. SSE (Server-Sent Events) Server + "custom-api": { + "url": "http://localhost:3000/sse", + "transport": "sse" + }, + + # 3. With Environment Variables + "github": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-github"], + "env": { + "GITHUB_TOKEN": os.getenv("GITHUB_TOKEN") + } + }, + + # 4. Database Access + "postgres": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-postgres"], + "env": { + "DATABASE_URL": "postgresql://:@localhost/db" + } + }, + + # 5. Custom Local Server + "my-custom-server": { + "command": "python", + "args": ["./servers/my_server.py"], + "cwd": "/path/to/project" + } +} + +# Use în agent options +options = { + "systemPrompt": "...", + "mcpServers": mcp_configs +} +``` + +**Popular MCP Servers List:** + +| Server | Purpose | Install | +|--------|---------|---------| +| `sequential-thinking` | Extended reasoning | `npx -y @modelcontextprotocol/server-sequential-thinking` | +| `filesystem` | File operations | `npx -y @modelcontextprotocol/server-filesystem` | +| `github` | GitHub API | `npx -y @modelcontextprotocol/server-github` | +| `gitlab` | GitLab API | `npx -y @modelcontextprotocol/server-gitlab` | +| `postgres` | PostgreSQL | `npx -y @modelcontextprotocol/server-postgres` | +| `mysql` | MySQL/MariaDB | `npx -y @modelcontextprotocol/server-mysql` | +| `sqlite` | SQLite | `npx -y @modelcontextprotocol/server-sqlite` | +| `slack` | Slack integration | `npx -y @modelcontextprotocol/server-slack` | +| `google-drive` | Google Drive | `npx -y @modelcontextprotocol/server-google-drive` | +| `brave-search` | Web search | `npx -y @modelcontextprotocol/server-brave-search` | + +### Exemplu 6: Session Management & Conversation History + +```python +from claude_agent_sdk import AgentClient +import json +from datetime import datetime + +class ConversationManager: + """Manage multi-turn conversations with persistent history""" + + def __init__(self, session_file="session.json"): + self.session_file = session_file + self.history = self.load_session() + + # Agent options + self.options = { + "systemPrompt": "You are a helpful assistant.", + "cwd": "/workspace", + "allowedTools": "*" + } + + self.client = AgentClient(self.options) + + def load_session(self): + """Load conversation history from file""" + try: + with open(self.session_file, 'r') as f: + return json.load(f) + except FileNotFoundError: + return [] + + def save_session(self): + """Save conversation history to file""" + with open(self.session_file, 'w') as f: + json.dump(self.history, f, indent=2) + + def chat(self, user_message: str) -> str: + """Send message and get response""" + + # Add user message to history + self.history.append({ + "role": "user", + "content": user_message, + "timestamp": datetime.now().isoformat() + }) + + # Query agent with full history + response_text = "" + + for message in self.client.query(self.history): + if message.type == "text": + response_text += message.content + + # Add assistant response to history + self.history.append({ + "role": "assistant", + "content": response_text, + "timestamp": datetime.now().isoformat() + }) + + # Persist to disk + self.save_session() + + return response_text + + def clear(self): + """Clear conversation history""" + self.history = [] + self.save_session() + +# Usage +manager = ConversationManager("my_session.json") + +# Turn 1 +print(manager.chat("What is FastAPI?")) + +# Turn 2 (remembers context!) +print(manager.chat("Show me an example endpoint")) + +# Turn 3 +print(manager.chat("Add error handling to that example")) + +# Clear when done +# manager.clear() +``` + +### Exemplu 7: Error Handling & Retries + +```python +from claude_agent_sdk import AgentClient, AgentError +import time + +def query_with_retry(client: AgentClient, messages: list, max_retries=3): + """Query agent cu retry logic pentru errors""" + + for attempt in range(max_retries): + try: + results = [] + + for message in client.query(messages): + results.append(message) + + return results + + except AgentError as e: + if "rate_limit" in str(e).lower(): + # Rate limit - wait and retry + wait_time = 2 ** attempt # Exponential backoff + print(f"Rate limited. Waiting {wait_time}s before retry...") + time.sleep(wait_time) + + elif "context_length" in str(e).lower(): + # Context too long - truncate history + print("Context too long. Truncating history...") + messages = messages[-10:] # Keep last 10 messages + + else: + # Other error - re-raise + raise + + except Exception as e: + print(f"Unexpected error: {e}") + if attempt == max_retries - 1: + raise + time.sleep(1) + + raise Exception(f"Failed after {max_retries} retries") + +# Usage +client = AgentClient({"systemPrompt": "..."}) + +messages = [{"role": "user", "content": "Help me debug this code"}] + +try: + results = query_with_retry(client, messages) + for msg in results: + print(msg) +except Exception as e: + print(f"Failed: {e}") +``` + +--- + +## Integrări Posibile + +### 1. Development Tools + +| Tool | Integration Type | Use Case | +|------|-----------------|----------| +| **VS Code** | Extension/API | Custom coding assistant în IDE | +| **JetBrains IDEs** | Plugin | IntelliJ, PyCharm, WebStorm integration | +| **Vim/Neovim** | Plugin/RPC | Terminal-based coding assistant | +| **GitHub** | Actions/Webhooks | CI/CD automation, PR reviews | +| **GitLab** | CI/CD | Pipeline automation | +| **Jira** | API | Ticket analysis, task automation | + +### 2. Communication Platforms + +| Platform | Integration | Use Case | +|----------|------------|----------| +| **Telegram** | Bot API | Remote coding, notifications | +| **Slack** | Bot/Slash Commands | Team assistant, code reviews | +| **Discord** | Bot | Community support, automation | +| **Email** | IMAP/SMTP | Email automation, summarization | +| **WhatsApp** | Business API | Customer support | + +### 3. Productivity Tools + +| Tool | Integration | Use Case | +|------|------------|----------| +| **Obsidian** | Plugin/API | Knowledge management | +| **Notion** | API | Database management, content creation | +| **Todoist** | API | Task automation | +| **Google Calendar** | API | Scheduling, reminders | +| **Trello** | API | Project management | + +### 4. Development Platforms + +| Platform | Integration | Use Case | +|----------|------------|----------| +| **Vercel** | Deploy hooks | Auto-deploy & testing | +| **Netlify** | Build plugins | CI/CD automation | +| **AWS** | Lambda | Serverless agent execution | +| **Google Cloud** | Cloud Functions | Scalable agents | +| **Docker** | Container | Isolated agent environments | + +### 5. Databases & Storage + +| Service | MCP Server | Use Case | +|---------|-----------|----------| +| **PostgreSQL** | `server-postgres` | Database queries, migrations | +| **MySQL** | `server-mysql` | Database operations | +| **MongoDB** | Custom | NoSQL operations | +| **Redis** | Custom | Cache management | +| **S3** | Custom | File storage/retrieval | + +### 6. Monitoring & Analytics + +| Tool | Integration | Use Case | +|------|------------|----------| +| **Sentry** | SDK Integration | Error tracking, performance | +| **Datadog** | API | Metrics, logs, traces | +| **Grafana** | API | Dashboard queries | +| **New Relic** | API | Performance monitoring | +| **Prometheus** | API | Metrics querying | + +--- + +## Monitoring și Debugging + +### Sentry Integration (din Transcript) + +**De ce Sentry pentru AI Agents?** +- ✅ Vezi toate deciziile pe care le-a luat agentul +- ✅ Token usage tracking +- ✅ Performance metrics (timp de execuție) +- ✅ Tool call tracing +- ✅ Error tracking + +**Setup:** + +```python +import sentry_sdk +from sentry_sdk.integrations.anthropic import AnthropicIntegration + +# Initialize Sentry cu AI monitoring +sentry_sdk.init( + dsn="your-sentry-dsn", + integrations=[ + AnthropicIntegration(), # Special pentru Claude/Anthropic + ], + traces_sample_rate=1.0, # 100% trace sampling +) + +# Use Claude Agent SDK normally +from claude_agent_sdk import AgentClient + +client = AgentClient({...}) + +# Toate queries sunt automat tracked în Sentry! +for message in client.query(messages): + print(message) +``` + +**Ce Vezi în Sentry Dashboard:** + +``` +📊 Trace: "User request - Fix authentication bug" +├─ Span: Agent Query (2.3s) +│ ├─ Input tokens: 1,234 +│ ├─ Output tokens: 567 +│ └─ Model: claude-sonnet-4.5 +│ +├─ Tool: glob (0.1s) +│ └─ Pattern: "**/*auth*.py" +│ +├─ Tool: read (0.05s) +│ └─ File: auth/views.py +│ +├─ Tool: edit (0.2s) +│ └─ Changes: +5 lines, -3 lines +│ +└─ Total: 2.65s, 1,801 tokens +``` + +**Exemplu cu Sentry (Telegram Bot):** + +```python +import sentry_sdk +from sentry_sdk.integrations.anthropic import AnthropicIntegration +from claude_agent_sdk import AgentClient +from telegram.ext import ApplicationBuilder, MessageHandler, filters + +# Sentry setup +sentry_sdk.init( + dsn=os.getenv("SENTRY_DSN"), + integrations=[AnthropicIntegration()], + traces_sample_rate=1.0, + environment="production", +) + +async def handle_message(update, context): + user_message = update.message.text + + # Sentry automatically tracks this! + with sentry_sdk.start_transaction(op="agent_query", name=user_message[:50]): + agent = AgentClient(options) + + for message in agent.query([{"role": "user", "content": user_message}]): + if message.type == "text": + await update.message.reply_text(message.content) + +# Bot setup +app = ApplicationBuilder().token(os.getenv("BOT_TOKEN")).build() +app.add_handler(MessageHandler(filters.TEXT, handle_message)) +app.run_polling() +``` + +**Beneficii în Production:** +1. **Debugging**: Vezi exact ce a făcut agentul pentru fiecare request +2. **Validation**: Verifică dacă agentul face deciziile corecte +3. **Cost Tracking**: Monitorizează token usage +4. **Performance**: Identifică bottlenecks +5. **Errors**: Catch și debug issues rapid + +### Custom Logging + +```python +import logging +from claude_agent_sdk import AgentClient + +# Setup logging +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('agent.log'), + logging.StreamHandler() + ] +) + +logger = logging.getLogger(__name__) + +def query_with_logging(client, messages): + """Query cu detailed logging""" + + logger.info(f"Starting query with {len(messages)} messages") + + tool_calls = [] + response_text = "" + + for message in client.query(messages): + if message.type == "text": + logger.info(f"Text response: {message.content[:100]}...") + response_text += message.content + + elif message.type == "tool_use": + logger.info(f"Tool use: {message.tool_name} with args: {message.args}") + tool_calls.append(message.tool_name) + + elif message.type == "error": + logger.error(f"Agent error: {message.error}") + + logger.info(f"Query completed. Tools used: {tool_calls}") + + return response_text +``` + +--- + +## Best Practices + +### 1. Security & Permissions + +**❌ BAD - Prea permisiv:** +```python +options = { + "allowedTools": "*", # TOT! + "cwd": "/" # ROOT ACCESS! +} +``` + +**✅ GOOD - Granular permissions:** +```python +options = { + "allowedTools": ["read", "glob"], # Doar citire + "cwd": "/safe/project/directory", # Specific directory + "bash": { + "allowedCommands": ["git status", "npm test"] # Specific commands + } +} +``` + +### 2. System Prompts + +**❌ BAD - Vague:** +```python +"systemPrompt": "You are helpful." +``` + +**✅ GOOD - Specific și contextual:** +```python +"systemPrompt": """You are an expert DevOps engineer for our e-commerce platform. + +Tech Stack: +- Backend: Django 5.0, PostgreSQL, Redis +- Frontend: Next.js 14, TypeScript +- Infrastructure: Kubernetes on AWS EKS +- CI/CD: GitHub Actions + +Guidelines: +1. Always write production-ready code with error handling +2. Include unit tests for new features +3. Follow our coding standards (Black, ESLint) +4. Document infrastructure changes +5. Never commit secrets or credentials + +Current task: Kubernetes migration from EC2 instances +""" +``` + +### 3. Error Handling + +**✅ Always wrap queries în try-catch:** +```python +try: + for message in agent.query(messages): + process(message) +except AgentError as e: + logger.error(f"Agent error: {e}") + # Fallback logic +except Exception as e: + logger.error(f"Unexpected error: {e}") + sentry_sdk.capture_exception(e) +``` + +### 4. Context Management + +**❌ BAD - Unlimited history:** +```python +# History devine prea mare! +conversation_history.append(every_single_message) +``` + +**✅ GOOD - Truncate sau summarize:** +```python +# Păstrează doar ultimele N mesaje +MAX_HISTORY = 20 + +if len(conversation_history) > MAX_HISTORY: + # Păstrează system prompt + ultimele mesaje + conversation_history = [ + conversation_history[0], # System prompt + *conversation_history[-MAX_HISTORY:] + ] +``` + +### 5. MCP Server Management + +**✅ Use environment variables pentru secrets:** +```python +"mcpServers": { + "github": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-github"], + "env": { + "GITHUB_TOKEN": os.getenv("GITHUB_TOKEN") # ✅ Din env + # ❌ NU: evita hardcodarea token-ului direct în configurație + } + } +} +``` + +### 6. Testing + +**✅ Test agent behavior:** +```python +import pytest +from claude_agent_sdk import AgentClient + +def test_agent_file_reading(): + """Test că agentul poate citi fișiere""" + + client = AgentClient({ + "cwd": "/test/directory", + "allowedTools": ["read"] + }) + + messages = [{"role": "user", "content": "Read test.txt"}] + + used_tools = [] + for message in client.query(messages): + if message.type == "tool_use": + used_tools.append(message.tool_name) + + assert "read" in used_tools + +def test_agent_permissions(): + """Test că permissions sunt respectate""" + + client = AgentClient({ + "allowedTools": ["read"] # Doar read + }) + + messages = [{"role": "user", "content": "Delete file.txt"}] + + with pytest.raises(PermissionError): + list(client.query(messages)) +``` + +### 7. Performance Optimization + +**✅ Use prompt caching:** +```python +# Claude Agent SDK face asta automat, dar poți optimiza prin: +# - Păstrează system prompts consistente +# - Reuse același client pentru multiple queries +# - Evită schimbări frecvente de configuration + +client = AgentClient(options) # ✅ Create once + +for user_request in requests: + # ✅ Reuse client - automatic caching! + client.query([{"role": "user", "content": user_request}]) +``` + +### 8. Monitoring în Production + +**✅ Always monitor în production:** +```python +# 1. Sentry pentru traces +sentry_sdk.init(dsn="...", integrations=[AnthropicIntegration()]) + +# 2. Custom metrics +from prometheus_client import Counter, Histogram + +agent_queries = Counter('agent_queries_total', 'Total agent queries') +agent_duration = Histogram('agent_duration_seconds', 'Agent query duration') + +@agent_duration.time() +def query_agent(messages): + agent_queries.inc() + return list(client.query(messages)) + +# 3. Logging +logger.info(f"Agent query: {user_message}") +``` + +### 9. Cost Management + +**✅ Track și optimize costs:** +```python +# Monitor token usage +total_tokens = 0 + +for message in client.query(messages): + if hasattr(message, 'usage'): + total_tokens += message.usage.get('total_tokens', 0) + +logger.info(f"Total tokens used: {total_tokens}") + +# Set limits +if total_tokens > MAX_TOKENS_PER_SESSION: + raise Exception("Token limit exceeded") +``` + +### 10. Deployment + +**✅ Containerize pentru consistency:** + +```dockerfile +# Dockerfile pentru agent deployment +FROM python:3.11-slim + +# Install Node.js (pentru MCP servers) +RUN apt-get update && apt-get install -y nodejs npm + +WORKDIR /app + +# Install dependencies +COPY requirements.txt . +RUN pip install -r requirements.txt + +# Copy agent code +COPY . . + +# Environment variables (definește-le în runtime sau pipeline) +# - ANTHROPIC_API_KEY +# - SENTRY_DSN + +CMD ["python", "agent.py"] +``` + +--- + +## Resurse și Referințe + +### Documentație Oficială + +- **Claude Agent SDK Docs**: https://docs.claude.com/en/api/agent-sdk/overview +- **GitHub Python SDK**: https://github.com/anthropics/claude-agent-sdk-python +- **GitHub TypeScript SDK**: https://github.com/anthropics/claude-agent-sdk-typescript +- **Migration Guide** (Code SDK → Agent SDK): https://docs.claude.com/en/api/agent-sdk/migration + +### Anthropic Blog Posts + +- **Building Agents with Claude Agent SDK**: https://www.anthropic.com/engineering/building-agents-with-the-claude-agent-sdk +- **Enabling Claude Code to Work More Autonomously**: https://www.anthropic.com/news/enabling-claude-code-to-work-more-autonomously +- **Agent Skills**: https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills + +### Tutorials și Guides + +- **DataCamp Tutorial**: https://www.datacamp.com/tutorial/how-to-use-claude-agent-sdk +- **Practical Guide to Custom Coding Agents**: https://www.eesel.ai/blog/custom-coding-agents-claude-code-sdk +- **Python SDK Guide 2025**: https://www.eesel.ai/blog/python-claude-code-sdk + +### MCP (Model Context Protocol) + +- **MCP Documentation**: https://modelcontextprotocol.io +- **MCP Servers List**: https://github.com/modelcontextprotocol/servers +- **Create Custom MCP Server**: https://modelcontextprotocol.io/docs/creating-servers + +### Monitoring & Observability + +- **Sentry AI Monitoring**: https://docs.sentry.io/platforms/python/integrations/anthropic/ +- **LangSmith** (alternative): https://docs.smith.langchain.com/ +- **Weights & Biases** (alternative): https://wandb.ai/ + +### Example Projects & Repositories + +- **Claude Code Examples** (din transcript): https://github.com/[repository-link-from-video] +- **Awesome Claude Agents**: https://github.com/topics/claude-agent-sdk +- **Community Examples**: https://github.com/anthropics/anthropic-cookbook + +### Community + +- **Discord**: Anthropic Discord server +- **Reddit**: r/ClaudeAI +- **Twitter**: @AnthropicAI + +--- + +## Concluzie + +**Claude Agent SDK** nu este doar pentru coding - este o platformă completă pentru a construi **orice tip de agent AI** care beneficiază de: + +✅ **File operations puternice** (read, write, edit, search) +✅ **Code execution** (bash, Python, etc.) +✅ **Extensibility** (MCP servers pentru orice API/service) +✅ **Production-ready features** (permissions, error handling, context management) +✅ **Flexibility** (integrează în orice app/workflow) + +### Key Takeaways + +1. **Beyond Coding**: Use pentru knowledge management, automation, research, support +2. **Programmable**: Controlează totul - system prompts, permissions, tools, MCP servers +3. **Integration-Friendly**: Telegram, Obsidian, Slack, Email, CI/CD, etc. +4. **Production-Ready**: Built-in monitoring (Sentry), error handling, caching +5. **Future-Proof**: Arhitectura care va fi copiată de alte AI coding tools + +### Următorii Pași + +1. **Experimentează** cu quick start examples +2. **Alege un use case** (e.g., Telegram bot, Obsidian integration) +3. **Configurează MCP servers** pentru API-urile tale +4. **Setup monitoring** (Sentry) +5. **Deploy în production** (Docker, AWS Lambda, etc.) + +**Happy Building!** 🚀 + +--- + +*Documentație generată pe baza transcriptului "Claude Code's Real Purpose" și documentației oficiale Anthropic (Ianuarie 2025)*