
LangChain Go 接入百度 ERNIE 大模型实现 Function Calling 完整指南【免费下载链接】langchaingoLangChain for Go, the easiest way to write LLM-based programs in Go项目地址: https://gitcode.com/GitHub_Trending/la/langchaingo本文以 examples/ernie-function-call-example 为例讲解如何在 LangChain for Go 项目中初始化百度 ERNIEEnhanced Representation through kNowledge IntEgration大模型并通过标准函数调用Function Calling能力让模型在回答天气查询等场景时主动请求调用自定义函数。读完本文你将掌握 ERNIE 模型的两类认证方式、函数定义JSON Schema的写法、请求携带函数的调用链以及如何从响应中提取模型发起的函数调用并能在真实项目中复刻这一模式。ERNIE 模型与函数调用示例在做什么示例 ernie_function_call_example.go 展示了 LangChain Go 中 ERNIE 函数调用的完整闭环核心流程共五步初始化 ERNIE 模型通过ernie.New配置模型名称与认证信息AK/SK 或 Access Token定义天气函数实现一个getCurrentWeather(location, unit)函数用模拟数据返回指定地点的天气 JSON注册函数定义用llms.FunctionDefinition声明函数的名称、描述和参数结构JSON Schema交给模型携带函数发起请求向模型发送 What is the weather like in Boston?并通过llms.WithFunctions注入函数能力处理响应判断resp.Choices[0].FuncCall是否非空若模型决定调用函数则打印调用详情。这种模型决策 → 应用执行 → 结果回填的模式让 LLM 能够访问实时数据、外部 API 或内部业务逻辑是构建 Agent 与工具调用类应用的基础能力。环境准备与依赖示例目录 go.mod 声明了独立模块关键依赖如下module github.com/tmc/langchaingo/examples/ernie-function-call-example go 1.24.3 require github.com/tmc/langchaingo v0.1.14-pre.4运行前你需要安装 Go 1.24 工具链在百度智能云千帆平台开通 ERNIE 系列模型服务获取 API Key 与 Secret KeyAK/SK在项目根目录执行go run ernie_function_call_example.go即可运行示例若仓库中其余示例依赖完整亦可用go mod tidy整理依赖。初始化 ERNIE 模型三种认证方式ernie.New是模型入口实现在 llms/ernie/erniellm.go。它先读取环境变量ERNIE_API_KEY与ERNIE_SECRET_KEY作为默认认证再叠加传入的 Option。方式一AK/SK生产环境推荐llm, err : ernie.New( ernie.WithModelName(ernie.ModelNameERNIEBot), ernie.WithAKSK(ak, sk), ) if err ! nil { log.Fatal(err) }WithAKSK(apiKey, secretKey)定义在 llms/ernie/erniellm_option.go。传入 AK/SK 后客户端会自动调用百度 OAuth 接口换取 access token并通过后台 goroutine 每 10 天自动刷新一次token 有效期为 30 天相关实现见 llms/ernie/internal/ernieclient/ernieclient.go因此生产环境无需关心 token 过期问题。方式二直接传入 Access Token开发环境llm, err : ernie.New( ernie.WithModelName(ernie.ModelNameERNIEBot), ernie.WithAccessToken(accesstoken), )WithAccessToken的注释明确说明通常用于开发调试生产环境推荐使用WithAKSK见 llms/ernie/erniellm_option.go。方式三环境变量不传任何认证 Option 时New会从环境变量读取export ERNIE_API_KEY{API Key} export ERNIE_SECRET_KEY{Secret Key}若 accessToken、apiKey、secretKey 三者都为空newClient会返回明确的引导性错误见 llms/ernie/erniellm.go。可用的模型名称ModelName常量定义在 llms/ernie/erniellm_option.go示例中使用的ernie.ModelNameERNIEBot即 ERNIE-Bot会映射到completions请求路径。完整映射表见 llms/ernie/erniellm.go模型常量模型字符串请求路径ModelNameERNIEBotERNIE-BotcompletionsModelNameERNIEBotTurboERNIE-Bot-turboeb-instantModelNameERNIEBotProERNIE-Bot-procompletions_proModelNameBloomz7BBLOOMZ-7Bbloomz_7b1ModelNameLlama2_7BChatLlama-2-7b-chatllama_2_7bModelNameLlama2_13BChatLlama-2-13b-chatllama_2_13bModelNameLlama2_70BChatLlama-2-70b-chatllama_2_70b未指定模型时默认使用 ERNIE-BotDefaultCompletionModelPath completions。示例本身刻意同时传入WithAKSK与WithAccessToken注释提示可用外部缓存维护 access token实际使用二选一即可。定义可被模型调用的函数示例中getCurrentWeather是纯模拟实现返回一段 JSON 字符串func getCurrentWeather(location string, unit string) (string, error) { weatherInfo : map[string]interface{}{ location: location, temperature: 72, unit: unit, forecast: []string{sunny, windy}, } b, err : json.Marshal(weatherInfo) if err ! nil { return , err } return string(b), nil }真正交给模型的是它的说明书——llms.FunctionDefinition定义于 llms/options.go包含Name、Description、ParametersJSON Schema三个字段。示例中的声明如下var functions []llms.FunctionDefinition{ { Name: getCurrentWeather, Description: Get the current weather in a given location, Parameters: json.RawMessage({type: object, properties: {location: {type: string, description: The city and state, e.g. San Francisco, CA}, unit: {type: string, enum: [celsius, fahrenheit]}}, required: [location]}), }, }这里的 JSON Schema 表达了三层信息函数接收object类型的参数location为必填字符串并给出示例值帮助模型理解格式unit为可选字符串且限定在celsius/fahrenheit枚举内。描述写得越精确模型生成合法参数的命中率越高。底层请求结构ernieclient.FunctionDefinition与响应侧结构保持对应见 llms/ernie/internal/ernieclient/chat.go。携带函数定义发起生成请求请求通过统一的GenerateContent接口发出ctx : context.Background() resp, err : llm.GenerateContent(ctx, []llms.MessageContent{ llms.TextParts(llms.ChatMessageTypeHuman, What is the weather like in Boston?), }, llms.WithFunctions(functions)) if err ! nil { log.Fatal(err) }llms.TextParts(llms.ChatMessageTypeHuman, ...)构造一条人类角色的文本消息llms/generatecontent.go而llms.WithFunctions(functions)负责把函数定义挂到本次调用的CallOptions上llms/options.go。在 ERNIE 客户端侧函数调用请求由CreateChat处理其关键行为位于 llms/ernie/internal/ernieclient/ernieclient.go只要请求携带Functions且未显式指定行为就自动将function_call设为autodefaultFunctionCallBehavior auto即由模型自主决定是否调用函数响应中result与function_call均为空时返回ErrEmptyResponse避免静默失败。请求最终落到百度端点https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/{modelPath}?access_token...URL 拼接见 llms/ernie/internal/ernieclient/ernieclient.go。处理模型返回的函数调用模型可能返回普通文本也可能返回我决定调用 getCurrentWeather的指令。示例的判读逻辑choice1 : resp.Choices[0] if choice1.FuncCall ! nil { fmt.Printf(Function call: %v\n, choice1.FuncCall) }ContentResponse.Choices[0]是*llms.ContentChoice其FuncCall字段在模型请求调用函数时非空llms/generatecontent.go。FuncCall携带Name与ArgumentsJSON 字符串形式的实参。ERNIE 服务端的函数调用响应结构为FunctionCallRes包含三个字段llms/ernie/internal/ernieclient/chat.go字段含义name模型决定调用的函数名thoughts模型的思考过程arguments依据 JSON Schema 生成的函数实参JSON 字符串在真实场景中你应将FuncCall.Name分派到对应业务函数、用FuncCall.Arguments反序列化出实参执行再把结果作为新的对话消息回传给模型继续生成最终答案——示例将getCurrentWeather简化为模拟实现正式使用时替换为真实天气 API 查询逻辑即可。底层链路从 Option 到 HTTP 请求从源码结构可以梳理出函数调用请求的完整传递链llms.WithFunctions将定义写入CallOptions.Functionsllms/options.goernie.LLM.GenerateContent遍历CallOption收集参数并构造ernieclient.CompletionRequestllms/ernie/erniellm.go请求 JSON 序列化后 POST 到带access_token的百度端点响应解码为ChatResponse其中的FunctionCall *FunctionCallRes被映射到llms.ContentChoice.FuncCall供调用方读取。单测用例也印证了这一行为llms/ernie/internal/ernieclient/client_unit_test.go 中 chat with function call 用例构造带Functions的请求、模拟返回function_call负载并断言resp.FunctionCall.Name get_weather且arguments含{location:Beijing}empty response error 用例则验证了空响应兜底逻辑。常见问题与进阶提示认证报错ErrNotSetAuth表示三种认证信息均未提供按 llms/ernie/erniellm.go 的提示配置 AK/SK 或环境变量即可模型切换在ernie.New中改用ernie.WithModelName(ernie.ModelNameERNIEBotTurbo)等常量或通过WithModel(modelName string)llms/ernie/erniellm_option.go按需指定自定义端点与客户端WithBaseURL、WithModelPath、WithHTTPClientllms/ernie/erniellm_option.go可用于代理网关、私有化部署或注入自定义 HTTP 传输层如日志、限流流式函数调用客户端支持流式聊天解析流式分片中携带的function_call会被汇总到最终响应llms/ernie/internal/ernieclient/chat.go函数行为控制ERNIE 侧支持auto与none两种FunctionCallBehaviorllms/ernie/internal/ernieclient/chat.go需要强制禁用函数时可通过llms.WithFunctionCallBehavior(llms.FunctionCallBehaviorNone)显式指定。该示例为开发者提供了模型 工具调用的最小可运行样板把getCurrentWeather换成任意业务函数、把函数定义数组扩成多个工具即可快速搭建基于百度 ERNIE 的 Go Agent 应用。【免费下载链接】langchaingoLangChain for Go, the easiest way to write LLM-based programs in Go项目地址: https://gitcode.com/GitHub_Trending/la/langchaingo创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考