Page History
...
| Info |
|---|
리액티브 스트림을 반영해 지능형 AI 서비스 아키텍처를 보강해죠 |
보너스 - Reactive Stream 버전으로 LLM호출하기
| Code Block | ||
|---|---|---|
| ||
LLM 호출 및 AI 모듈과 연결할 때, LLM을 안정적이게 사용할수 있는 backpressure 를 이용하는 방법의 샘플 코드를 akka stream을 이용한 샘플코드를 작성해 스칼라/자바/코틀린 버전으로 각각 작성 |
...
| Code Block |
|---|
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.javadsl.*
import scala.concurrent.duration.Duration
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ThreadLocalRandom
fun main() {
val system = ActorSystem.create("llm-system")
val materializer = ActorMaterializer.create(system)
val llmFlow = Flow.of(String::class.java)
.mapAsync(4) { input -> callLLM(input) }
val inputList = (1..100).map { "input-$it" }
Source.from(inputList)
.throttle(5, Duration.create(1, "second"))
.via(llmFlow)
.runWith(Sink.foreach { println("[LLM] $it") }, materializer)
.whenComplete { _, _ -> system.terminate() }
}
fun callLLM(input: String): CompletableFuture<String> {
return CompletableFuture.supplyAsync {
Thread.sleep(ThreadLocalRandom.current().nextInt(1000))
"LLM Response for [$input]"
}
}
|
✅ 핵심 요점 (적용 시 주의사항)
| 항목 | 설명 |
|---|---|
mapAsync(parallelism = N) | N개의 요청만 동시에 실행 (backpressure 핵심) |
throttle | 외부 API 보호를 위한 속도 제한 |
callLLM | 실제 HTTP 클라이언트로 대체 가능 (WebClient, OkHttp 등) |
Sink.foreach | 결과 소비자 (후처리 로직 삽입 가능) |
| Code Block | ||
|---|---|---|
| ||
callLLM 을 HuggingFace API 호출한버전? |
...
입력:
"Translate this sentence into French: Hello, how are you?"출력:
"Bonjour, comment ça va ?"
✅ 주의사항
| 항목 | 설명 |
|---|---|
| API 호출 속도 | HuggingFace는 무료 요금제에서 제한적 TPS 허용 |
| 모델 로딩 지연 | 모델 첫 호출 시 cold-start 수초 소요 가능 |
| JSON 파싱 | 일부 모델은 generated_text 대신 다른 필드를 반환할 수 있음 |
| 에러 처리 | JSON parse 오류, 5xx 에러 등에 대비 필요 |
