A ferramenta de busca por imagem permite que o modelo pesquise na internet imagens visualmente semelhantes com base em uma imagem de entrada. O modelo analisa os resultados da pesquisa e faz inferências. Esse recurso é útil para cenários como encontrar produtos similares ou rastrear a origem de conteúdo visual.
Como usar
Chame o recurso de busca por imagem pela Responses API. Adicione a ferramenta image_search ao parâmetro tools e passe a imagem no parâmetro input em formato multimodal.
O parâmetro
inputdeve conter conteúdo de imagem. Passe a URL da imagem usando o tipoinput_image. Você também pode passar texto usando o tipoinput_textpara fornecer informações adicionais à pesquisa.
# Import dependencies and create a client...
input_content = [
{"type": "input_text", "text": "Find landscape images with a style similar to this one"},
{"type": "input_image", "image_url": "https://img.alicdn.com/imgextra/i4/O1CN01YbrnSS1qtmsAkw0Ud_!!6000000005554-2-tps-788-450.png"}
]
response = client.responses.create(
model="qwen3.8-max",
input=[{"role": "user", "content": input_content}],
tools=[{"type": "image_search"}]
)
print(response.output_text)
Modelos suportados
Modelos recomendados
Para obter o melhor desempenho na chamada de ferramentas, use os seguintes modelos:
Qwen-Plus: série Qwen3.7-Plus, série Qwen3.6-Plus, série Qwen3.5-Plus
Qwen-Max: série Qwen3.8-Max, qwen3.7-max-2026-06-08
qwen3.8-27b
Outros modelos
Os modelos abaixo também oferecem suporte a esta ferramenta, mas apresentam desempenho inferior aos modelos recomendados.
- Qwen-Flash: série Qwen3.7-Flash, série Qwen3.6-Flash, série Qwen3.5-Flash
Este recurso só pode ser chamado pela Responses API.
Primeiros passos
Execute o código a seguir para chamar a ferramenta de busca por imagem pela Responses API e pesquisar imagens semelhantes ou relacionadas com base na imagem de entrada.
Antes de começar, obtenha uma chave de API e configure a chave de API como uma variável de ambiente .
Substitua o valor de
image_urlno código de exemplo por uma URL de imagem publicamente acessível.
import os
import json
from openai import OpenAI
client = OpenAI(
# If you have not configured the environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following URL is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)
input_content = [
{"type": "input_text", "text": "Find landscape images with a style similar to this one"},
# Replace image_url with the actual public URL of the image
{"type": "input_image", "image_url": "https://img.alicdn.com/imgextra/i4/O1CN01YbrnSS1qtmsAkw0Ud_!!6000000005554-2-tps-788-450.png"}
]
response = client.responses.create(
model="qwen3.8-max",
input=[{"role": "user", "content": input_content}],
tools=[
{
"type": "image_search"
}
]
)
# Traverse the output to display each step
for item in response.output:
if item.type == "image_search_call":
print(f"[Tool Call] Search by image (status: {item.status})")
# Parse and display the list of searched images
if item.output:
images = json.loads(item.output)
print(f" Found {len(images)} images:")
for img in images[:5]: # Display the first 5 images
print(f" [{img['index']}] {img['title']}")
print(f" {img['url']}")
if len(images) > 5:
print(f" ... {len(images)} images in total")
elif item.type == "message":
print(f"\n[Model Response]")
print(response.output_text)
# Display token usage and tool call statistics
print(f"\n[Token Usage] Input: {response.usage.input_tokens}, Output: {response.usage.output_tokens}, Total: {response.usage.total_tokens}")
if hasattr(response.usage, 'x_tools') and response.usage.x_tools:
for tool_name, info in response.usage.x_tools.items():
print(f"[Tool Statistics] {tool_name} call count: {info.get('count', 0)}")
import OpenAI from "openai";
import process from 'process';
const openai = new OpenAI({
// If you have not configured the environment variable, replace the following line with your Model Studio API key: apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
// The following URL is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
});
async function main() {
const response = await openai.responses.create({
model: "qwen3.8-max",
input: [
{
role: "user",
content: [
{ type: "input_text", text: "Find landscape images with a style similar to this one" },
// Replace image_url with the actual public URL of the image
{ type: "input_image", image_url: "https://img.alicdn.com/imgextra/i4/O1CN01YbrnSS1qtmsAkw0Ud_!!6000000005554-2-tps-788-450.png" }
]
}
],
tools: [
{ type: "image_search" }
]
});
// Traverse the output to display each step
for (const item of response.output) {
if (item.type === "image_search_call") {
console.log(`[Tool Call] Search by image (status: ${item.status})`);
// Parse and display the list of searched images
if (item.output) {
const images = JSON.parse(item.output);
console.log(` Found ${images.length} images:`);
images.slice(0, 5).forEach(img => {
console.log(` [${img.index}] ${img.title}`);
console.log(` ${img.url}`);
});
if (images.length > 5) {
console.log(` ... ${images.length} images in total`);
}
}
} else if (item.type === "message") {
console.log(`\n[Model Response]`);
console.log(response.output_text);
}
}
// Display token usage and tool call statistics
console.log(`\n[Token Usage] Input: ${response.usage.input_tokens}, Output: ${response.usage.output_tokens}, Total: ${response.usage.total_tokens}`);
if (response.usage && response.usage.x_tools) {
for (const [toolName, info] of Object.entries(response.usage.x_tools)) {
console.log(`[Tool Statistics] ${toolName} call count: ${info.count || 0}`);
}
}
}
main();
# The following URL is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.8-max",
"input": [
{
"role": "user",
"content": [
{"type": "input_text", "text": "Find landscape images with a style similar to this one"},
{"type": "input_image", "image_url": "https://img.alicdn.com/imgextra/i4/O1CN01YbrnSS1qtmsAkw0Ud_!!6000000005554-2-tps-788-450.png"}
]
}
],
"tools": [
{"type": "image_search"}
]
}'
Após executar o código, você receberá uma resposta semelhante à seguinte:
[Tool Call] Search by image (status: completed)
Found 2 images:
[1] QingMing Festival Holiday Notice 2024
https://www.healthcabin.net/blog/wp-content/uploads/2024/04/QingMing-Festival-Holiday-Notice-2024.jpg
[2] Serene Asian Landscape Stone Bridge Reflecting in Misty Water
https://thumbs.dreamstime.com/b/serene-asian-landscape-stone-bridge-reflecting-misty-water-tranquil-illustration-traditional-arch-spanning-lake-style-376972039.jpg
[Model Response]
OK. I have found several landscape images with a similar style.
These images all display the artistic conception of typical Chinese ink wash paintings or traditional landscape paintings, and they share the following common points:
* **Traditional architecture**: such as pavilions, towers, and arch bridges.
* **Natural elements**: such as distant mountains, lakes, weeping willows, and lotus flowers.
* **Artistic style**: uses elegant colors and soft lines to create a quiet and serene atmosphere.
...
[Token Usage] Input: 2753, Output: 181, Total: 2934
[Tool Statistics] image_search call count: 1
Saída em streaming
A ferramenta de busca por imagem tem um tempo de processamento longo. Ative a saída em streaming para recuperar resultados intermediários em tempo real.
import os
import json
from openai import OpenAI
client = OpenAI(
# If you have not configured the environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following URL is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)
input_content = [
{"type": "input_text", "text": "Find landscape images with a style similar to this one"},
# Replace image_url with the actual public URL of the image
{"type": "input_image", "image_url": "https://img.alicdn.com/imgextra/i4/O1CN01YbrnSS1qtmsAkw0Ud_!!6000000005554-2-tps-788-450.png"}
]
stream = client.responses.create(
model="qwen3.8-max",
input=[{"role": "user", "content": input_content}],
tools=[{"type": "image_search"}],
stream=True
)
for event in stream:
# Tool call starts
if event.type == "response.output_item.added":
if event.item.type == "image_search_call":
print("[Tool Call] Searching by image...")
# Tool call is complete. Parse and display the list of searched images.
elif event.type == "response.output_item.done":
if event.item.type == "image_search_call":
print(f"[Tool Call] Search by image complete (status: {event.item.status})")
if event.item.output:
images = json.loads(event.item.output)
print(f" Found {len(images)} images:")
for img in images[:5]: # Display the first 5 images
print(f" [{img['index']}] {img['title']}")
print(f" {img['url']}")
if len(images) > 5:
print(f" ... {len(images)} images in total")
# Model response starts
elif event.type == "response.content_part.added":
print(f"\n[Model Response]")
# Streamed text output
elif event.type == "response.output_text.delta":
print(event.delta, end="", flush=True)
# Response is complete. Output the usage.
elif event.type == "response.completed":
usage = event.response.usage
print(f"\n\n[Token Usage] Input: {usage.input_tokens}, Output: {usage.output_tokens}, Total: {usage.total_tokens}")
if hasattr(usage, 'x_tools') and usage.x_tools:
for tool_name, info in usage.x_tools.items():
print(f"[Tool Statistics] {tool_name} call count: {info.get('count', 0)}")
import OpenAI from "openai";
import process from 'process';
const openai = new OpenAI({
// If you have not configured the environment variable, replace the following line with your Model Studio API key: apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
// The following URL is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
});
async function main() {
const stream = await openai.responses.create({
model: "qwen3.8-max",
input: [
{
role: "user",
content: [
{ type: "input_text", text: "Find landscape images with a style similar to this one" },
// Replace image_url with the actual public URL of the image
{ type: "input_image", image_url: "https://img.alicdn.com/imgextra/i4/O1CN01YbrnSS1qtmsAkw0Ud_!!6000000005554-2-tps-788-450.png" }
]
}
],
tools: [{ type: "image_search" }],
stream: true
});
for await (const event of stream) {
// Tool call starts
if (event.type === "response.output_item.added") {
if (event.item.type === "image_search_call") {
console.log("[Tool Call] Searching by image...");
}
}
// Tool call is complete. Parse and display the list of searched images.
else if (event.type === "response.output_item.done") {
if (event.item && event.item.type === "image_search_call") {
console.log(`[Tool Call] Search by image complete (status: ${event.item.status})`);
if (event.item.output) {
const images = JSON.parse(event.item.output);
console.log(` Found ${images.length} images:`);
images.slice(0, 5).forEach(img => {
console.log(` [${img.index}] ${img.title}`);
console.log(` ${img.url}`);
});
if (images.length > 5) {
console.log(` ... ${images.length} images in total`);
}
}
}
}
// Model response starts
else if (event.type === "response.content_part.added") {
console.log(`\n[Model Response]`);
}
// Streamed text output
else if (event.type === "response.output_text.delta") {
process.stdout.write(event.delta);
}
// Response is complete. Output the usage.
else if (event.type === "response.completed") {
const usage = event.response.usage;
console.log(`\n\n[Token Usage] Input: ${usage.input_tokens}, Output: ${usage.output_tokens}, Total: ${usage.total_tokens}`);
if (usage && usage.x_tools) {
for (const [toolName, info] of Object.entries(usage.x_tools)) {
console.log(`[Tool Statistics] ${toolName} call count: ${info.count || 0}`);
}
}
}
}
}
main();
# The following URL is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.8-max",
"input": [
{
"role": "user",
"content": [
{"type": "input_text", "text": "Find landscape images with a style similar to this one"},
{"type": "input_image", "image_url": "https://img.alicdn.com/imgextra/i4/O1CN01YbrnSS1qtmsAkw0Ud_!!6000000005554-2-tps-788-450.png"}
]
}
],
"tools": [
{"type": "image_search"}
],
"stream": true
}'
Após executar o código, você receberá uma resposta semelhante à seguinte:
[Tool Call] Searching by image...
[Tool Call] Search by image complete (status: completed)
Found 3 images:
[1] QingMing Festival Holiday Notice 2024
https://www.healthcabin.net/blog/wp-content/uploads/2024/04/QingMing-Festival-Holiday-Notice-2024.jpg
[2] Serene Asian Landscape Stone Bridge Reflecting in Misty Water
https://thumbs.dreamstime.com/b/serene-asian-landscape-stone-bridge-reflecting-misty-water-...
[3] ...
[Model Response]
OK. I have found several landscape images with a similar style. These images all display the style of typical Chinese ink wash or fine-brush paintings...
[Token Usage] Input: 5339, Output: 164, Total: 5503
[Tool Statistics] image_search call count: 1
Faturamento
O faturamento envolve os seguintes aspectos:
- Taxas de chamada do modelo: Os resultados da busca por imagem são anexados ao prompt, o que aumenta o número de tokens de entrada do modelo. A cobrança segue a tarifa padrão do modelo. Para detalhes de preços, consulte o console do Model Studio.
- Taxas de chamada de ferramenta: A cobrança é feita a cada 1.000 chamadas. A taxa é de $8,00 para implantações na região de Singapore, enquanto a taxa para implantações em North China 2 (Beijing) é de $6.881.
Perguntas frequentes
P: Quais formatos de imagem e métodos de entrada são suportados?
R: Para mais informações, consulte Image limits e File input methods.
O SDK da OpenAI não oferece suporte à passagem de caminhos de arquivos locais.
P: Quantas imagens podem ser enviadas?
R: A quantidade de imagens permitida depende do comprimento máximo de entrada do modelo. O total de tokens das imagens e do texto não deve exceder o valor máximo suportado pelo modelo. O modelo pesquisa apenas uma imagem por chamada, mas você pode fazer múltiplas chamadas para processar várias imagens.
O modelo decide quantas imagens pesquisar.
P: Quantas imagens pesquisadas são retornadas?
R: O modelo determina a quantidade de imagens a serem retornadas. Esse número não é fixo, mas o limite máximo é de 100 imagens.