golang语言模型应用开发框架插件库langchaingo的使用

🦜️🔗 LangChain Go - Golang语言模型应用开发框架插件库

简介

LangChain Go是LangChain的Go语言实现版本,它通过组合性帮助开发者构建基于大型语言模型(LLM)的应用程序。

快速开始示例

以下是一个使用LangChain Go与OpenAI交互的完整示例:

package main

import (
  "context"
  "fmt"
  "log"

  "github.com/tmc/langchaingo/llms"
  "github.com/tmc/langchaingo/llms/openai"
)

func main() {
  // 创建上下文
  ctx := context.Background()
  
  // 初始化OpenAI LLM
  llm, err := openai.New()
  if err != nil {
    log.Fatal(err)
  }
  
  // 设置提示词
  prompt := "What would be a good company name for a company that makes colorful socks?"
  
  // 生成响应
  completion, err := llms.GenerateFromSinglePrompt(ctx, llm, prompt)
  if err != nil {
    log.Fatal(err)
  }
  
  // 输出结果
  fmt.Println(completion)
}

运行结果示例:

$ go run .
Socktastic

核心功能

LangChain Go提供了以下主要功能:

  1. 支持多种LLM提供商(如OpenAI)
  2. 提示模板管理
  3. 链式调用组合
  4. 记忆功能
  5. 文档加载和检索

进阶使用

LangChain Go还支持更复杂的用例,如:

  • 使用本地运行的Ollama模型
  • 集成Google的Gemini模型
  • 构建聊天机器人应用
  • 文档问答系统

社区资源

开发者可以加入Discord社区获取支持和参与讨论。以下是一些有用的博客文章:

  • 在Go中使用LangChainGo与Gemini模型
  • 在LangChainGo中使用Ollama
  • 用Go创建简单的ChatGPT克隆
  • 用Go创建可在笔记本电脑上运行的ChatGPT克隆

贡献者

LangChain Go正在向更社区化的方向发展,如果你有兴趣成为维护者或贡献者,请加入Discord社区并告知我们。


更多关于golang语言模型应用开发框架插件库langchaingo的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang语言模型应用开发框架插件库langchaingo的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


LangChainGo 使用指南

LangChainGo 是 Go 语言的 LangChain 实现,它提供了构建基于语言模型应用的框架和工具集。下面我将介绍 LangChainGo 的核心功能和使用方法。

安装

首先安装 LangChainGo 库:

go get github.com/tmc/langchaingo

核心组件

1. LLM (大语言模型) 集成

LangChainGo 支持多种 LLM 提供者:

import (
	"context"
	"fmt"
	"github.com/tmc/langchaingo/llms"
	"github.com/tmc/langchaingo/llms/openai"
)

func main() {
	// 创建 OpenAI 客户端
	llm, err := openai.New()
	if err != nil {
		panic(err)
	}

	// 调用模型
	ctx := context.Background()
	completion, err := llm.Call(ctx, "讲一个关于人工智能的短故事")
	if err != nil {
		panic(err)
	}

	fmt.Println(completion)
}

2. 提示模板 (Prompt Templates)

import "github.com/tmc/langchaingo/prompts"

func promptExample() {
	template := "你是一个专业的{role},请用{style}风格回答以下问题:{question}"
	prompt := prompts.NewPromptTemplate(template, []string{"role", "style", "question"})

	result, _ := prompt.Format(map[string]interface{}{
		"role":    "医生",
		"style":   "通俗易懂",
		"question": "如何预防感冒?",
	})

	fmt.Println(result)
	// 输出: 你是一个专业的医生,请用通俗易懂风格回答以下问题:如何预防感冒?
}

3. 链 (Chains)

链允许你将多个组件组合在一起:

import (
	"github.com/tmc/langchaingo/chains"
	"github.com/tmc/langchaingo/llms/openai"
)

