大模型相当于是大脑他需要Function-Call 是给大模型加上手脚才能更大限度的发挥他的能力。本文介绍大模型调用 “计算器” 这个工具完成自然语言计算器的功能。官网地址https://trpc-group.github.io/trpc-agent-go/zh/tool/import(contextfmtlogostrpc.group/trpc-go/trpc-agent-go/agent/llmagenttrpc.group/trpc-go/trpc-agent-go/modeltrpc.group/trpc-go/trpc-agent-go/model/openaitrpc.group/trpc-go/trpc-agent-go/runnertrpc.group/trpc-go/trpc-agent-go/tooltrpc.group/trpc-go/trpc-agent-go/tool/function)funcmain(){os.Setenv(OPENAI_API_KEY,os.Getenv(AI_DEEPSEEK_API_KEY))// 仅测试时使用os.Setenv(OPENAI_BASE_URL,https://api.deepseek.com/v1)// 创建模型modelInstance:openai.New(deepseek-v4-pro)// 创建工具calculatorTool:function.NewFunctionTool(calculator,function.WithName(calculator),function.WithDescription(执行加减乘除。参数a、b 为数值op 取值 add/sub/mul/div返回 result 为计算结果。),)// 启用流式输出genConfig:model.GenerationConfig{Stream:true,}// 创建 Agentagent:llmagent.New(assistant,llmagent.WithModel(modelInstance),llmagent.WithTools([]tool.Tool{calculatorTool}),llmagent.WithGenerationConfig(genConfig),)// 创建 Runnerrunner:runner.NewRunner(calculator-app,agent)// 执行对话ctx:context.Background()events,err:runner.Run(ctx,user-001,session-001,model.NewUserMessage(计算 1003 等于多少),)iferr!nil{log.Fatal(err)}// 处理事件流forevent:rangeevents{ifevent.Objectchat.completion.chunk{fmt.Print(event.Response.Choices[0].Delta.Content)}}// 附带调试信息//for event : range events {// fmt.Printf(Event Object: %s, Error: %v, Response: %v\n, event.Object, event.Error, event.Response)// if event.Object chat.completion.chunk len(event.Response.Choices) 0 {// fmt.Print(event.Response.Choices[0].Delta.Content)// }//}fmt.Println()}funccalculator(ctx context.Context,req calculatorReq)(calculatorRsp,error){varresultfloat64switchreq.Op{caseadd,:resultreq.Areq.Bcasesub,-:resultreq.A-req.Bcasemul,*:resultreq.A*req.Bcasediv,/:resultreq.A/req.B}returncalculatorRsp{Result:result},nil}typecalculatorReqstruct{Afloat64json:aBfloat64json:bOpstringjson:op}typecalculatorRspstruct{Resultfloat64json:result}