Todos los productos
Search
Centro de documentos

Alibaba Cloud Model Studio:Reconocimiento de intención

Última actualización: Oct 12, 2026

Identifica las intenciones del usuario en milisegundos y selecciona las herramientas adecuadas para atender las consultas.

ImportanteSolo región China (Pekín). Utilice una clave de API de China (Pekín).

ImportanteAlibaba Cloud Model Studio ha lanzado dominios específicos de espacio de trabajo para las regiones de China (Pekín), Singapore y China (Hong Kong). Los nuevos dominios dedicados ofrecen un rendimiento superior y una mayor estabilidad para las solicitudes de inferencia. Recomendamos migrar a los nuevos dominios:

  • China (Pekín): de https://dashscope.aliyuncs.com a https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com
  • Singapur: de https://dashscope-intl.aliyuncs.com a https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com
  • China (Hong Kong): de https://cn-hongkong.dashscope.aliyuncs.com a https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com

{WorkspaceId} es su ID de espacio de trabajo, que se encuentra en la página Workspace Details de la consola de Alibaba Cloud Model Studio. El dominio existente permanece totalmente funcional.

Modelos admitidos

Modelo

Ventana de contexto

Entrada máxima

Salida máxima

Precio de entrada

Precio de salida

(tokens)

(por 1M tokens)

tongyi-intent-detect-v3

8,192

8,192

1,024

$0.058

$0.144

Uso

Requisitos previos

Obtenga una clave de API y exporte la clave de API como variable de entorno. Si utiliza el SDK de OpenAI o el SDK de DashScope para realizar llamadas, instale el SDK.

Generar tanto información de intención como de llamada de función

Para devolver tanto información de intención como de llamada de función, configure el mensaje del sistema de la siguiente manera:

You are Qwen, created by Alibaba Cloud. You are a helpful assistant. You may call one or more tools to assist with the user query. The tools you can use are as follows:
{Tool information}
Response in INTENT_MODE.

Incluya Response in INTENT_MODE. en el mensaje del sistema y especifique las herramientas disponibles. El formato de la información de la herramienta es el siguiente:

[{
    "name": "Name of tool 1",
    "description": "Description of tool 1",
    "parameters": {
        "type": "The type of the parameter, typically object",
        "properties": {
            "parameter_1": {
                "description": "Description of parameter_1",
                "type": "Type of parameter_1",
                "default": "Default value of parameter_1"
            },
            ...
            "parameter_n": {
                "description": "Description of parameter_n",
                "type": "Type of parameter_n",
                "default": "Default value of parameter_n"
            }
        },
        "required": [
        "parameter_1",
        ...
        "parameter_n"
    ]
    },
},
...
{
    "name": "Name of tool n",
    "description": "Description of tool n",
    "parameters": {
        "type": "The type of the parameter, typically object",
        "properties": {
            "parameter_1": {
                "description": "Description of parameter_1",
                "type": "Type of parameter_1",
                "default": "Default value of parameter_1"
            },
            ...
            "parameter_n": {
                "description": "Description of parameter_n",
                "type": "Type of parameter_n",
                "default": "Default value of parameter_n"
            }
        },
        "required": [
        "parameter_1",
        ...
        "parameter_n"
    ]
    },
}]

Ejemplo con dos herramientas (consulta de hora y consulta de clima):

[
    {
        "name": "get_current_time",
        "description": "This is useful when you want to know the current time.",
        "parameters": {}
    },
    {
        "name": "get_current_weather",
        "description": "This is useful when you want to query the weather of a specified city.",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "A city or district, such as Beijing, Hangzhou, or Yuhang District."
                }
            },
            "required": ["location"]
        }
    }
]

Solicitud de ejemplo

import os
import json
from openai import OpenAI

# Define tools
tools = [
    {
        "name": "get_current_time",
        "description": "This is useful when you want to know the current time.",
        "parameters": {}
    },
    {
        "name": "get_current_weather",
        "description": "This is useful when you want to query the weather of a specified city.",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "A city or district, such as Beijing, Hangzhou, or Yuhang District.",
                }
            },
            "required": ["location"]
        }
    }
]

tools_string = json.dumps(tools,ensure_ascii=False)

