Skip to main content
Mais Modelos

Intent recognition

Identifica as intenções do usuário em milissegundos e seleciona as ferramentas adequadas para atender às consultas.

China (Beijing) região apenas. Use uma chave de API da China (Beijing).
O Model Studio lançou domínios específicos por workspace para as regiões China (Beijing), Singapura e China (Hong Kong). Os novos domínios dedicados oferecem desempenho superior e maior estabilidade para solicitações de inferência. Recomendamos a migração para os novos domínios:
  • China (Beijing): de https://dashscope.aliyuncs.com para https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com
  • Singapura: de https://dashscope-intl.aliyuncs.com para https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com
  • China (Hong Kong): de https://cn-hongkong.dashscope.aliyuncs.com para https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com
{WorkspaceId} é o ID do seu workspace, disponível na página Workspace Details no console do Model Studio. O domínio existente permanece totalmente funcional.

Modelos compatíveis

Model

Context window

Max input

Max output

Input price

Output price

(tokens)

(per 1M tokens)

tongyi-intent-detect-v3

8.192

8.192

1.024

$0,058

$0,144

Uso

Pré-requisitos

Obtenha uma chave de API e exporte a chave de API como uma variável de ambiente. Caso utilize o OpenAI SDK ou DashScope SDK para fazer chamadas, instale o SDK.

Retornar informações de intenção e chamada de função

Para retornar tanto a intenção quanto as informações de chamada de função, defina a mensagem do sistema conforme abaixo:
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.
Inclua Response in INTENT_MODE. na mensagem do sistema e especifique as ferramentas disponíveis. O formato das informações da ferramenta é o seguinte:
[{
    "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"
    ]
    },
}]
Exemplo com duas ferramentas (consulta de hora e 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"]
        }
    }
]

Solicitação de exemplo

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)

Resposta de exemplo

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

</content>
Analise a resposta usando a função 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))
A saída é a seguinte:
{
    "tags": "[function call, json response]",
    "tool_call": [
        {
            "name": "get_current_weather",
            "arguments": {
                "location": "Hangzhou"
            }
        }
    ],
    "content": ""
}

Retornar apenas informações de intenção

Para retornar apenas as informações de intenção, defina a mensagem do sistema conforme abaixo:
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.
O formato das informações de intenção é o seguinte:
{
    "Intent 1": "Description of Intent 1",
    "Intent 2": "Description of Intent 2",
    "Intent 3": "Description of Intent 3",
    ...
}

Solicitação de exemplo

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)

Resposta de exemplo

alarm_set

Melhorar o tempo de resposta do reconhecimento de intenção

Para melhorar o tempo de resposta, use letras maiúsculas únicas para as categorias de intenção. Isso gera respostas de token único, otimizando a latência da chamada do 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)
Saída: um resultado de intenção com token único.
M

Retornar apenas informações de chamada de função

Para retornar apenas as informações de chamada de função, defina a mensagem do sistema conforme abaixo:
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.
O formato das informações da ferramenta é o mesmo descrito na seção Retornar informações de intenção e chamada de função.

Solicitação de exemplo

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)

Resposta de exemplo

<tool_call>
{"name": "get_current_weather", "arguments": {"location": "Hangzhou"}}
</tool_call>
Após receber a resposta, use a função parse_text para analisar a ferramenta retornada e as informações de parâmetro:
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))
A saída é a seguinte:
{"name": "get_current_weather", "arguments": {"location": "Hangzhou"}}

Conversas de múltiplas rodadas

Se uma consulta não tiver informações suficientes, o modelo fará perguntas de acompanhamento. Após coletar os parâmetros necessários, ele retorna as informações de chamada de função.
  • Output both intent and function call information
  • Output only function call information
Solicitação de exemplo
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)
Resposta de exemplo
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>

FAQ

Qual é o número máximo de ferramentas que podem ser passadas?

Forneça no máximo 10 ferramentas. Exceder esse limite pode reduzir a precisão das chamadas de ferramenta.
Referência da API de Geração de Texto
Geração de Imagens
  • FAQ
Geração de Vídeo
Áudio
API em tempo real
Incorporação de Texto
Produção de Modelos