func chainExample() {
	llm, _ := openai.New()
	
	// 创建简单的LLM链
	chain := chains.NewLLMChain(llm, prompts.NewPromptTemplate(
		"将以下文本翻译成{language}: {text}",
		[]string{"language", "text"},
	))

	ctx := context.Background()
	out, _ := chains.Run(ctx, chain, map[string]interface{}{
		"language": "英语",
		"text":     "今天天气真好",
	})

	fmt.Println(out)
}

4. 记忆 (Memory)

为对话添加记忆功能:

import "github.com/tmc/langchaingo/memory"

func memoryExample() {
	llm, _ := openai.New()
	
	// 创建带记忆的对话链
	conversation := chains.NewConversation(llm, memory.NewConversationBuffer())
	
	ctx := context.Background()
	_, _ = chains.Run(ctx, conversation, "你好,我叫小明")
	response, _ := chains.Run(ctx, conversation, "我的名字是什么?")
	
	fmt.Println(response) // 会回答"你的名字是小明"
}

5. 文档加载和向量存储

import (
	"github.com/tmc/langchaingo/documentloaders"
	"github.com/tmc/langchaingo/textsplitter"
	"github.com/tmc/langchaingo/vectorstores"
	"github.com/tmc/langchaingo/embeddings"
	"github.com/tmc/langchaingo/llms/openai"
)

func vectorStoreExample() {
	// 创建嵌入模型
	llm, _ := openai.New()
	embedder, _ := embeddings.NewEmbedder(llm)
	
	// 加载文档
	loader := documentloaders.NewText("example.txt")
	docs, _ := loader.Load()
	
	// 分割文本
	splitter := textsplitter.NewRecursiveCharacter()
	splits, _ := splitter.SplitDocuments(docs)
	
	// 创建向量存储
	store, _ := vectorstores.NewPinecone(
		context.Background(),
		vectorstores.WithEmbedder(embedder),
		vectorstores.WithIndexName("my-index"),
		vectorstores.WithEnvironment("us-west1-gcp"),
		vectorstores.WithProjectName("my-project"),
		vectorstores.WithAPIKey("pinecone-api-key"),
	)
	
	// 添加文档到向量存储
	_, _ = store.AddDocuments(context.Background(), splits)
	
	// 相似性搜索
	results, _ := store.SimilaritySearch(context.Background(), "搜索查询", 5)
	for _, doc := range results {
		fmt.Println(doc.PageContent)
	}
}

高级用法

自定义链

import (
	"github.com/tmc/langchaingo/schema"
)

type CustomChain struct {}

func (c *CustomChain) Call(ctx context.Context, inputs map[string]interface{}, opts ...chains.ChainCallOption) (map[string]interface{}, error) {
	// 自定义处理逻辑
	text := inputs["text"].(string)
	return map[string]interface{}{
		"result": "处理后的: " + text,
	}, nil
}

func (c *CustomChain) GetMemory() schema.Memory { return nil }
func (c *CustomChain) GetInputKeys() []string  { return []string{"text"} }
func (c *CustomChain) GetOutputKeys() []string { return []string{"result"} }

代理 (Agents)

import (
	"github.com/tmc/langchaingo/agents"
	"github.com/tmc/langchaingo/tools"
)

func agentExample() {
	llm, _ := openai.New()
	
	// 创建工具集
	calculator := tools.Calculator{}
	toolSet := []tools.Tool{calculator}
	
	// 创建代理
	executor, _ := agents.Initialize(
		llm,
		toolSet,
		agents.ZeroShotReactDescription,
	)
	
	ctx := context.Background()
	response, _ := executor.Run(ctx, "计算3的平方是多少?")
	fmt.Println(response)
}

最佳实践

  1. 错误处理:所有 LangChainGo 操作都可能返回错误,务必处理
  2. 上下文传递:使用 context.Context 控制超时和取消
  3. 资源清理:某些组件需要关闭或清理,如向量存储连接
  4. 配置管理:将 API 密钥等敏感信息放在环境变量中

LangChainGo 为 Go 开发者提供了构建基于语言模型应用的强大工具集,通过组合各种组件,你可以快速开发出复杂的 AI 应用。

回到顶部