system_prompt = f"""You are Qwen, created by Alibaba Cloud. You are a helpful assistant. You may call one or more tools to assist with the user query. The tools you can use are as follows:
{tools_string}
Response in INTENT_MODE."""
client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [
    {'role': 'system', 'content': system_prompt},
    {'role': 'user', 'content': "Weather in Hangzhou"}
    ]
response = client.chat.completions.create(
    model="tongyi-intent-detect-v3",
    messages=messages
)

print(response.choices[0].message.content)
import os
import json
from dashscope import Generation
# The following is the base_url for the Beijing region. Replace WorkspaceId with your actual workspace ID. Configurations vary by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"

# Define tools
tools = [
    {
        "name": "get_current_time",
        "description": "This is useful when you want to know the current time.",
        "parameters": {}
    },
    {
        "name": "get_current_weather",
        "description": "This is useful when you want to query the weather of a specified city.",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "A city or district, such as Beijing, Hangzhou, or Yuhang District.",
                }
            },
            "required": ["location"]
        }
    }
]

tools_string = json.dumps(tools,ensure_ascii=False)

system_prompt = f"""You are Qwen, created by Alibaba Cloud. You are a helpful assistant. You may call one or more tools to assist with the user query. The tools you can use are as follows:
{tools_string}
Response in INTENT_MODE."""

messages = [
    {'role': 'system', 'content': system_prompt},
    {'role': 'user', 'content': "Weather in Hangzhou"}
    ]
response = Generation.call(
    # Replace with your API key if DASHSCOPE_API_KEY is not set: api_key = "sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="tongyi-intent-detect-v3",
    messages=messages,
    result_format="message"
)

print(response.output.choices[0].message.content)

NotaLa CLI de dashscope aún no admite el subcomando understanding. Utilice el SDK de Python:

from dashscope import Understanding
Understanding.call(model='opennlu-v1', sentence='The weather is really nice today', labels='weather, emotion')

ImportanteEl asistente interactivo SDK Expert puede realizar las mismas tareas de desarrollo y solución de problemas mediante lenguaje natural; consulte

DashScope SDK Expert.

Respuesta de ejemplo

<tags>
[function call, json response]
</tags><tool_call>
[{"name": "get_current_weather", "arguments": {"location": "Hangzhou"}}]
</tool_call><content>

</content>

Analice la respuesta utilizando la función parse_text:

import re

def parse_text(text):
    # Define regular expression patterns to match <tags>, <tool_call>, <content>, and their content
    tags_pattern = r'<tags>(.*?)</tags>'
    tool_call_pattern = r'<tool_call>(.*?)</tool_call>'
    content_pattern = r'<content>(.*?)</content>'
    # Use regular expressions to find matching content
    tags_match = re.search(tags_pattern, text, re.DOTALL)
    tool_call_match = re.search(tool_call_pattern, text, re.DOTALL)
    content_match = re.search(content_pattern, text, re.DOTALL)
    # Extract matched content (returns empty string if no match)
    tags = tags_match.group(1).strip() if tags_match else ""
    tool_call = tool_call_match.group(1).strip() if tool_call_match else ""
    content = content_match.group(1).strip() if content_match else ""
    # Store the extracted content in a dictionary
    result = {
      "tags": tags,
      "tool_call": tool_call,
      "content": content
    }
    return result

response = """<tags>
[function call, json response]
</tags><tool_call>
[{"name": "get_current_weather", "arguments": {"location": "Hangzhou"}}]
</tool_call><content>

</content>"""
print(parse_text(response))

La salida es la siguiente:

{
    "tags": "[function call, json response]",
    "tool_call": [
        {
            "name": "get_current_weather",
            "arguments": {
                "location": "Hangzhou"
            }
        }
    ],
    "content": ""
}

Generar solo información de intención

Para devolver únicamente información de intención, configure el mensaje del sistema de la siguiente manera:

You are Qwen, created by Alibaba Cloud. You are a helpful assistant. \nYou should choose one tag from the tag list:\n{intent information}\njust reply with the chosen tag.

El formato de la información de intención es el siguiente:

{
    "Intent 1": "Description of Intent 1",
    "Intent 2": "Description of Intent 2",
    "Intent 3": "Description of Intent 3",
    ...
}

Solicitud de ejemplo

import os
import json
from openai import OpenAI

