This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

互动

通过提示有效使用大型语言模型(LLMs)

1 - 会话概述

会话API功能概述

Dapr的会话API简化了与大型语言模型(LLM)进行大规模、安全、可靠交互的复杂性。无论您是缺乏必要本地SDK的开发者,还是只想专注于LLM交互提示的多语言开发团队,会话API都提供了一个统一的API接口来与底层LLM提供商进行对话。

显示用户应用与Dapr的LLM组件通信流程的图示。

除了启用关键的性能和安全功能(如提示缓存个人信息清理),您还可以将会话API与Dapr的其他功能结合使用,例如:

  • 弹性断路器和重试机制,以应对限制和令牌错误,或
  • 中间件,用于验证与LLM之间的请求

Dapr通过为您的LLM交互提供指标,增强了系统的可观测性。

功能

以下功能适用于所有支持的会话组件

提示缓存

提示缓存通过存储和重用在多个API调用中经常重复的提示来优化性能。Dapr将这些频繁使用的提示存储在本地缓存中,从而显著减少延迟和成本,使您的集群、pod或其他组件可以重用,而无需为每个新请求重新处理信息。

个人信息清理

个人信息清理功能能够识别并删除会话响应中的任何形式的敏感用户信息。只需在输入和输出数据上启用此功能,即可保护您的隐私,清除可能用于识别个人的敏感细节。

演示

观看在Diagrid的Dapr v1.15庆祝活动中展示的演示,了解会话API如何使用.NET SDK工作。

试用会话

快速入门和教程

想要测试Dapr会话API?通过以下快速入门和教程来查看其实际应用:

快速入门/教程 描述
会话快速入门 TODO

直接在您的应用中开始使用会话API

想跳过快速入门?没问题。您可以直接在您的应用中试用会话模块。在Dapr安装完成后,您可以从操作指南开始使用会话API。

下一步

2 - 操作指南:使用 conversation API 与 LLM 对话

学习如何简化与大型语言模型交互的复杂性

让我们开始使用 conversation API。在本指南中,您将学习如何:

  • 配置一个可用的 Dapr 组件(echo),以便与 conversation API 搭配使用。
  • 将 conversation 客户端集成到您的应用程序中。
  • 使用 dapr run 启动连接。

配置 conversation 组件

创建一个名为 conversation.yaml 的新配置文件,并将其保存到应用程序目录中的组件或配置子文件夹中。

为您的 conversation.yaml 文件选择 合适的 conversation 组件规范

在这个场景中,我们使用一个简单的 echo 组件。

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: echo
spec:
  type: conversation.echo
  version: v1

集成 conversation 客户端

以下示例使用 HTTP 客户端向 Dapr 的 sidecar HTTP 端点发送 POST 请求。您也可以使用 Dapr SDK 客户端

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("Received the following from the LLM:");
foreach (var resp in response.Outputs)
{
    Console.WriteLine($"\t{resp.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{
		Message: "Please write a witty haiku about the Dapr distributed programming framework at dapr.io",
		// Role:     nil, // Optional
		// ScrubPII: nil, // Optional
	}

	fmt.Printf("conversation input: %s\n", input.Message)

	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.message);

    let response = client.converse_alpha1(request).await?;

    println!("conversation output: {:?}", response.outputs[0].result);
    Ok(())
}

启动 conversation 连接

使用 dapr run 命令启动连接。例如,在这个场景中,我们在一个应用程序上运行 dapr run,其应用程序 ID 为 conversation,并指向 ./config 目录中的 conversation YAML 文件。

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 -- go run ./main.go

预期输出

  - '== APP == conversation output: Please write a witty haiku about the Dapr distributed programming framework at dapr.io'
dapr run --app-id=conversation --resources-path ./config --dapr-grpc-port 3500 -- cargo run --example conversation

预期输出

  - 'conversation input: hello world'
  - 'conversation output: hello world'

相关链接

尝试使用支持的 SDK 仓库中提供的完整示例来体验 conversation API。

下一步