Overview
This topic describes how to build a travel assistant based on Assistant API. The assistant can access various functions and answer travel-related questions. The following example is based on the APIs of mock functions that cover various travel-related questions.
You can replace the mock functions with your actual APIs or override the mock functions based on your requirements.
Features applied
The parameter generation capability of Assistant API.
The function calling capability of Assistant API.
Implement code
After you configure the code of the following files, run tour-assistant.py to test the assistant.
The mock functions support only questions about Lijiang and Beijing.
Prerequisites
Alibaba Cloud Model Studio is activated. For more information, see Activate Alibaba Cloud Model Studio.
An API key is obtained. For more information, see Obtain an API key.
An SDK of the latest version is installed. For more information, see Install the SDK.
Run the following command and replace YOUR_DASHCOPE_API_KEY with your API key.
export DASHSCOPE_API_KEY=YOUR_DASHSCOPE_API_KEYMain function (tour_assistant.py)
# -*- encoding: utf-8 -*-
import json
import sys
from http import HTTPStatus
from dashscope import Assistants, Messages, Runs, Threads
from function_utils import *
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
def create_assistant():
# create assistant with information
assistant = Assistants.create(
model='qwen-max',
name='smart helper',
description='A travel assistant that can query weather conditions, plan routes, and recommend restaurants for users. ',
instructions='You are a travel assistant and can solve problems by calling plug-ins. Your plug-ins include weather query, route planning, and local restaurant recommendation. If you cannot answer a question, call the plug-ins. Enrich your response appropriately based on the results of the plug-ins. ',
tools=[{
'type': 'function',
'function': {
'name': 'Weather query',
'description': 'This plug-in is used to query the weather conditions.',
'parameters': {
'type': 'object',
'properties': {
'location': {
'type': 'str',
'description': 'The location to query.'
},
'date': {
'type': 'str',
'description': 'The date to query.'
}
},
'required': ['location', 'date']
}
}
},
{
'type': 'function',
'function': {
'name': 'Route planning',
'description': 'This plug-in is used to recommend travel routes and plan the path between a specified start point and destination. The plug-in can also recommend recently popular destinations. ',
'parameters': {
'type': 'object',
'properties': {
'start': {
'type': 'str',
'description': 'The start point.'
},
'destination': {
'type': 'str',
'description': 'The destination.'
},
'recommendation': {
'type': 'int',
'description': 'This parameter specifies whether to recommend random destinations. If the destination cannot be determined, set the value to 1. In other cases, set the value to 0 and popular destination are recommended.'
}
},
'required': ['destination', 'start', 'recommendation']
}
}
},
{
'type': 'function',
'function': {
'name': 'Obtain destination recommendation',
'description': 'This plug-in is used to recommend recently popular destinations. ',
'parameters': {
'type': 'object',
'properties': {
'query': {
'type': 'str',
'description': 'Information that may be required'
},
},
'required': ['query']
}
}
},
{
'type': 'function',
'function': {
'name': 'Obtain attraction recommendation',
'description': 'This plug-in is used to recommend popular attractions in a specified city. ',
'parameters': {
'type': 'object',
'properties': {
'city': {
'type': 'str',
'description': 'City name'
},
},
'required': ['city']
}
}
},
{
'type': 'function',
'function': {
'name': 'Obtain dining recommendation',
'description': 'This plug-in is used to recommend dining in a specified city. ',
'parameters': {
'type': 'object',
'properties': {
'city': {
'type': 'str',
'description': 'City name'
},
},
'required': ['city']
}
}
},
{
'type': 'function',
'function': {
'name': 'Obtain travel tips',
'description': 'This plug-in is used to obtain travel tips about a specified city. ',
'parameters': {
'type': 'object',
'properties': {
'city': {
'type': 'str',
'description': 'City name'
},
},
'required': ['city']
}
}
},
{
'type': 'function',
'function': {
'name': 'Obtain local customs',
'description': 'This plug-in is used to obtain information about local customs of a specified city. ',
'parameters': {
'type': 'object',
'properties': {
'city': {
'type': 'str',
'description': 'City name'
},
},
'required': ['city']
}
}
},
],
)
return assistant
function_mapper = {
"Weather query": get_weather,
"Route planning": get_path_recommendation,
"Obtain destination recommendation": get_destination_recommendation,
"Obtain attraction recommendation": get_attraction_recommendation,
"Obtain dining recommendation": get_dining_recommendation,
"Obtain travel tips": get_life_tips,
"Obtain local customs": get_local_customs,
}
def verify_status_code(res):
if res.status_code != HTTPStatus.OK:
sys.exit(res.status_code)
def send_message(assistant, message='Query the weather in Hangzhou'):
print(f"Query: {message}")
# create thread.
# create a thread.
thread = Threads.create()
print(thread)
# create a message.
message = Messages.create(thread.id, content=message)
# create run
run = Runs.create(thread.id, assistant_id=assistant.id)
print(run)
# # get run statue
# run_status = Runs.get(run.id, thread_id=thread.id)
# print(run_status)
# wait for run completed or requires_action
run_status = Runs.wait(run.id, thread_id=thread.id)
# print(run_status)
# if prompt input tool result, submit tool result.
if run_status.required_action:
f = run_status.required_action.submit_tool_outputs.tool_calls[0].function
func_name = f['name']
param = json.loads(f['arguments'])
print(f)
if func_name in function_mapper:
output = function_mapper[func_name](**param)
else:
output = ""
tool_outputs = [{
'output':
output
}]
run = Runs.submit_tool_outputs(run.id,
thread_id=thread.id,
tool_outputs=tool_outputs)
# should wait for run completed
run_status = Runs.wait(run.id, thread_id=thread.id)
# print(run_status)
verify_status_code(run_status)
run_status = Runs.get(run.id, thread_id=thread.id)
print(run_status)
# verify_status_code(run_status)
# get the thread messages.
msgs = Messages.list(thread.id)
# print(msgs)
# print(json.dumps(msgs, default=lambda o: o.__dict__, sort_keys=True, indent=4))
print("Results:")
for message in msgs['data'][::-1]:
print("content: ", message['content'][0]['text']['value'])
print("\n")
if __name__ == '__main__':
assistant = create_assistant()
send_message(assistant=assistant, message="What's the weather like in Lijiang?")
# send_message(assistant=assistant,message="Are there any recommended places to go on vacation?")
# send_message(assistant=assistant,message="How can I travel from Beijing to Lijiang?")
# send_message(assistant=assistant,message="What attractions are there to see in Lijiang?")
# send_message(assistant=assistant,message="What food do you recommend in Lijiang?")
# send_message(assistant=assistant,message="What else should I pay attention to in Lijiang?")
# send_message(assistant=assistant,message="Tell me something about the local customs in Lijiang.")
# send_message(assistant=assistant,message='Travel advice from Hangzhou to Beijing')
Custom functions (function_utils.py)
Multiple custom functions are included in tour_assistant.py. You can modify or add functions based on your needs.
from mocked_information import *
def get_destination_recommendation(query):
return destination
def get_attraction_recommendation(city):
return attraction
def get_dining_recommendation(city):
return dining
def get_life_tips(city):
return life_tips
def get_local_customs(city):
return local_customs
def get_current_date():
return "Today"
def get_weather(location, date=""):
if date == "":
date = get_current_date()
return date + "it is" + "sunny"
def get_current_location():
return "in Beijing"
def get_path_recommendation(destination, start='', recommendation=False):
return "It is recommended to travel from" + start + "to" + destination + "by airplane. \nFlight information: \n" + flight
Mock information (mocked_information.py)
The following file contains the information that is referenced by some of the preceding functions.
destination="""
Here are some recommended destinations:
1. Hangzhou (China)
West Lake: Enjoys the reputation of "paradise on earth" and is one of the most famous natural landscapes in China.
Lingyin Temple: One of the oldest temples in Hangzhou and a place for peaceful spiritual cultivation.
Xixi Wetland: A natural wetland zone that allows close contact with nature and wildlife.
2. Lijiang (China)
Old Town: Boasts well-preserved historical buildings and Naxi culture.
Yulong Snow Mountain: A majestic mountain with spectacular views, offering skiing and mountaineering activities.
Shuhe Ancient Town: A more tranquil place than Lijiang Old Town, suitable for tea tasting and meditation.
3. Paris (France)
The Eiffel Tower: A symbol of France, offering a panoramic view of the city.
Louvre: One of the largest art museums in the world, housing a collection of precious works of art such as the Mona Lisa.
Palace of Versailles: The royal palace and the pinnacle of European gardens and palaces.
4. Cape Town (South Africa)
Table Mountain: Accessed by cable car with stunning views of Cape Town and Robin Island.
Cape of Good Hope: A famous landmark for navigators throughout history.
Kirstenbosch Botanical Garden: One of the most biodiverse botanical gardens in the world.
"""
attraction = """
1. Lijiang Old Town (Dayan Old Town)
Features: The Old Town of Lijiang is a perfectly preserved old Naxi town, famous for its stone-slab roads, flowing water and ancient bridges. No ticket is charged, but a maintenance fee is required.
Suggested time: It is recommended to start your tour in the morning to avoid the crowds.
Tips: The Old Town is particularly charming at night, with plenty of bars and cafés to enjoy.
2. Black Dragon Pool Park
Features: Located to the north of Lijiang Old Town, it is an excellent place to enjoy the reflection of Yulong Snow Mountain.
Suggested time: morning or evening.
Tips: No admission fee. This is a good place to take photos and have a walk.
3. Yulong Snow Mountain
Features: This spectacular snow-capped mountain is an iconic attraction in Lijiang, and you can take a cable car to Glacier Park or Yak Meadow.
Suggested time: All day, but allow enough time to go up and down the mountain.
Tips: High altitude may cause altitude sickness, it is recommended to prepare in advance.
4. Baisha Old Town
Features: Compared with the Old Town of Lijiang, Baisha is more peaceful and retains more of the traditional Naxi culture.
Suggested time: Afternoon.
Tips: You can try to DIY Naxi traditional handicrafts.
5. Shuhe Old Town
Features: Smaller and more peaceful than the Old Town of Lijiang, it is another good place to learn about Naxi culture.
Suggested time: Night.
Tips: The night in Shuhe is more tranquil. It is a great place to have dinner.
"""
dining = """
Dining recommendations
Breakfast: Try the local yogurt and grilled rice cake sold in the alleys of the Lijiang Old Town.
Lunch: Try Tibetan or Naxi-style dishes at a restaurant under the Yulong Snow Mountain.
Dinner: There are many restaurants in the old town of Shuhe that offer authentic Naxi cuisine, especially Naxi grilled fish.
"""
life_tips = """
Travel tips
Clothing: Lijiang has a large temperature difference between day and night, so even in summer, you will need a warm coat.
Altitude sickness: Lijiang has an altitude of about 2400 meters, and some people may experience altitude sickness. It is suggested that you try to adapt to the high-altitude environment upon arriving, take a rest, stay hydrated, and do less strenuous physical activities. Before going to high-altitude areas such as Yulong Snow Mountain, it is recommended to take steps to prevent altitude sickness.
"""
local_customs = """
Naxi etiquette:
The Naxi people are the main ethnic group in Lijiang, and they attach importance to etiquette. When talking with elders, speak politely and avoid looking directly into their eyes, which is a sign of respect.
When visiting a Naxi family or participating in local activities, it is polite to accept food and drink from the host.
Traditional clothing:
Local people may wear traditional clothing for certain festivals or important events. Tourists can rent Naxi clothing for photos, but please be respectful and do not treat the clothing improperly.
Festivals and celebrations:
Sanyue Street is a large market and celebration held in the third month of the lunar calendar every year. To participate in local festivals and temple fairs, tourists should abide by local rules and traditions, such as not making loud noises and not entering the sacrificial area without permission.
"""
flight = """
Flight number Aircraft Departure time Departure airport Arrival time Arrival airport Flight schedule Meal service Ticket price
CA1469 32N 06:30 Capital International Airport T2 10:25 Sanyi Airport Daily 93% Starting from CNY 1730
ZH1469 32N 06:30 Capital International Airport T2 10:25 Sanyi Airport Daily 93% Check current price
JD5181 32Q 06:55 Daxing International Airport 10:15 Sanyi Airport Daily 97% Starting from CNY 630
CA1459 32N 16:20 Capital International Airport T2 20:15 Sanyi Airport Daily 97% Starting from CNY 1150
ZH1459 32N 16:20 Capital International Airport T2 20:15 Sanyi Airport Daily 97% Check current price
3U5234 737 16:55 Daxing International Airport 20:05 Sanyi Airport Daily - Starting from CNY 2860
KN6139 737 16:55 Daxing International Airport 20:05 Sanyi Airport Daily - Check current price
MU5716 737 16:55 Daxing International Airport 20:05 Sanyi Airport Daily - Starting from CNY 900
3U5234 737 17:00 Daxing International Airport 20:05 Sanyi Airport Daily - Starting from CNY 2860
KN6139 737 17:00 Daxing International Airport 20:05 Sanyi Airport Daily - Check current price
MU5716 737 16:55 Daxing International Airport 20:05 Sanyi Airport Daily - Starting from CNY 900
"""
Sample response
In the following example, the input question in tour_assistant.py is changed to "Are there any recommended places to go on vacation?". Then, run tour_assistant.py.
The Obtain destination recommendation function is called and the following response is returned:
Results:
content: Are there any recommended places to go on vacation?
content: Here are some currently popular vacation destinations for your consideration:
1. **Hangzhou, China**
- **West Lake**: Known as "paradise on earth," it's one of China's most renowned natural landscapes.
- **Lingyin Temple**: One of Hangzhou's oldest temples, perfect for a peaceful retreat.
- **Xixi Wetland**: A natural wonder where you can connect with nature and observe wildlife.
2. **Lijiang, China**
- **Lijiang Old Town**: Famed for its preserved ancient architecture and rich Naxi culture.
- **Yulong Snow Mountain**: Offers breathtaking scenery and activities like skiing and hiking.
- **Shuhe Ancient Town**: A serene alternative to Lijiang Old Town, ideal for tea experiences and relaxation.
3. **Paris, France**
- **Eiffel Tower**: The iconic symbol of France providing panoramic city views.
- **Louvre Museum**: Among the world's largest, home to masterpieces like the Mona Lisa.
- **Palace of Versailles**: A royal residence exemplifying the grandeur of European gardens and palaces.
4. **Cape Town, South Africa**
- **Table Mountain**: Accessible by cable car, it showcases stunning vistas of Cape Town and beyond.
- **Cape of Good Hope**: A historic landmark significant to navigators.
- **Kirstenbosch Botanical Garden**: Renowned for its biodiversity and natural beauty.
Each of these destinations offers unique experiences and sights, catering to different interests and preferences. Happy traveling!You can also enable the streaming output mode when you use Assistant APIs. For more information, see Call examples.