intent_dict = {
    "play_game": "Play game",
    "email_querycontact": "Email query contact",
    "general_quirky": "quirky",
    "email_addcontact": "Email add contact",
    "takeaway_query": "Takeaway query",
    "recommendation_locations": "Location recommendation",
    "transport_traffic": "Transportation",
    "iot_cleaning": "IoT - vacuum cleaner, cleaner",
    "general_joke": "Joke",
    "lists_query": "Query list/checklist",
    "calendar_remove": "Calendar delete event",
    "transport_taxi": "Taxi, taxi booking",
    "qa_factoid": "Factual Q&A",
    "transport_ticket": "Transportation ticket",
    "play_radio": "Play radio",
    "alarm_set": "Set alarm",
}

intent_string = json.dumps(intent_dict,ensure_ascii=False)

system_prompt = f"""You are Qwen, created by Alibaba Cloud. You are a helpful assistant.
You should choose one tag from the tag list:
{intent_string}
Just reply with the chosen tag."""

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [
    {'role': 'system', 'content': system_prompt},
    {'role': 'user', 'content': "Wake me up at nine on Friday morning"}
    ]
response = client.chat.completions.create(
    model="tongyi-intent-detect-v3",
    messages=messages
)

print(response.choices[0].message.content)
import os
import json
from dashscope import Generation
# The following is the base_url for the Beijing region. Replace WorkspaceId with your actual workspace ID. Configurations vary by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"

intent_dict = {
    "play_game": "Play game",
    "email_querycontact": "Email query contact",
    "general_quirky": "quirky",
    "email_addcontact": "Email add contact",
    "takeaway_query": "Takeaway query",
    "recommendation_locations": "Location recommendation",
    "transport_traffic": "Transportation",
    "iot_cleaning": "IoT - vacuum cleaner, cleaner",
    "general_joke": "Joke",
    "lists_query": "Query list/checklist",
    "calendar_remove": "Calendar delete event",
    "transport_taxi": "Taxi, taxi booking",
    "qa_factoid": "Factual Q&A",
    "transport_ticket": "Transportation ticket",
    "play_radio": "Play radio",
    "alarm_set": "Set alarm",
}

intent_string = json.dumps(intent_dict,ensure_ascii=False)

system_prompt = f"""You are Qwen, created by Alibaba Cloud. You are a helpful assistant.
You should choose one tag from the tag list:
{intent_string}
Just reply with the chosen tag."""

messages = [
    {'role': 'system', 'content': system_prompt},
    {'role': 'user', 'content': "Wake me up at nine on Friday morning"}
    ]
response = Generation.call(
    # Replace with your API key if DASHSCOPE_API_KEY is not set: api_key = "sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="tongyi-intent-detect-v3",
    messages=messages,
    result_format="message"
)

print(response.output.choices[0].message.content)

Respuesta de ejemplo

alarm_set

Mejorar el tiempo de respuesta del reconocimiento de intención

Para mejorar el tiempo de respuesta, utilice letras mayúsculas individuales para las categorías de intención. Esto genera respuestas de un solo token, optimizando la latencia de las llamadas al modelo.

import os
import json
from openai import OpenAI

intent_dict = {
    "A": "Play game",
    "B": "Email query contact",
    "C": "quirky",
    "D": "Email add contact",
    "E": "Takeaway query",
    "F": "Location recommendation",
    "G": "Transportation",
    "H": "IoT - vacuum cleaner, cleaner",
    "I": "Joke",
    "J": "Query list/checklist",
    "K": "Calendar delete event",
    "L": "Taxi, taxi booking",
    "M": "Factual Q&A",
    "N": "Transportation ticket",
    "O": "Play radio",
    "P": "Set alarm",
}

intent_string = json.dumps(intent_dict, ensure_ascii=False)

system_prompt = f"""You are Qwen, created by Alibaba Cloud. You are a helpful assistant.
You should choose one tag from the tag list:
{intent_string}
Just reply with the chosen tag."""

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [
    {"role": "system", "content": system_prompt},
    {"role": "user", "content": "What is the earliest flight from Beijing to Hangzhou?"},
]
response = client.chat.completions.create(
    model="tongyi-intent-detect-v3", messages=messages
)

