-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExample-3-8-functioncalling dashscope.py
More file actions
148 lines (125 loc) · 4.23 KB
/
Copy pathExample-3-8-functioncalling dashscope.py
File metadata and controls
148 lines (125 loc) · 4.23 KB
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# Simple example of function calling using dashscope to get weather information
import json
import os
from dotenv import load_dotenv
import dashscope
from dashscope.api_entities.dashscope_response import Role
# Load environment variables
load_dotenv()
# Get API key from environment variables
dashscope.api_key = os.getenv('BL_API_KEY')
def get_current_weather(location, unit="celsius"):
"""
Get weather information for specified location
Args:
location (str): Location name
unit (str): Temperature unit, default is celsius
Returns:
str: Weather information in JSON format
"""
temperature = -1
if '大连' in location or 'Dalian' in location:
temperature = 10
if location == '上海':
temperature = 36
if location == '深圳':
temperature = 37
weather_info = {
"location": location,
"temperature": temperature,
"unit": unit,
"forecast": ["Sunny", "Light breeze"],
}
return json.dumps(weather_info, ensure_ascii=False)
def get_response(messages):
"""
Get response from Qwen model
Args:
messages (list): Message list containing conversation history
Returns:
dashscope.Generation.Response: Model response object
"""
try:
response = dashscope.Generation.call(
model='qwen-turbo',
messages=messages,
functions=functions,
result_format='message'
)
return response
except Exception as e:
print(f"API call error: {str(e)}")
return None
def run_conversation(query):
"""
Run conversation flow, handle weather queries
Args:
query (str): User's query text
Returns:
dict: Final conversation result
"""
messages = [{"role": "user", "content": query}]
# First response
response = get_response(messages)
if not response or not response.output:
print("Failed to get response")
return None
message = response.output.choices[0].message
messages.append(message)
# Handle function call
if hasattr(message, 'function_call') and message.function_call:
function_call = message.function_call
tool_name = function_call['name']
arguments = json.loads(function_call['arguments'])
# Execute weather query function
tool_response = get_current_weather(
location=arguments.get('location'),
unit=arguments.get('unit'),
)
# Add function call result to conversation history
tool_info = {"role": "function", "name": tool_name, "content": tool_response}
messages.append(tool_info)
# Get second response
response = get_response(messages)
if not response or not response.output:
print("Failed to get second response")
return None
message = response.output.choices[0].message
return message
return message
# Define available functions
functions = [
{
'name': 'get_current_weather',
'description': 'Get current weather information for specified location',
'parameters': {
'type': 'object',
'properties': {
'location': {
'type': 'string',
'description': 'City name, e.g.: Dalian, Shanghai, Shenzhen'
},
'unit': {
'type': 'string',
'enum': ['celsius', 'fahrenheit'],
'description': 'Temperature unit'
}
},
'required': ['location']
}
}
]
if __name__ == "__main__":
# Test examples
test_queries = [
"大连的天气怎样",
"上海现在天气如何",
"深圳今天天气怎么样"
]
for query in test_queries:
print(f"\nQuery: {query}")
result = run_conversation(query)
if result:
print(f"Result: {result.content}")
else:
print("Query failed")