-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.go
106 lines (90 loc) · 2.51 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"context"
"fmt"
"os"
"github.com/devinyf/dashscopego"
"github.com/devinyf/dashscopego/qwen"
)
// 定义工具 tools.
// nolint:all
var tools = []qwen.Tool{
{
Type: "function",
Function: qwen.ToolFunction{
Name: "get_current_weather",
Description: "当你想查询指定城市的天气时非常有用。",
Parameters: qwen.ToolCallParameter{
Type: "object",
Properties: map[string]qwen.PropertieDefinition{
"location": {
Type: "string",
Description: "城市名称",
},
},
},
Required: []string{"location"},
},
},
}
// 定义工具调用的函数. e.g. 天气查询.
func getCurrentWeather(cityName string) string {
return fmt.Sprintf("%v今天有钞票雨。 ", cityName)
}
func main() {
model := qwen.QwenTurbo
token := os.Getenv("DASHSCOPE_API_KEY")
if token == "" {
panic("token is empty")
}
cli := dashscopego.NewTongyiClient(model, token)
content := qwen.TextContent{Text: "青岛今天的天气怎么样?"}
messageHistory := []dashscopego.TextMessage{
{Role: qwen.RoleUser, Content: &content},
}
NEXT_ROUND:
input := dashscopego.TextInput{
Messages: messageHistory,
}
req := &dashscopego.TextRequest{
Input: input,
Tools: tools,
// StreamingFn: // function_call 目前好像还不支持streaming模式.
}
ctx := context.TODO()
resp, err := cli.CreateCompletion(ctx, req)
if err != nil {
panic(err)
}
// 判断是否需要调用工具
if resp.HasToolCallInput() {
// 使用 tools.
toolCalls := *resp.Output.Choices[0].Message.ToolCalls
for _, toolCall := range toolCalls {
fnName := toolCall.Function.Name
if fnName == "get_current_weather" {
argMap := toolCall.Function.GetArguments()
cityName := argMap["properties"]["location"]
toolAnswer := getCurrentWeather(cityName)
// fmt.Println("tool answer: ", tool_answer)
toolMessage := dashscopego.TextMessage{
Role: qwen.RoleTool,
Content: &qwen.TextContent{
Text: toolAnswer,
},
Name: &fnName,
}
// 添加 assistant 的回答到消息记录(如果漏填接口会报错)
assistantOutput := resp.Output.Choices[0].Message
messageHistory = append(messageHistory, assistantOutput)
// 添加 tool 的回答
messageHistory = append(messageHistory, toolMessage)
// 继续下一轮对话
goto NEXT_ROUND
}
}
}
// Final result
fmt.Println("\nnon-stream Final Result: ") // nolint:all
fmt.Println(resp.Output.Choices[0].Message.Content.ToString()) // nolint:all
}