print(response.choices[0].message.content)
import os
import json
from dashscope import Generation
# The following is the base_url for the Beijing region. Replace WorkspaceId with your actual workspace ID. Configurations vary by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"

intent_dict = {
    "A": "Play game",
    "B": "Email query contact",
    "C": "quirky",
    "D": "Email add contact",
    "E": "Takeaway query",
    "F": "Location recommendation",
    "G": "Transportation",
    "H": "IoT - vacuum cleaner, cleaner",
    "I": "Joke",
    "J": "Query list/checklist",
    "K": "Calendar delete event",
    "L": "Taxi, taxi booking",
    "M": "Factual Q&A",
    "N": "Transportation ticket",
    "O": "Play radio",
    "P": "Set alarm",
}

intent_string = json.dumps(intent_dict, ensure_ascii=False)

system_prompt = f"""You are Qwen, created by Alibaba Cloud. You are a helpful assistant.
You should choose one tag from the tag list:
{intent_string}
Just reply with the chosen tag."""

messages = [
    {"role": "system", "content": system_prompt},
    {"role": "user", "content": "What is the earliest flight from Beijing to Hangzhou?"},
]
response = Generation.call(
    # Replace with your API key if DASHSCOPE_API_KEY is not set: api_key = "sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="tongyi-intent-detect-v3",
    messages=messages,
    result_format="message",
)

print(response.output.choices[0].message.content)

Salida: un resultado de intención de un solo token.

M

Generar solo información de llamada de función

Para devolver únicamente información de llamada de función, configure el mensaje del sistema de la siguiente manera:

You are Qwen, created by Alibaba Cloud. You are a helpful assistant. You may call one or more tools to assist with the user query. The tools you can use are as follows:\n{Tool information}\nResponse in NORMAL_MODE.

El formato de la información de la herramienta es el mismo que en la sección Generar tanto información de intención como de llamada de función.

Solicitud de ejemplo

import os
import json
from openai import OpenAI

# Define tools
tools = [
    {
        "name": "get_current_time",
        "description": "This is useful when you want to know the current time.",
        "parameters": {}
    },
    {
        "name": "get_current_weather",
        "description": "This is useful when you want to query the weather of a specified city.",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "A city or district, such as Beijing, Hangzhou, or Yuhang District.",
                }
            },
            "required": ["location"]
        }
    }
]

tools_string = json.dumps(tools,ensure_ascii=False)

system_prompt = f"""You are Qwen, created by Alibaba Cloud. You are a helpful assistant. You may call one or more tools to assist with the user query. The tools you can use are as follows:
{tools_string}
Response in NORMAL_MODE."""
client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [
    {'role': 'system', 'content': system_prompt},
    {'role': 'user', 'content': "Weather in Hangzhou"}
    ]
response = client.chat.completions.create(
    model="tongyi-intent-detect-v3",
    messages=messages
)

print(response.choices[0].message.content)
import os
import json
from dashscope import Generation
# The following is the base_url for the Beijing region. Replace WorkspaceId with your actual workspace ID. Configurations vary by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"

# Define tools
tools = [
    {
        "name": "get_current_time",
        "description": "This is useful when you want to know the current time.",
        "parameters": {}
    },
    {
        "name": "get_current_weather",
        "description": "This is useful when you want to query the weather of a specified city.",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "A city or district, such as Beijing, Hangzhou, or Yuhang District.",
                }
            },
            "required": ["location"]
        }
    }
]

tools_string = json.dumps(tools,ensure_ascii=False)

system_prompt = f"""You are Qwen, created by Alibaba Cloud. You are a helpful assistant. You may call one or more tools to assist with the user query. The tools you can use are as follows:
{tools_string}
Response in NORMAL_MODE."""

messages = [
    {'role': 'system', 'content': system_prompt},
    {'role': 'user', 'content': "Weather in Hangzhou"}
    ]
response = Generation.call(
    # Replace with your API key if DASHSCOPE_API_KEY is not set: api_key = "sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="tongyi-intent-detect-v3",
    messages=messages,
    result_format="message"
)

print(response.output.choices[0].message.content)

Respuesta de ejemplo

<tool_call>
{"name": "get_current_weather", "arguments": {"location": "Hangzhou"}}
</tool_call>

