How-To: 대화 API로 LLM과 대화하기
대규모 언어 모델과 상호작용하는 복잡함을 추상화하는 방법 알아보기
Alpha
대화 API는 현재 alpha 단계예요. 대화 API 사용을 시작해 볼게요. 이 가이드에서 배울 내용은 다음과 같아요:
- 대화 API와 함께 동작하는 사용 가능한 Dapr 컴포넌트(echo) 중 하나를 설정해요.
- 애플리케이션에 대화 클라이언트를 추가해요.
dapr run을 사용해 연결을 실행해요.
출처: Dapr 문서
본문
대화 컴포넌트 설정하기
conversation.yaml이라는 새 구성 파일을 만들고 애플리케이션 디렉터리의 components 또는 config 하위 폴더에 저장해요.
conversation.yaml 파일에 원하는 대화 컴포넌트 스펙을 선택해요.
이 시나리오에서는 간단한 echo 컴포넌트를 사용할게요.
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: echo
spec:
type: conversation.echo
version: v1
OpenAI 컴포넌트 사용하기
실제 LLM과 연동하려면 OpenAI, Hugging Face, Anthropic, DeepSeek 등을 비롯한 다른 지원되는 대화 컴포넌트 중 하나를 사용해요.
예를 들어 echo 목 컴포넌트를 OpenAI 컴포넌트로 바꾸려면 conversation.yaml 파일을 다음과 같이 교체해요. API 키를 컴포넌트 파일에 복사해 넣어야 해요.
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: openai
spec:
type: conversation.openai
metadata:
- name: key
value: <REPLACE_WITH_YOUR_KEY>
- name: model
value: gpt-4-turbo
대화 클라이언트 연결하기
다음 예시는 Dapr SDK 클라이언트를 사용해 LLM과 상호작용해요.
- .NET
- Java
- Python
- Go
- Rust
using Dapr.AI.Conversation;
using Dapr.AI.Conversation.Extensions;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDaprConversationClient();
var app = builder.Build();
var conversationClient = app.Services.GetRequiredService<DaprConversationClient>();
var response = await conversationClient.ConverseAsync("conversation",
new List<DaprConversationInput>
{
new DaprConversationInput(
"Please write a witty haiku about the Dapr distributed programming framework at dapr.io",
DaprConversationRole.Generic)
});
Console.WriteLine("conversation output: ");
foreach (var resp in response.Outputs)
{
Console.WriteLine($"\t{resp.Result}");
}
//dependencies
import io.dapr.client.DaprClientBuilder;
import io.dapr.client.DaprPreviewClient;
import io.dapr.client.domain.ConversationInput;
import io.dapr.client.domain.ConversationRequest;
import io.dapr.client.domain.ConversationResponse;
import reactor.core.publisher.Mono;
import java.util.List;
public class Conversation {
public static void main(String[] args) {
String prompt = "Please write a witty haiku about the Dapr distributed programming framework at dapr.io";
try (DaprPreviewClient client = new DaprClientBuilder().buildPreviewClient()) {
System.out.println("Input: " + prompt);
ConversationInput daprConversationInput = new ConversationInput(prompt);
// Component name is the name provided in the metadata block of the conversation.yaml file.
Mono<ConversationResponse> responseMono = client.converse(new ConversationRequest("echo",
List.of(daprConversationInput))
.setContextId("contextId")
.setScrubPii(true).setTemperature(1.1d));
ConversationResponse response = responseMono.block();
System.out.printf("conversation output: %s", response.getConversationOutputs().get(0).getResult());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
#dependencies
from dapr.clients import DaprClient
from dapr.clients.grpc._request import ConversationInput
#code
with DaprClient() as d:
inputs = [
ConversationInput(content="Please write a witty haiku about the Dapr distributed programming framework at dapr.io", role='user', scrub_pii=True),
]
metadata = {
'model': 'modelname',
'key': 'authKey',
'responseCacheTTL': '10m',
}
response = d.converse_alpha1(
name='echo', inputs=inputs, temperature=0.7, context_id='chat-123', metadata=metadata
)
for output in response.outputs:
print(f'conversation output: {output.result}')
package main
import (
"context"
"fmt"
dapr "github.com/dapr/go-sdk/client"
"log"
)
func main() {
client, err := dapr.NewClient()
if err != nil {
panic(err)
}
input := dapr.ConversationInput{
Content: "Please write a witty haiku about the Dapr distributed programming framework at dapr.io",
// Role: "", // Optional
// ScrubPII: false, // Optional
}
fmt.Printf("conversation input: %s\n", input.Content)
var conversationComponent = "echo"
request := dapr.NewConversationRequest(conversationComponent, []dapr.ConversationInput{input})
resp, err := client.ConverseAlpha1(context.Background(), request)
if err != nil {
log.Fatalf("err: %v", err)
}
fmt.Printf("conversation output: %s\n", resp.Outputs[0].Result)
}
use dapr::client::{ConversationInputBuilder, ConversationRequestBuilder};
use std::thread;
use std::time::Duration;
type DaprClient = dapr::Client<dapr::client::TonicClient>;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Sleep to allow for the server to become available
thread::sleep(Duration::from_secs(5));
// Set the Dapr address
let address = "https://127.0.0.1".to_string();
let mut client = DaprClient::connect(address).await?;
let input = ConversationInputBuilder::new("Please write a witty haiku about the Dapr distributed programming framework at dapr.io").build();
let conversation_component = "echo";
let request =
ConversationRequestBuilder::new(conversation_component, vec![input.clone()]).build();
println!("conversation input: {:?}", input.content);
let response = client.converse_alpha1(request).await?;
println!("conversation output: {:?}", response.outputs[0].result);
Ok(())
}
대화 연결 실행하기
dapr run 명령을 사용해 연결을 시작해요. 예를 들어 이 시나리오에서는 앱 ID conversation으로 애플리케이션에서 dapr run을 실행하고, ./config 디렉터리의 대화 YAML 파일을 가리켜요.
- .NET
- Java
- Python
- Go
- Rust
dapr run --app-id conversation --dapr-grpc-port 50001 --log-level debug --resources-path ./config -- dotnet run
dapr run --app-id conversation --dapr-grpc-port 50001 --log-level debug --resources-path ./config -- mvn spring-boot:run
dapr run --app-id conversation --dapr-grpc-port 50001 --log-level debug --resources-path ./config -- python3 app.py
dapr run --app-id conversation --dapr-grpc-port 50001 --log-level debug --resources-path ./config -- go run ./main.go
dapr run --app-id=conversation --resources-path ./config --dapr-grpc-port 3500 -- cargo run --example conversation
예상 출력
- '== APP == conversation output: Please write a witty haiku about the Dapr distributed programming framework at dapr.io'
고급 기능
대화 API는 다음 기능을 지원해요:
- 프롬프트 캐싱: 개발자가 Dapr에서 프롬프트를 캐시해 응답 시간을 크게 줄이고, egress 및 LLM 제공업체 캐시에 프롬프트를 넣는 비용을 줄여요.
- PII 스크러빙: LLM으로 들어가고 나오는 데이터를 난독화해요.
- 도구 호출: LLM이 외부 함수와 API와 상호작용하게 해줘요.
이 기능들을 활성화하는 방법은 대화 API 참조 가이드를 참고하세요.
Dapr SDK 저장소의 대화 API 예시
지원되는 SDK 저장소에 제공된 전체 예시로 대화 API를 사용해 보세요.
- .NET
- Java
- Python
- Go
- Rust
.NET SDK를 사용한 Dapr 대화 예시
Java SDK를 사용한 Dapr 대화 예시
Python SDK를 사용한 Dapr 대화 예시
Go SDK를 사용한 Dapr 대화 예시
Rust SDK를 사용한 Dapr 대화 예시
다음 단계
- Conversation quickstart
- Conversation API 참조 가이드
- 사용 가능한 대화 컴포넌트