Skip to content

Commit 3057b13

Browse files
committed
docs: 문서, 튜토리얼 및 설정 업데이트
프로젝트 문서화 및 설정 업데이트 Changes: - README.md, CHANGELOG.md, ARCHITECTURE.md, QUICK_START.md 업데이트 - 17개 Jupyter Notebook 튜토리얼 추가 - Playground Backend 문서 추가 (IMPLEMENTATION_PROGRESS.md, COMPLETION_SUMMARY.md 등) - pyproject.toml 패키지 설정 업데이트 - src/beanllm/__init__.py Public API 업데이트 - REPL UI 추가 (repl_shell.py, common_commands.py 등) - 예제 코드 추가 (model_router_example.py, streaming_example.py)
1 parent 77c94f4 commit 3057b13

File tree

63 files changed

+18835
-10657
lines changed

Some content is hidden

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

63 files changed

+18835
-10657
lines changed

ARCHITECTURE.md

Lines changed: 177 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
6. [주요 패턴](#주요-패턴)
1111
7. [데이터 흐름](#데이터-흐름)
1212

13+
> 📖 **의존성 규칙 상세 가이드**: [DEPENDENCY_RULES.md](./DEPENDENCY_RULES.md)를 참조하세요.
14+
1315
---
1416

1517
## 아키텍처 개요
@@ -246,7 +248,21 @@ src/beanllm/
246248
│ │ ├── __init__.py
247249
│ │ └── model_scanner.py # ModelScanner
248250
│ │
249-
│ └── ml/ # ML Models
251+
│ ├── security/ # Security
252+
│ │ ├── __init__.py
253+
│ │ └── config.py # SecureConfig
254+
│ │
255+
│ └── integrations/ # 외부 프레임워크 통합
256+
│ ├── __init__.py
257+
│ ├── README.md # 통합 가이드
258+
│ ├── langgraph/ # LangGraph 통합
259+
│ │ ├── bridge.py # beanLLM ↔ LangGraph 변환
260+
│ │ └── workflow.py # LangGraph 워크플로우 빌더
261+
│ └── llamaindex/ # LlamaIndex 통합
262+
│ ├── bridge.py # beanLLM ↔ LlamaIndex 변환
263+
│ └── query_engine.py # LlamaIndex Query Engine 래퍼
264+
265+
│ └── ml/ # ML Models (미사용)
250266
│ ├── __init__.py
251267
│ └── ml_models.py # BaseMLModel, PyTorchModel 등
252268
@@ -285,15 +301,116 @@ src/beanllm/
285301

286302
## 의존성 방향
287303

304+
자세한 내용은 [DEPENDENCY_RULES.md](./DEPENDENCY_RULES.md)를 참고하세요.
305+
306+
## 분산 아키텍처
307+
308+
### 개요
309+
310+
환경변수 `USE_DISTRIBUTED`에 따라 분산/인메모리 모드를 자동 선택하는 추상화 레이어를 제공합니다.
311+
312+
- **인메모리 모드** (`USE_DISTRIBUTED=false`): 기존 코드와 동일하게 동작
313+
- **분산 모드** (`USE_DISTRIBUTED=true`): Redis/Kafka를 사용한 분산 처리
314+
315+
### 주요 컴포넌트
316+
317+
1. **Rate Limiting**: Redis 기반 분산 Rate Limiter
318+
2. **캐싱**: Redis 기반 분산 캐시
319+
3. **작업 큐**: Kafka 기반 작업 큐
320+
4. **이벤트 스트리밍**: Kafka 기반 이벤트 발행/구독
321+
5. **분산 락**: Redis 기반 분산 락
322+
323+
### 데코레이터 패턴
324+
325+
분산 시스템 기능을 자동으로 적용하는 데코레이터를 제공하여 코드 중복을 85-90% 감소시켰습니다.
326+
327+
```python
328+
from beanllm.infrastructure.distributed import with_distributed_features
329+
330+
@with_distributed_features(
331+
pipeline_type="vision_rag",
332+
enable_cache=True,
333+
enable_rate_limiting=True,
334+
enable_event_streaming=True,
335+
cache_key_prefix="vision_rag:retrieve",
336+
rate_limit_key="vision:embedding",
337+
event_type="vision_rag.retrieve",
338+
)
339+
async def retrieve(self, request: VisionRAGRequest) -> VisionRAGResponse:
340+
# 실제 로직만 작성 (캐싱, Rate Limiting, 이벤트 스트리밍 자동 적용)
341+
results = self._vector_store.similarity_search(query, k=k)
342+
return VisionRAGResponse(results=results)
343+
```
344+
345+
**자동 적용 기능:**
346+
- ✅ 캐싱 (자동 키 생성, 조회, 저장)
347+
- ✅ Rate Limiting (설정 기반)
348+
- ✅ 이벤트 스트리밍 (시작/완료/실패)
349+
- ✅ 분산 락 (파일 경로 기반 자동 감지)
350+
- ✅ 동기/비동기 자동 감지
351+
352+
### 동적 설정 변경
353+
354+
런타임에 파이프라인별 설정을 자유롭게 수정할 수 있습니다.
355+
356+
```python
357+
from beanllm.infrastructure.distributed import update_pipeline_config
358+
359+
# Vision RAG의 Rate Limiting 비활성화
360+
update_pipeline_config("vision_rag", enable_rate_limiting=False)
361+
362+
# Chain의 캐시 TTL 변경
363+
update_pipeline_config("chain", chain_cache_ttl=7200)
364+
365+
# Multi-Agent의 Kafka Bus 활성화
366+
update_pipeline_config("multi_agent", use_kafka_bus=True)
367+
```
368+
369+
### 사용법
370+
371+
```python
372+
from beanllm.infrastructure.distributed import (
373+
get_rate_limiter,
374+
get_cache,
375+
get_task_queue,
376+
get_event_bus,
377+
get_distributed_lock,
378+
update_pipeline_config,
379+
get_pipeline_config
380+
)
381+
382+
# 환경변수로 자동 선택
383+
rate_limiter = get_rate_limiter()
384+
cache = get_cache()
385+
task_queue = get_task_queue("ocr.tasks")
386+
producer, consumer = get_event_bus()
387+
lock = get_distributed_lock()
388+
389+
# 설정 조회 및 수정
390+
config = get_pipeline_config("vision_rag")
391+
update_pipeline_config("vision_rag", enable_cache=True, cache_ttl=3600)
392+
```
393+
394+
**참고 자료:**
395+
- 상세 가이드: [src/beanllm/infrastructure/distributed/README.md](./src/beanllm/infrastructure/distributed/README.md)
396+
- 성능 가이드: [docs/DISTRIBUTED_ARCHITECTURE_PERFORMANCE.md](./docs/DISTRIBUTED_ARCHITECTURE_PERFORMANCE.md)
397+
398+
---
399+
400+
## 의존성 방향
401+
402+
> 📖 **상세 가이드**: [DEPENDENCY_RULES.md](./DEPENDENCY_RULES.md)를 참조하세요.
403+
288404
### 원칙
289405

290406
1. **의존성은 항상 안쪽으로** (Dependency Rule)
291407
- Facade → Handler → Service → Domain ← Infrastructure
292408
- Domain은 어떤 레이어에도 의존하지 않음
293409

294-
2. **인터페이스에 의존**
295-
- Service는 인터페이스(IChatService)에 의존
296-
- 구현체(ChatServiceImpl)는 Infrastructure에 위치
410+
2. **인터페이스에 의존** (Dependency Inversion Principle)
411+
- Handler는 Service 인터페이스(IChatService)에 의존
412+
- Service는 Domain 인터페이스에 의존
413+
- Infrastructure는 Domain 인터페이스를 구현
297414

298415
3. **의존성 주입 (Dependency Injection)**
299416
- Factory 패턴으로 의존성 관리
@@ -302,15 +419,53 @@ src/beanllm/
302419
### 의존성 다이어그램
303420

304421
```
305-
Facade Layer
306-
↓ (의존)
307-
Handler Layer
308-
↓ (의존)
309-
Service Layer (인터페이스)
310-
↓ (의존)
311-
Domain Layer ← Infrastructure Layer (구현체)
422+
┌─────────────────────────────────────────────────────────┐
423+
│ Facade Layer │
424+
│ ✅ Handler, DTO, Utils, Domain/Infrastructure │
425+
│ ❌ Service (구현체) │
426+
└──────────────────────┬────────────────────────────────────┘
427+
│ 의존
428+
┌──────────────────────▼────────────────────────────────────┐
429+
│ Handler Layer │
430+
│ ✅ Service (인터페이스), DTO, Utils │
431+
│ ❌ Service (구현체), Domain, Infrastructure │
432+
└──────────────────────┬────────────────────────────────────┘
433+
│ 의존
434+
┌──────────────────────▼────────────────────────────────────┐
435+
│ Service Layer │
436+
│ ✅ Domain (인터페이스), Infrastructure (인터페이스) │
437+
│ ❌ Handler, Facade │
438+
└──────────────────────┬────────────────────────────────────┘
439+
│ 의존
440+
┌──────────────────────▼────────────────────────────────────┐
441+
│ Domain Layer │
442+
│ ✅ Domain 내부 모듈만 │
443+
│ ❌ Service, Handler, Facade, Infrastructure │
444+
└──────────────────────┬────────────────────────────────────┘
445+
│ 구현
446+
┌──────────────────────▼────────────────────────────────────┐
447+
│ Infrastructure Layer │
448+
│ ✅ Domain (인터페이스), Utils │
449+
│ ❌ Service, Handler, Facade │
450+
└───────────────────────────────────────────────────────────┘
312451
```
313452

453+
### 핵심 규칙 요약
454+
455+
**허용된 의존성:**
456+
-**Facade** → Handler, DTO, Utils, Domain/Infrastructure (직접 사용 가능)
457+
-**Handler** → Service (인터페이스), DTO, Utils
458+
-**Service** → Domain (인터페이스), Infrastructure (인터페이스), DTO
459+
-**Domain** → Domain 내부만
460+
-**Infrastructure** → Domain (인터페이스), Utils
461+
462+
**금지된 의존성:**
463+
- ❌ 순환 의존 (Circular Dependency)
464+
- ❌ 역방향 의존 (하위 레이어 → 상위 레이어)
465+
- ❌ 구현체 직접 의존 (인터페이스 사용 필수)
466+
- ❌ Handler/Facade → Service 구현체
467+
- ❌ Domain → Service/Handler/Facade
468+
314469
---
315470

316471
## 설계 원칙
@@ -538,6 +693,16 @@ from beanllm.facade import Client, RAGChain, Agent
538693
- 모든 LLM 호출은 async/await
539694
- Streaming 지원
540695

696+
### 4. 대용량 처리
697+
- **스트리밍**: LLM 응답, 파일 로딩 스트리밍 지원
698+
- **메모리 매핑 (mmap)**: 10MB 이상 파일 자동 mmap 사용
699+
- **배치 처리**: Embedding 배치 처리, 동적 배치 분할
700+
- **병렬 처리**: ProcessPoolExecutor, asyncio.gather() 활용
701+
- **지연 로딩**: LazyLoadMixin으로 필요 시 로드
702+
- **캐싱**: LRU Cache로 메모리 효율성 향상
703+
- **분산 아키텍처**: Redis/Kafka 기반 분산 처리 (선택적)
704+
- 자세한 내용: [docs/DISTRIBUTED_ARCHITECTURE_PERFORMANCE.md](./docs/DISTRIBUTED_ARCHITECTURE_PERFORMANCE.md)
705+
541706
---
542707

543708
## 보안 고려사항
@@ -580,4 +745,4 @@ response = client.chat("Hello")
580745

581746
---
582747

583-
**최종 업데이트**: 2025-12-22
748+
**최종 업데이트**: 2026-01-XX

CHANGELOG.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,38 @@ All notable changes to this project will be documented in this file.
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
## [Unreleased] - 2026-01-XX
9+
10+
### Added
11+
12+
#### 분산 아키텍처 완전 적용
13+
-**데코레이터 패턴**: `@with_distributed_features` 데코레이터로 분산 시스템 기능 자동 적용
14+
- 코드 중복 85-90% 감소
15+
- 모든 파이프라인에 일관된 패턴 적용
16+
- Vision RAG, Multi-Agent, Chain, Graph 서비스에 적용 완료
17+
-**동적 설정 변경**: 런타임에 파이프라인별 설정 수정 가능
18+
- `update_pipeline_config()`: 파이프라인별 설정 동적 수정
19+
- `get_pipeline_config()`: 파이프라인별 설정 조회
20+
- `reset_pipeline_config()`: 파이프라인별 설정 초기화
21+
-**배치 처리 데코레이터**: `@with_batch_processing` 데코레이터로 배치 처리 자동화
22+
23+
#### 코드 최적화
24+
-**중복 코드 제거**: 중복 이벤트 로깅, 캐시 로직, Rate Limiting 로직 제거
25+
-**함수 통합**: `run_parallel_chain()`의 중복 함수 정의 통합
26+
27+
### Changed
28+
29+
#### 아키텍처 개선
30+
-**데코레이터 기반 분산 시스템**: 수동 코드 → 데코레이터 패턴으로 전환
31+
-**설정 관리**: 정적 설정 → 동적 설정 변경 지원
32+
33+
### Performance
34+
35+
-**코드 감소**: 각 메서드마다 ~30-50줄 → ~3-5줄 (85-90% 감소)
36+
-**유지보수성**: 분산 시스템 로직 변경 시 한 곳만 수정
37+
38+
---
39+
840
## [0.2.2] - 2026-01-05
941

1042
### Dependency Updates

QUICK_START.md

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -664,6 +664,77 @@ poetry env info
664664

665665
---
666666

667+
## 🌐 분산 아키텍처 (선택적)
668+
669+
### 기본 사용 (인메모리 모드)
670+
671+
기본적으로 beanllm은 **인메모리 모드**로 동작합니다. 설정 없이 바로 사용 가능하며, 단일 서버 환경에서 가장 빠른 성능을 제공합니다.
672+
673+
```python
674+
# .env 파일 (선택적)
675+
# USE_DISTRIBUTED=false # 기본값
676+
677+
# 바로 사용 가능!
678+
from beanllm import Client
679+
client = Client(model="gpt-4o")
680+
```
681+
682+
### 분산 모드 활성화 (프로덕션)
683+
684+
다중 서버 환경이나 높은 트래픽이 예상되는 경우, 분산 아키텍처를 활성화할 수 있습니다.
685+
686+
#### 1. Redis 설치 (Docker)
687+
688+
```bash
689+
docker run -d -p 6379:6379 redis:latest
690+
```
691+
692+
#### 2. Kafka 설치 (선택적, 장기 작업 처리용)
693+
694+
```bash
695+
docker run -d -p 9092:9092 apache/kafka:latest
696+
```
697+
698+
#### 3. 환경변수 설정
699+
700+
```bash
701+
# .env
702+
USE_DISTRIBUTED=true
703+
REDIS_HOST=localhost
704+
REDIS_PORT=6379
705+
KAFKA_BOOTSTRAP_SERVERS=localhost:9092
706+
```
707+
708+
#### 4. 분산 의존성 설치
709+
710+
```bash
711+
pip install beanllm[distributed]
712+
```
713+
714+
#### 5. 사용
715+
716+
```python
717+
# 자동으로 분산 아키텍처 사용
718+
from beanllm import RAGChain
719+
720+
rag = RAGChain.from_documents("docs/")
721+
response = await rag.query("What is AI?")
722+
# 자동으로 분산 캐싱, Rate Limiting, 이벤트 스트리밍 적용
723+
```
724+
725+
### 성능 개선 효과
726+
727+
| 메트릭 | 인메모리 | 분산 | 개선율 |
728+
|--------|---------|------|--------|
729+
| **평균 응답 시간** | 250ms | 180ms | **28% 빠름** |
730+
| **캐시 Hit Rate** | 10% | 85% | **8.5배 증가** |
731+
| **API 호출 수** | 900/min | 150/min | **83% 감소** |
732+
| **비용 (API 호출)** | $100/일 | $17/일 | **83% 절감** |
733+
734+
**자세한 내용**: [docs/DISTRIBUTED_ARCHITECTURE_PERFORMANCE.md](docs/DISTRIBUTED_ARCHITECTURE_PERFORMANCE.md)
735+
736+
---
737+
667738
## 📚 다음 단계
668739

669740
1. **문서 읽기**: [`docs/`](docs/) 폴더의 상세 문서

0 commit comments

Comments
 (0)