Después de recibir la respuesta, utilice la función parse_text para analizar la herramienta y la información de parámetros devueltas:

import re

def parse_text(text):
    tool_call_pattern = r'<tool_call>(.*?)</tool_call>'
    # Use regular expressions to find matching content
    tool_call_match = re.search(tool_call_pattern, text, re.DOTALL)
    # Extract matched content (returns empty string if no match)
    tool_call = tool_call_match.group(1).strip() if tool_call_match else ""
    return tool_call

response = """<tool_call>
{"name": "get_current_weather", "arguments": {"location": "Hangzhou"}}
</tool_call>"""
print(parse_text(response))

La salida es la siguiente:

{"name": "get_current_weather", "arguments": {"location": "Hangzhou"}}

Conversaciones de múltiples rondas

Si a una consulta le falta información suficiente, el modelo hace preguntas de seguimiento. Después de recopilar los parámetros necesarios, devuelve la información de la llamada de función.

Generar tanto información de intención como de llamada de función

Solicitud de ejemplo
import os
import json
from openai import OpenAI

# Define tools
tools = [
    {
        "name": "get_current_time",
        "description": "This is useful when you want to know the current time.",
        "parameters": {},
    },
    {
        "name": "get_current_weather",
        "description": "This is useful when you want to query the weather of a specified city.",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "A city or district, such as Beijing, Hangzhou, or Yuhang District.",
                }
            },
            "required": ["location"],
        },
    },
]

tools_string = json.dumps(tools, ensure_ascii=False)

system_prompt = f"""You are Qwen, created by Alibaba Cloud. You are a helpful assistant. You may call one or more tools to assist with the user query. The tools you can use are as follows:
{tools_string}
Response in INTENT_MODE."""
client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [
    {"role": "system", "content": system_prompt},
    # First round question
    {"role": "user", "content": "I want to check the weather"},
]
response = client.chat.completions.create(
    model="tongyi-intent-detect-v3", messages=messages
)

print("Query: I want to check the weather")
print("First-round output:\n")
print(response.choices[0].message.content)
messages.append(response.choices[0].message)
# Second round question
messages.append({"role": "user", "content": "In Hangzhou"})
response = client.chat.completions.create(
    model="tongyi-intent-detect-v3", messages=messages
)
print("\nQuery: In Hangzhou")
print("Second-round output:\n")
print(response.choices[0].message.content)
import os
import json
from dashscope import Generation
# The following is the base_url for the Beijing region. Replace WorkspaceId with your actual workspace ID. Configurations vary by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"

# Define tools
tools = [
    {
        "name": "get_current_time",
        "description": "This is useful when you want to know the current time.",
        "parameters": {},
    },
    {
        "name": "get_current_weather",
        "description": "This is useful when you want to query the weather of a specified city.",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "A city or district, such as Beijing, Hangzhou, or Yuhang District.",
                }
            },
            "required": ["location"],
        },
    },
]

tools_string = json.dumps(tools, ensure_ascii=False)

system_prompt = f"""You are Qwen, created by Alibaba Cloud. You are a helpful assistant. You may call one or more tools to assist with the user query. The tools you can use are as follows:
{tools_string}
Response in INTENT_MODE."""

messages = [
    {"role": "system", "content": system_prompt},
    # First round question
    {"role": "user", "content": "I want to check the weather"},
]
response = Generation.call(
    # Replace with your API key if DASHSCOPE_API_KEY is not set: api_key = "sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="tongyi-intent-detect-v3",
    messages=messages,
    result_format="message",
)
print("Query: I want to check the weather")
print("First-round output:\n")
print(response.output.choices[0].message.content)

messages.append(
    {"role": "assistant", "content": response.output.choices[0].message.content}
)
# Second round question
messages.append({"role": "user", "content": "Hangzhou"})

response = Generation.call(
    # Replace with your API key if DASHSCOPE_API_KEY is not set: api_key = "sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="tongyi-intent-detect-v3",
    messages=messages,
    result_format="message",
)
print("\nQuery: Hangzhou")
print("Second-round output:\n")
print(response.output.choices[0].message.content)
Respuesta de ejemplo
Query: I want to check the weather
First-round output:

<tags>
[weather inquiry]
</tags><tool_call>
[]
</tool_call><content>
OK. Which city's weather would you like to check?
</content>

