构建一个简单的聊天应用
在本教程中,你将使用LangChainGo构建一个基本的聊天应用程序。该应用程序将演示核心概念,如LLM集成、对话记忆和基本提示模板。
先决条件
- Go 1.21+
- OpenAI API密钥
- 基础的Go编程知识
步骤 1:项目设置
为你的聊天应用创建一个新的Go模块:
mkdir langchain-chat-app
cd langchain-chat-app
go mod init chat-app
添加LangChainGo作为依赖项:
go get github.com/tmc/langchaingo
步骤 2:基本聊天实现
在main.go
中创建一个基本的聊天循环:
package main
import (
"bufio"
"context"
"fmt"
"log"
"os"
"strings"
"github.com/tmc/langchaingo/llms"
"github.com/tmc/langchaingo/llms/openai"
"github.com/tmc/langchaingo/memory"
)
func main() {
// 初始化LLM
llm, err := openai.New()
if err != nil {
log.Fatal(err)
}
// 创建对话记忆
chatMemory := memory.NewConversationBuffer()
fmt.Println("聊天应用启动!输入'quit'退出。")
scanner := bufio.NewScanner(os.Stdin)
ctx := context.Background()
for {
fmt.Print("你: ")
if !scanner.Scan() {
break
}
input := strings.TrimSpace(scanner.Text())
if input == "quit" {
break
}
// 获取LLM的响应
response, err := llm.GenerateContent(ctx, []llms.MessageContent{
llms.TextParts(llms.ChatMessageTypeHuman, input),
})
if err != nil {
fmt.Printf("错误: %v\n", err)
continue
}
aiResponse := response.Choices[0].Content
fmt.Printf("AI: %s\n\n", aiResponse)
// 将对话存储在记忆中
chatMemory.ChatHistory.AddUserMessage(ctx, input)
chatMemory.ChatHistory.AddAIMessage(ctx, aiResponse)
}
}
步骤 3:环境变量设置
设置你的OpenAI API密钥:
export OPENAI_API_KEY="your-api-key-here"
步骤 4:运行聊天应用
go run main.go
你应该会看到:
聊天应用启动!输入'quit'退出。
你: Hello!
AI: Hello! 我能帮你什么?
你: quit
步骤 5:使用对话记忆增强聊天功能
让我们改进聊天应用程序以使用对话记忆:
package main
import (
"bufio"
"context"
"fmt"
"log"
"os"
"strings"
"github.com/tmc/langchaingo/chains"
"github.com/tmc/langchaingo/llms/openai"
"github.com/tmc/langchaingo/memory"
)
func main() {
// 初始化LLM
llm, err := openai.New()
if err != nil {
log.Fatal(err)
}
// 创建对话记忆
chatMemory := memory.NewConversationBuffer()
// 创建对话链
chain := chains.NewConversationChain(llm, chatMemory)
fmt.Println("增强版聊天应用启动!输入'quit'退出。")
scanner := bufio.NewScanner(os.Stdin)
ctx := context.Background()
for {
fmt.Print("你: ")
if !scanner.Scan() {
break
}
input := strings.TrimSpace(scanner.Text())
if input == "quit" {
break
}
// 使用链进行有状态对话
result, err := chains.Run(ctx, chain, input)
if err != nil {
fmt.Printf("错误: %v\n", err)
continue
}
fmt.Printf("AI: %s\n\n", result)
}
}
步骤 6:添加自定义提示模板
创建一个更复杂的聊天体验,使用自定义提示:
package main
import (
"bufio"
"context"
"fmt"
"log"
"os"
"strings"
"github.com/tmc/langchaingo/chains"
"github.com/tmc/langchaingo/llms/openai"
"github.com/tmc/langchaingo/memory"
"github.com/tmc/langchaingo/prompts"
)
func main() {
// 初始化LLM
llm, err := openai.New()
if err != nil {
log.Fatal(err)
}
// 创建对话记忆
chatMemory := memory.NewConversationBuffer()
// 创建自定义提示模板
template := `你是一个乐于助人的AI助手。你在与人类进行对话。
当前对话:
{history}