Query: Hangzhou
Second-round output:

<tags>
[function call, json response]
</tags><tool_call>
[{"name": "get_current_weather", "arguments": {"location": "Hangzhou"}}]
</tool_call><content>

</content>

Generar solo información de llamada de función

Solicitud de ejemplo
import os
import json
from openai import OpenAI

# Define tools
tools = [
    {
        "name": "get_current_time",
        "description": "This is useful when you want to know the current time.",
        "parameters": {},
    },
    {
        "name": "get_current_weather",
        "description": "This is useful when you want to query the weather of a specified city.",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "A city or district, such as Beijing, Hangzhou, or Yuhang District.",
                }
            },
            "required": ["location"],
        },
    },
]

tools_string = json.dumps(tools, ensure_ascii=False)

system_prompt = f"""You are Qwen, created by Alibaba Cloud. You are a helpful assistant. You may call one or more tools to assist with the user query. The tools you can use are as follows:
{tools_string}
Response in NORMAL_MODE."""
client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [
    {"role": "system", "content": system_prompt},
    {"role": "user", "content": "I want to check the weather"},
]
response = client.chat.completions.create(
    model="tongyi-intent-detect-v3", messages=messages
)

messages.append(response.choices[0].message)
print("Query: I want to check the weather")
print("First-round output:\n")
print(response.choices[0].message.content)
messages.append({"role": "user", "content": "Hangzhou"})
response = client.chat.completions.create(
    model="tongyi-intent-detect-v3", messages=messages
)
print("\nQuery: Hangzhou")
print("Second-round output:\n")
print(response.choices[0].message.content)
import os
import json
from dashscope import Generation
# The following is the base_url for the Beijing region. Replace WorkspaceId with your actual workspace ID. Configurations vary by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"

# Define tools
tools = [
    {
        "name": "get_current_time",
        "description": "This is useful when you want to know the current time.",
        "parameters": {},
    },
    {
        "name": "get_current_weather",
        "description": "This is useful when you want to query the weather of a specified city.",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "A city or district, such as Beijing, Hangzhou, or Yuhang District.",
                }
            },
            "required": ["location"],
        },
    },
]

tools_string = json.dumps(tools, ensure_ascii=False)

system_prompt = f"""You are Qwen, created by Alibaba Cloud. You are a helpful assistant. You may call one or more tools to assist with the user query. The tools you can use are as follows:
{tools_string}
Response in NORMAL_MODE."""

messages = [
    {"role": "system", "content": system_prompt},
    {"role": "user", "content": "I want to check the weather"},
]
response = Generation.call(
    # Replace with your API key if DASHSCOPE_API_KEY is not set: api_key = "sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="tongyi-intent-detect-v3",
    messages=messages,
    result_format="message",
)
print("Query: I want to check the weather")
print("First-round output:\n")
print(response.output.choices[0].message.content)
messages.append(
    {"role": "assistant", "content": response.output.choices[0].message.content}
)
messages.append({"role": "user", "content": "Hangzhou"})
response = Generation.call(
    # Replace with your API key if DASHSCOPE_API_KEY is not set: api_key = "sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="tongyi-intent-detect-v3",
    messages=messages,
    result_format="message",
)
print("\nQuery: Hangzhou")
print("Second-round output:\n")
print(response.output.choices[0].message.content)
Respuesta de ejemplo
Query: I want to check the weather
First-round output:

Which city's weather would you like to check?

Query: Hangzhou
Second-round output:

<tool_call>
{"name": "get_current_weather", "arguments": {"location": "Hangzhou"}}
</tool_call>

CLI de dashscope

La CLI de dashscope aún no admite el subcomando understanding. Utilice el SDK de Python:

from dashscope import Understanding
Understanding.call(model='opennlu-v1', sentence='The weather is really nice today', labels='weather, emotion')

ImportanteEl asistente interactivo SDK Expert puede realizar las mismas tareas de desarrollo y solución de problemas mediante lenguaje natural; consulte

DashScope SDK Expert.

Para la tabla completa de regiones, consulte Resumen de URL base.

FAQ

¿Cuál es el número máximo de herramientas que se pueden pasar?

Proporcione no más de 10 herramientas. Exceder este límite puede reducir la precisión de las llamadas a herramientas.