Uma run representa a execução de um agente em uma thread.
Crie uma run
Crie uma run.- HTTP
- SDK
curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/threads/thread_cc2a3e9d-436b-482b-91c5-377e0f376506/runs' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
"assistant_id": "asst_46e95014-ccac-435d-b884-c97ac44a94d9",
"metadata": {}
}'
curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/threads/thread_cc2a3e9d-436b-482b-91c5-377e0f376506/runs' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
"assistant_id": "asst_46e95014-ccac-435d-b884-c97ac44a94d9",
"metadata": {},
"stream": true
}'
Nome do parâmetro de entrada | Descrição do parâmetro de entrada | Tipo | Obrigatório |
|---|---|---|---|
thread_id | ID da thread para a run. | string | Sim |
assistant_id | ID do assistente a ser executado. | string | Sim |
model | Nome do modelo a ser chamado. Se especificado, substitui o modelo definido no assistente. | string | Não |
instructions | Substitui a instrução definida no assistente. | string | Não |
tools | Substitui a lista de ferramentas definida no assistente. Transmitir informações de autenticação de ferramenta personalizada { "type": "plugin_type", "auth": {"type": "user_http","user_token": "bearer-token", } } Quando o assistente solicita um plugin, ele adiciona o bearer token ao cabeçalho da chamada do plugin no formato | string | Não |
metadata | Outras descrições de parâmetros relacionados. | string | Não |
stream | Especifica se o resultado deve ser retornado no modo de streaming. | boolean | Não |
temperature | Controla o grau de aleatoriedade e diversidade. | float | Não |
top_p | Limiar de probabilidade para amostragem de núcleo durante a geração. | float | Não |
top_k | Tamanho do conjunto de candidatos para amostragem durante a geração. | integer | Não |
{
"id": "run_3de634fa-75d4-4370-adcf-92ba2a60c396",
"object": "thread.run",
"created_at": 1711517598169,
"thread_id": "thread_cc2a3e9d-436b-482b-91c5-377e0f376506",
"assistant_id": "asst_46e95014-ccac-435d-b884-c97ac44a94d9",
"status": "in_progress",
"model": "qwen-max",
"instructions": "You are an intelligent assistant. You can call different tools based on user needs to provide answers. Use tools as appropriate.",
"tools": [
{
"type": "search"
},
{
"type": "text_to_image"
}
],
"metadata": {},
"request_id": "225292ff-9843-95d4-8591-b1377c33e2be"
}
event:thread.created
data:{"id":"thread_5b7824dc-dbf9-4538-b214-624ee199caa4","object":"thread","created_at":1714448101977,"metadata":{},"request_id":"f38314af-21c4-945e-acdc-cb9765d1d48f"}
event:thread.run.created
data:{"id":"run_04fba6a3-3ac9-42e8-ba2b-9b5c889a8d58","object":"thread.run","created_at":1714448101996,"thread_id":"thread_5b7824dc-dbf9-4538-b214-624ee199caa4","assistant_id":"asst_5378d83a-f612-4fc1-9034-915351d67d98","status":"queued","required_action":null,"last_error":null,"expires_at":null,"started_at":null,"cancelled_at":null,"failed_at":null,"completed_at":null,"model":"qwen-max","instructions":"You are an intelligent assistant. You can call different tools based on user needs to provide answers. Use tools as appropriate.","tools":[{"type":"text_to_image"},{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"file_ids":[],"metadata":{},"usage":null,"temperature":null,"top_p":null,"top_k":null,"max_tokens":null,"truncation_strategy":null,"request_id":"f38314af-21c4-945e-acdc-cb9765d1d48f"}
event:thread.run.queued
data:{"id":"run_04fba6a3-3ac9-42e8-ba2b-9b5c889a8d58","object":"thread.run","created_at":1714448101996,"thread_id":"thread_5b7824dc-dbf9-4538-b214-624ee199caa4","assistant_id":"asst_5378d83a-f612-4fc1-9034-915351d67d98","status":"queued","required_action":null,"last_error":null,"expires_at":null,"started_at":null,"cancelled_at":null,"failed_at":null,"completed_at":null,"model":"qwen-max","instructions":"You are an intelligent assistant. You can call different tools based on user needs to provide answers. Use tools as appropriate.","tools":[{"type":"text_to_image"},{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"file_ids":[],"metadata":{},"usage":null,"temperature":null,"top_p":null,"top_k":null,"max_tokens":null,"truncation_strategy":null,"request_id":"f38314af-21c4-945e-acdc-cb9765d1d48f"}
event:thread.run.in_progress
data:{"id":"run_04fba6a3-3ac9-42e8-ba2b-9b5c889a8d58","object":"thread.run","created_at":1714448101996,"thread_id":"thread_5b7824dc-dbf9-4538-b214-624ee199caa4","assistant_id":"asst_5378d83a-f612-4fc1-9034-915351d67d98","status":"in_progress","required_action":null,"last_error":null,"expires_at":null,"started_at":null,"cancelled_at":null,"failed_at":null,"completed_at":null,"model":"qwen-max","instructions":"You are an intelligent assistant. You can call different tools based on user needs to provide answers. Use tools as appropriate.","tools":[{"type":"text_to_image"},{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"file_ids":[],"metadata":{},"usage":null,"temperature":null,"top_p":null,"top_k":null,"max_tokens":null,"truncation_strategy":null,"request_id":"f38314af-21c4-945e-acdc-cb9765d1d48f"}
event:thread.run.step.created
data:{"id":"step_52c42910-4993-496d-a7f3-ecd4cf007839","object":"thread.run.step","created_at":1714448102574,"assistant_id":"asst_5378d83a-f612-4fc1-9034-915351d67d98","thread_id":"thread_5b7824dc-dbf9-4538-b214-624ee199caa4","run_id":"run_04fba6a3-3ac9-42e8-ba2b-9b5c889a8d58","type":"message_creation","status":"in_progress","step_details":{"type":"message_creation","message_creation":{"message_id":"message_f4f68f6b-6003-4115-8f20-3ea590137502"}},"last_error":null,"expired_at":null,"cancelled_at":null,"failed_at":null,"completed_at":null,"metadata":{},"usage":null,"request_id":"f38314af-21c4-945e-acdc-cb9765d1d48f"}
event:thread.run.step.in_progress
data:{"id":"step_52c42910-4993-496d-a7f3-ecd4cf007839","object":"thread.run.step","created_at":1714448102574,"assistant_id":"asst_5378d83a-f612-4fc1-9034-915351d67d98","thread_id":"thread_5b7824dc-dbf9-4538-b214-624ee199caa4","run_id":"run_04fba6a3-3ac9-42e8-ba2b-9b5c889a8d58","type":"message_creation","status":"in_progress","step_details":{"type":"message_creation","message_creation":{"message_id":"message_f4f68f6b-6003-4115-8f20-3ea590137502"}},"last_error":null,"expired_at":null,"cancelled_at":null,"failed_at":null,"completed_at":null,"metadata":{},"usage":null,"request_id":"f38314af-21c4-945e-acdc-cb9765d1d48f"}
event:thread.message.created
data:{"id":"message_f4f68f6b-6003-4115-8f20-3ea590137502","object":"thread.message","created_at":1714448102574,"thread_id":"thread_5b7824dc-dbf9-4538-b214-624ee199caa4","incomplete_details":null,"completed_at":null,"incomplete_at":null,"role":"assistant","content":[],"assistant_id":"asst_5378d83a-f612-4fc1-9034-915351d67d98","run_id":"run_04fba6a3-3ac9-42e8-ba2b-9b5c889a8d58","file_ids":[],"metadata":{},"request_id":"f38314af-21c4-945e-acdc-cb9765d1d48f"}
event:thread.message.in_progress
data:{"id":"message_f4f68f6b-6003-4115-8f20-3ea590137502","object":"thread.message","created_at":1714448102574,"thread_id":"thread_5b7824dc-dbf9-4538-b214-624ee199caa4","incomplete_details":null,"completed_at":null,"incomplete_at":null,"role":"assistant","content":[],"assistant_id":"asst_5378d83a-f612-4fc1-9034-915351d67d98","run_id":"run_04fba6a3-3ac9-42e8-ba2b-9b5c889a8d58","file_ids":[],"metadata":{},"request_id":"f38314af-21c4-945e-acdc-cb9765d1d48f"}
event:thread.message.delta
data:{"id":"message_f4f68f6b-6003-4115-8f20-3ea590137502","object":"thread.message.delta","delta":{"role":"assistant","content":[{"type":"text","text":{"value":"9","annotations":[]}}],"file_ids":[]},"request_id":"f38314af-21c4-945e-acdc-cb9765d1d48f"}
event:thread.message.delta
data:{"id":"message_f4f68f6b-6003-4115-8f20-3ea590137502","object":"thread.message.delta","delta":{"role":"assistant","content":[{"type":"text","text":{"value":"9","annotations":[]}}],"file_ids":[]},"request_id":"f38314af-21c4-945e-acdc-cb9765d1d48f"}
event:thread.message.delta
data:{"id":"message_f4f68f6b-6003-4115-8f20-3ea590137502","object":"thread.message.delta","delta":{"role":"assistant","content":[{"type":"text","text":{"value":"9","annotations":[]}}],"file_ids":[]},"request_id":"f38314af-21c4-945e-acdc-cb9765d1d48f"}
event:thread.message.delta
data:{"id":"message_f4f68f6b-6003-4115-8f20-3ea590137502","object":"thread.message.delta","delta":{"role":"assistant","content":[{"type":"text","text":{"value":" multiplied by 998","annotations":[]}}],"file_ids":[]},"request_id":"f38314af-21c4-945e-acdc-cb9765d1d48f"}
event:thread.message.delta
data:{"id":"message_f4f68f6b-6003-4115-8f20-3ea590137502","object":"thread.message.delta","delta":{"role":"assistant","content":[{"type":"text","text":{"value":" equals 997002.","annotations":[]}}],"file_ids":[]},"request_id":"f38314af-21c4-945e-acdc-cb9765d1d48f"}
event:thread.message.delta
data:{"id":"message_f4f68f6b-6003-4115-8f20-3ea590137502","object":"thread.message.delta","delta":{"role":"assistant","content":[{"type":"text","text":{"value":"","annotations":[]}}],"file_ids":[]},"request_id":"f38314af-21c4-945e-acdc-cb9765d1d48f"}
event:thread.message.completed
data:{"id":"message_f4f68f6b-6003-4115-8f20-3ea590137502","object":"thread.message","created_at":1714448102574,"thread_id":"thread_5b7824dc-dbf9-4538-b214-624ee199caa4","incomplete_details":null,"completed_at":1714448104154,"incomplete_at":null,"role":"assistant","content":[{"type":"text","text":{"value":"999 multiplied by 998 equals 997002.","annotations":[]}}],"assistant_id":"asst_5378d83a-f612-4fc1-9034-915351d67d98","run_id":"run_04fba6a3-3ac9-42e8-ba2b-9b5c889a8d58","file_ids":[],"metadata":{},"request_id":"f38314af-21c4-945e-acdc-cb9765d1d48f"}
event:thread.run.step.completed
data:{"id":"step_52c42910-4993-496d-a7f3-ecd4cf007839","object":"thread.run.step","created_at":1714448102574,"assistant_id":"asst_5378d83a-f612-4fc1-9034-915351d67d98","thread_id":"thread_5b7824dc-dbf9-4538-b214-624ee199caa4","run_id":"run_04fba6a3-3ac9-42e8-ba2b-9b5c889a8d58","type":"message_creation","status":"completed","step_details":{"type":"message_creation","message_creation":{"message_id":"message_f4f68f6b-6003-4115-8f20-3ea590137502"}},"last_error":null,"expired_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1714448104154,"metadata":{},"usage":null,"request_id":"f38314af-21c4-945e-acdc-cb9765d1d48f"}
event:thread.run.completed
data:{"id":"run_04fba6a3-3ac9-42e8-ba2b-9b5c889a8d58","object":"thread.run","created_at":1714448101996,"thread_id":"thread_5b7824dc-dbf9-4538-b214-624ee199caa4","assistant_id":"asst_5378d83a-f612-4fc1-9034-915351d67d98","status":"completed","required_action":null,"last_error":null,"expires_at":null,"started_at":null,"cancelled_at":null,"failed_at":null,"completed_at":null,"model":"qwen-max","instructions":"You are an intelligent assistant. You can call different tools based on user needs to provide answers. Use tools as appropriate.","tools":[{"type":"text_to_image"},{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"file_ids":[],"metadata":{},"usage":{"input_tokens":419,"output_tokens":16,"total_tokens":435},"temperature":null,"top_p":null,"top_k":null,"max_tokens":null,"truncation_strategy":null,"request_id":"f38314af-21c4-945e-acdc-cb9765d1d48f"}
event:done
data:[DONE]
import dashscope
import os
stream_iterator = dashscope.Runs.create(
'thread_id', # Replace with actual thread_id
# We recommend that you configure the environment variable first. If you have not configured the environment variable, replace the following line with your DashScope API key: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
assistant_id='assistant_id', # Replace with actual assistant_id
stream=True
)
for event, msg in stream_iterator:
print(event)
print(msg)
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.InvalidateParameter;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.threads.runs.AssistantStreamMessage;
import com.alibaba.dashscope.threads.runs.RunParam;
import com.alibaba.dashscope.threads.runs.Runs;
import io.reactivex.Flowable;
public class Main {
public static void main(String[] args) throws ApiException, NoApiKeyException, InputRequiredException, InvalidateParameter, InterruptedException {
Runs runs = new Runs();
// We recommend that you configure the environment variable first. If you have not configured the environment variable, replace the following line with your DashScope API key: apiKey("sk-xxx")
RunParam runParam = RunParam.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.assistantId("assistantId")
.stream(true)
.build();
Flowable<AssistantStreamMessage> run = runs.createStream("threadId", runParam);
}
}
import dashscope
import os
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
stream_iterator = dashscope.Runs.create(
'thread_id', # Replace with actual thread_id
# We recommend that you configure the environment variable first. If you have not configured the environment variable, replace the following line with your DashScope API key: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
assistant_id='assistant_id', # Replace with actual assistant_id
stream=True
)
for event, msg in stream_iterator:
print(event)
print(msg)
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.InvalidateParameter;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.threads.runs.AssistantStreamMessage;
import com.alibaba.dashscope.threads.runs.RunParam;
import com.alibaba.dashscope.threads.runs.Runs;
import io.reactivex.Flowable;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void main(String[] args) throws ApiException, NoApiKeyException, InputRequiredException, InvalidateParameter, InterruptedException {
Runs runs = new Runs();
// We recommend that you configure the environment variable first. If you have not configured the environment variable, replace the following line with your DashScope API key: apiKey("sk-xxx")
RunParam runParam = RunParam.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.assistantId("assistantId")
.stream(true)
.build();
Flowable<AssistantStreamMessage> run = runs.createStream("threadId", runParam);
}
}
Parâmetro | Tipo | Valor padrão | Descrição |
|---|---|---|---|
thread_id | string | - | Thread onde a execução ocorrerá. |
assistant_id | string | - | ID do assistente. |
model | string | - | Modelo a ser utilizado. |
instructions | string | None | Instrução para esta run. |
tools | List[Dict] | [] | Ferramentas utilizadas pelo assistente. Transmitir informações de autenticação de ferramenta personalizada { "type": "plugin_type", "auth": {"type": "user_http","user_token": "bearer-token", } } Quando o assistente solicita um plugin, ele adiciona o bearer token ao cabeçalho da chamada do plugin no formato |
stream | boolean | False | Controla se a saída deve usar streaming. |
metadata | Dict | None | Informações sobre a associação do assistente. |
temperature | Controla o grau de aleatoriedade e diversidade. | float | Não |
top_p | Limiar de probabilidade para amostragem de núcleo durante a geração. | float | Não |
top_k | Tamanho do conjunto de candidatos para amostragem durante a geração. | integer | Não |
metadata | Outras descrições de parâmetros relacionados. | string | Não |
truncation_strategy | Dict | None | Política de truncamento de mensagens na thread. Apenas last_messages é suportado. O valor padrão é: "truncation_strategy": { "type": "last_messages", "last_messages": 10 } |
workspace | string | None | O Workspace ID do Model Studio. Este parâmetro é necessário apenas quando a api_key for uma chave de API de sub-workspace. |
api_key | string | None | Para a chave de API do Alibaba Cloud Model Studio, recomendamos que você configure a chave de API como uma variável de ambiente. |
thread.run.created
{'tools': [{'type': 'quark_search'}], 'required_action': None, 'id': 'run_0f314675-06a4-4379-929c-d29cd351a446', 'object': 'thread.run', 'created_at': 1714460227904, 'thread_id': 'thread_28f0b00b-d825-48f5-bb27-f3b171a64d33', 'assistant_id': 'asst_9453fe59-d6eb-498e-aeca-9abecd492e51', 'status': 'queued', 'last_error': None, 'expires_at': None, 'started_at': None, 'cancelled_at': None, 'failed_at': None, 'completed_at': None, 'model': 'qwen-max', 'instructions': 'You are a helpful assistant. When asked a question, use tools wherever possible.', 'file_ids': [], 'metadata': {}, 'usage': None, 'temperature': None, 'top_p': None, 'top_k': None, 'max_tokens': None, 'truncation_strategy': None, 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.run.queued
{'tools': [{'type': 'quark_search'}], 'required_action': None, 'id': 'run_0f314675-06a4-4379-929c-d29cd351a446', 'object': 'thread.run', 'created_at': 1714460227904, 'thread_id': 'thread_28f0b00b-d825-48f5-bb27-f3b171a64d33', 'assistant_id': 'asst_9453fe59-d6eb-498e-aeca-9abecd492e51', 'status': 'queued', 'last_error': None, 'expires_at': None, 'started_at': None, 'cancelled_at': None, 'failed_at': None, 'completed_at': None, 'model': 'qwen-max', 'instructions': 'You are a helpful assistant. When asked a question, use tools wherever possible.', 'file_ids': [], 'metadata': {}, 'usage': None, 'temperature': None, 'top_p': None, 'top_k': None, 'max_tokens': None, 'truncation_strategy': None, 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.run.in_progress
{'tools': [{'type': 'quark_search'}], 'required_action': None, 'id': 'run_0f314675-06a4-4379-929c-d29cd351a446', 'object': 'thread.run', 'created_at': 1714460227904, 'thread_id': 'thread_28f0b00b-d825-48f5-bb27-f3b171a64d33', 'assistant_id': 'asst_9453fe59-d6eb-498e-aeca-9abecd492e51', 'status': 'in_progress', 'last_error': None, 'expires_at': None, 'started_at': None, 'cancelled_at': None, 'failed_at': None, 'completed_at': None, 'model': 'qwen-max', 'instructions': 'You are a helpful assistant. When asked a question, use tools wherever possible.', 'file_ids': [], 'metadata': {}, 'usage': None, 'temperature': None, 'top_p': None, 'top_k': None, 'max_tokens': None, 'truncation_strategy': None, 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.run.step.created
{'step_details': {'tool_calls': [], 'type': 'tool_calls'}, 'usage': None, 'id': 'step_f923bd08-1e22-40d9-bf54-373b21fde378', 'object': 'thread.run.step', 'created_at': 1714460228960, 'assistant_id': 'asst_9453fe59-d6eb-498e-aeca-9abecd492e51', 'thread_id': 'thread_28f0b00b-d825-48f5-bb27-f3b171a64d33', 'run_id': 'run_0f314675-06a4-4379-929c-d29cd351a446', 'type': 'tool_calls', 'status': 'in_progress', 'expired_at': None, 'cancelled_at': None, 'failed_at': None, 'completed_at': None, 'metadata': {}, 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200, 'last_error': None}
thread.run.step.in_progress
{'step_details': {'tool_calls': [], 'type': 'tool_calls'}, 'usage': None, 'id': 'step_f923bd08-1e22-40d9-bf54-373b21fde378', 'object': 'thread.run.step', 'created_at': 1714460228960, 'assistant_id': 'asst_9453fe59-d6eb-498e-aeca-9abecd492e51', 'thread_id': 'thread_28f0b00b-d825-48f5-bb27-f3b171a64d33', 'run_id': 'run_0f314675-06a4-4379-929c-d29cd351a446', 'type': 'tool_calls', 'status': 'in_progress', 'expired_at': None, 'cancelled_at': None, 'failed_at': None, 'completed_at': None, 'metadata': {}, 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200, 'last_error': None}
thread.run.step.delta
{'delta': {'step_details': {'tool_calls': [{'type': 'quark_search', 'quark_search': {'arguments': ''}}], 'type': 'tool_calls'}}, 'id': 'step_f923bd08-1e22-40d9-bf54-373b21fde378', 'object': 'thread.run.step.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.run.step.delta
{'delta': {'step_details': {'tool_calls': [{'type': 'quark_search', 'quark_search': {'arguments': '{"query": "'}}], 'type': 'tool_calls'}}, 'id': 'step_f923bd08-1e22-40d9-bf54-373b21fde378', 'object': 'thread.run.step.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.run.step.delta
{'delta': {'step_details': {'tool_calls': [{'type': 'quark_search', 'quark_search': {'arguments': 'Today Beijing weather"}'}], 'type': 'tool_calls'}}, 'id': 'step_f923bd08-1e22-40d9-bf54-373b21fde378', 'object': 'thread.run.step.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.run.step.delta
{'delta': {'step_details': {'tool_calls': [{'type': 'quark_search', 'quark_search': {'arguments': ''}}], 'type': 'tool_calls'}}, 'id': 'step_f923bd08-1e22-40d9-bf54-373b21fde378', 'object': 'thread.run.step.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.run.step.delta
{'delta': {'step_details': {'tool_calls': [{'type': 'quark_search', 'quark_search': {'arguments': ''}}], 'type': 'tool_calls'}}, 'id': 'step_f923bd08-1e22-40d9-bf54-373b21fde378', 'object': 'thread.run.step.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.run.step.delta
{'delta': {'step_details': {'tool_calls': [{'type': 'quark_search', 'plugin_name': {'output': '{"success": true, "errorCode": null, "errorMsg": null, "data": [{"title": "Weather in Beijing, China", "url": null, "desc": "Real-time weather: sunny, temperature 24 degrees, feels like 23 degrees, west wind level 1, moderate temperature, very comfortable. For the 15-day weather forecast, click here.", "type": "weather_moji", "original": null, "query": null, "source": null}, {"title": "Beijing Meteorological Bureau", "url": "http://bj.cma.gov.cn/fzlm/index.html", "desc": "36-hour weather forecast (released by Beijing Meteorological Bureau at 05:24:58 on January 25, 2024) Today daytime: Maximum temperature 5°C, sunny to partly cloudy, north wind level 3 with gusts up to level 5, turning to level 2. Tonight: Minimum temperature -5°C, sunny, north wind level 2 turning to level 3. Tomorrow daytime: Maximum temperature 5°C, sunny, wind level 3 turning to level 1...", "type": "structure_web_info", "original": null, "query": null, "source": "Beijing Meteorological Bureau"}, {"title": "Beijing", "url": "https://m.weather.com.cn/mweather/101010100.shtml?_t=1480291523052", "desc": "Beijing weather forecast, timely and accurate release of weather information from the Central Meteorological Administration, convenient query of Beijing's weather today, Beijing's weekend weather, Beijing's one-week weather forecast, Beijing's blue sky forecast, Beijing's weather forecast, Beijing's 40-day weather forecast, and also provides Beijing's life index, health index, ...", "type": "normal", "original": null, "query": null, "source": "China Weather"}, {"title": "Moji Weather Official Chinese Website", "url": "https://m.moji.com/", "desc": "Moji Weather forecast app, used by about 650 million people worldwide, supports weather forecast queries for more than 200,000 cities and regions in 199 countries. Download the Moji Weather forecast app to monitor sunny, cloudy, rainy, and snowy conditions in real time, along with real-time air quality and air quality level forecasts.", "type": "structure_web_info", "original": null, "query": null, "source": "Moji Weather Mobile Version"}, {"title": "Beijing", "url": "http://sq.weather.com.cn/mweather15d/101010100.shtml?from=singlemessage", "desc": "Beijing weather forecast, timely and accurate release of weather information from the Central Meteorological Administration, convenient query of Beijing's weather today, Beijing's weekend weather, Beijing's one-week weather forecast, Beijing's blue sky forecast, Beijing's weather forecast, Beijing's 40-day weather forecast, and also provides Beijing's life index, health index, ...", "type": "structure_web_info", "original": null, "query": null, "source": "China Weather Network"}, {"title": "Toutiao News", "url": null, "desc": "China Weather Network reported 1 day ago: Forecast, Warning, Radar, Cloud Map, Weather Map, Professional Products, Information, Video, Solar Terms, My Sky ... Prince Gong's Mansion, Beijing Olympic Park, Olympic Forest Park, Beijing Shijingshan Amusement Park, Jinhai Lake, Jingdong Grand Canyon Tourist Area, Ming Tombs, Yinshan Pagoda Forest Scenic Area, China Aviation Museum, Beijing Happy Valley, Beijing China...", "type": "news_uchq", "original": null, "query": null, "source": null}, {"title": "Beijing", "url": "http://www.weather.com.cn/weather1d/101010100.shtml", "desc": "Beijing weather forecast, timely and accurate release of weather information from the Central Meteorological Administration, convenient query of Beijing's weather today, Beijing's weekend weather, Beijing's one-week weather forecast, Beijing's 15-day...", "type": "structure_web_info", "original": null, "query": null, "source": "China Weather Network"}, {"title": "Beijing 24-hour weather query_Beijing today's weather forecast query_2345 Weather King", "url": "http://waptianqi.2345.com/24hour-54511.htm", "desc": "2345 Weather Forecast provides you with the latest Beijing weather, 24-hour weather conditions, and other information in a timely manner, and also provides the daily meteorological index for Beijing.", "type": "structure_web_info", "original": null, "query": null, "source": "2345 Weather King"}, {"title": "Beijing 15-day weather details", "url": "http://waptianqi.2345.com/beijing-54511.htm", "desc": "2345 Weather Forecast provides Beijing weather forecasts, and future 15-day weather for Beijing. Through 2345 Weather Forecast, you can get detailed information about the weather forecast for Beijing and surrounding areas for the next 15 and 30 days, including temperature, air quality, precipitation, wind force, atmospheric pressure, ultraviolet intensity, etc.!", "type": "structure_web_info", "original": null, "query": null, "source": "2345 Weather King"}, {"title": "Beijing weather forecast for 15 days", "url": "https://m.tianqi.com/beijing/15/", "desc": "Beijing weather forecast 15-day details: 12/11 Today Light Snow -2~2 ℃ 12/12 Tomorrow Cloudy to Light Snow -2~2 ℃ 12/13 The day after tomorrow Light Snow -5~0 ℃ 12/14 Thursday Light Snow -5~-1 ℃ 12/15 Friday Overcast to Cloudy -10~-2 ℃ 12/16 Saturday Sunny -10~-3 ℃ 12/17 ...", "type": "structure_web_info", "original": null, "query": null, "source": "Weather Network"}, {"title": "Beijing Weather", "url": "https://t.8684.com/beijing_beijing", "desc": "Beijing weather forecast for one week and 15 days, Beijing weather forecast, Beijing weather forecast for one week, Beijing weather forecast for 15 days, Beijing weather forecast for this week, Beijing weather forecast for next week, Beijing weather forecast for 15 days query, Beijing weather forecast for 10 days", "type": "structure_web_info", "original": null, "query": null, "source": "8684 Weather"}], "requestId": null, "failed": false}'}}], 'type': 'tool_calls'}}, 'id': 'step_f923bd08-1e22-40d9-bf54-373b21fde378', 'object': 'thread.run.step.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.run.step.delta
{'delta': {'step_details': {'tool_calls': [{'quark_search': {'output': ''}}], 'type': 'tool_calls'}}, 'id': 'step_f923bd08-1e22-40d9-bf54-373b21fde378', 'object': 'thread.run.step.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.run.step.delta
{'delta': {'step_details': {'tool_calls': [{'quark_search': {'output': ''}}], 'type': 'tool_calls'}}, 'id': 'step_f923bd08-1e22-40d9-bf54-373b21fde378', 'object': 'thread.run.step.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.run.step.completed
{'step_details': {'tool_calls': [{'type': 'quark_search', 'plugin_name': {'arguments': '{"query": "Today Beijing weather"}', 'output': '{"success": true, "errorCode": null, "errorMsg": null, "data": [{"title": "Weather in Beijing, China", "url": null, "desc": "Real-time weather: sunny, temperature 24 degrees, feels like 23 degrees, west wind level 1, moderate temperature, very comfortable. For the 15-day weather forecast, click here.", "type": "weather_moji", "original": null, "query": null, "source": null}, {"title": "Beijing Meteorological Bureau", "url": "http://bj.cma.gov.cn/fzlm/index.html", "desc": "36-hour weather forecast (released by Beijing Meteorological Bureau at 05:24:58 on January 25, 2024) Today daytime: Maximum temperature 5°C, sunny to partly cloudy, north wind level 3 with gusts up to level 5, turning to level 2. Tonight: Minimum temperature -5°C, sunny, north wind level 2 turning to level 3. Tomorrow daytime: Maximum temperature 5°C, sunny, wind level 3 turning to level 1...", "type": "structure_web_info", "original": null, "query": null, "source": "Beijing Meteorological Bureau"}, {"title": "Beijing", "url": "https://m.weather.com.cn/mweather/101010100.shtml?_t=1480291523052", "desc": "Beijing weather forecast, timely and accurate release of weather information from the Central Meteorological Administration, convenient query of Beijing's weather today, Beijing's weekend weather, Beijing's one-week weather forecast, Beijing's blue sky forecast, Beijing's weather forecast, Beijing's 40-day weather forecast, and also provides Beijing's life index, health index, ...", "type": "normal", "original": null, "query": null, "source": "China Weather"}, {"title": "Moji Weather Official Chinese Website", "url": "https://m.moji.com/", "desc": "Moji Weather forecast app, used by about 650 million people worldwide, supports weather forecast queries for more than 200,000 cities and regions in 199 countries. Download the Moji Weather forecast app to monitor sunny, cloudy, rainy, and snowy conditions in real time, along with real-time air quality and air quality level forecasts.", "type": "structure_web_info", "original": null, "query": null, "source": "Moji Weather Mobile Version"}, {"title": "Beijing", "url": "http://sq.weather.com.cn/mweather15d/101010100.shtml?from=singlemessage", "desc": "Beijing weather forecast, timely and accurate release of weather information from the Central Meteorological Administration, convenient query of Beijing's weather today, Beijing's weekend weather, Beijing's one-week weather forecast, Beijing's blue sky forecast, Beijing's weather forecast, Beijing's 40-day weather forecast, and also provides Beijing's life index, health index, ...", "type": "structure_web_info", "original": null, "query": null, "source": "China Weather Network"}, {"title": "Toutiao News", "url": null, "desc": "China Weather Network reported 1 day ago: Forecast, Warning, Radar, Cloud Map, Weather Map, Professional Products, Information, Video, Solar Terms, My Sky ... Prince Gong's Mansion, Beijing Olympic Park, Olympic Forest Park, Beijing Shijingshan Amusement Park, Jinhai Lake, Jingdong Grand Canyon Tourist Area, Ming Tombs, Yinshan Pagoda Forest Scenic Area, China Aviation Museum, Beijing Happy Valley, Beijing China...", "type": "news_uchq", "original": null, "query": null, "source": null}, {"title": "Beijing", "url": "http://www.weather.com.cn/weather1d/101010100.shtml", "desc": "Beijing weather forecast, timely and accurate release of weather information from the Central Meteorological Administration, convenient query of Beijing's weather today, Beijing's weekend weather, Beijing's one-week weather forecast, Beijing's 15-day...", "type": "structure_web_info", "original": null, "query": null, "source": "China Weather Network"}, {"title": "Beijing 24-hour weather query_Beijing today's weather forecast query_2345 Weather King", "url": "http://waptianqi.2345.com/24hour-54511.htm", "desc": "2345 Weather Forecast provides you with the latest Beijing weather, 24-hour weather conditions, and other information in a timely manner, and also provides the daily meteorological index for Beijing.", "type": "structure_web_info", "original": null, "query": null, "source": "2345 Weather King"}, {"title": "Beijing 15-day weather details", "url": "http://waptianqi.2345.com/beijing-54511.htm", "desc": "2345 Weather Forecast provides Beijing weather forecasts, and future 15-day weather for Beijing. Through 2345 Weather Forecast, you can get detailed information about the weather forecast for Beijing and surrounding areas for the next 15 and 30 days, including temperature, air quality, precipitation, wind force, atmospheric pressure, ultraviolet intensity, etc.!", "type": "structure_web_info", "original": null, "query": null, "source": "2345 Weather King"}, {"title": "Beijing weather forecast for 15 days", "url": "https://m.tianqi.com/beijing/15/", "desc": "Beijing weather forecast 15-day details: 12/11 Today Light Snow -2~2 ℃ 12/12 Tomorrow Cloudy to Light Snow -2~2 ℃ 12/13 The day after tomorrow Light Snow -5~0 ℃ 12/14 Thursday Light Snow -5~-1 ℃ 12/15 Friday Overcast to Cloudy -10~-2 ℃ 12/16 Saturday Sunny -10~-3 ℃ 12/17 ...", "type": "structure_web_info", "original": null, "query": null, "source": "Weather Network"}, {"title": "Beijing Weather", "url": "https://t.8684.com/beijing_beijing", "desc": "Beijing weather forecast for one week and 15 days, Beijing weather forecast, Beijing weather forecast for one week, Beijing weather forecast for 15 days, Beijing weather forecast for this week, Beijing weather forecast for next week, Beijing weather forecast for 15 days query, Beijing weather forecast for 10 days", "type": "structure_web_info", "original": null, "query": null, "source": "8684 Weather"}], "requestId": null, "failed": false}'}}], 'type': 'tool_calls'}, 'usage': None, 'id': 'step_f923bd08-1e22-40d9-bf54-373b21fde378', 'object': 'thread.run.step', 'created_at': 1714460228960, 'assistant_id': 'asst_9453fe59-d6eb-498e-aeca-9abecd492e51', 'thread_id': 'thread_28f0b00b-d825-48f5-bb27-f3b171a64d33', 'run_id': 'run_0f314675-06a4-4379-929c-d29cd351a446', 'type': 'tool_calls', 'status': 'in_progress', 'expired_at': None, 'cancelled_at': None, 'failed_at': None, 'completed_at': None, 'metadata': {}, 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200, 'last_error': None}
thread.run.step.created
{'step_details': {'message_creation': {'message_id': 'message_93605cd7-fb74-468b-b6fb-4975cd253f8d'}, 'type': 'message_creation'}, 'usage': None, 'id': 'step_89e631c7-491a-4bff-b1f5-1298f88db531', 'object': 'thread.run.step', 'created_at': 1714460234236, 'assistant_id': 'asst_9453fe59-d6eb-498e-aeca-9abecd492e51', 'thread_id': 'thread_28f0b00b-d825-48f5-bb27-f3b171a64d33', 'run_id': 'run_0f314675-06a4-4379-929c-d29cd351a446', 'type': 'message_creation', 'status': 'in_progress', 'expired_at': None, 'cancelled_at': None, 'failed_at': None, 'completed_at': None, 'metadata': {}, 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200, 'last_error': None}
thread.run.step.in_progress
{'step_details': {'message_creation': {'message_id': 'message_93605cd7-fb74-468b-b6fb-4975cd253f8d'}, 'type': 'message_creation'}, 'usage': None, 'id': 'step_89e631c7-491a-4bff-b1f5-1298f88db531', 'object': 'thread.run.step', 'created_at': 1714460234236, 'assistant_id': 'asst_9453fe59-d6eb-498e-aeca-9abecd492e51', 'thread_id': 'thread_28f0b00b-d825-48f5-bb27-f3b171a64d33', 'run_id': 'run_0f314675-06a4-4379-929c-d29cd351a446', 'type': 'message_creation', 'status': 'in_progress', 'expired_at': None, 'cancelled_at': None, 'failed_at': None, 'completed_at': None, 'metadata': {}, 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200, 'last_error': None}
thread.message.created
{'content': [], 'id': 'message_93605cd7-fb74-468b-b6fb-4975cd253f8d', 'object': 'thread.message', 'created_at': 1714460234235, 'thread_id': 'thread_28f0b00b-d825-48f5-bb27-f3b171a64d33', 'incomplete_details': None, 'completed_at': None, 'incomplete_at': None, 'role': 'assistant', 'assistant_id': 'asst_9453fe59-d6eb-498e-aeca-9abecd492e51', 'run_id': 'run_0f314675-06a4-4379-929c-d29cd351a446', 'file_ids': [], 'metadata': {}, 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.message.in_progress
{'content': [], 'id': 'message_93605cd7-fb74-468b-b6fb-4975cd253f8d', 'object': 'thread.message', 'created_at': 1714460234235, 'thread_id': 'thread_28f0b00b-d825-48f5-bb27-f3b171a64d33', 'incomplete_details': None, 'completed_at': None, 'incomplete_at': None, 'role': 'assistant', 'assistant_id': 'asst_9453fe59-d6eb-498e-aeca-9abecd492e51', 'run_id': 'run_0f314675-06a4-4379-929c-d29cd351a446', 'file_ids': [], 'metadata': {}, 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.message.delta
{'delta': {'content': {'text': {'annotations': [], 'value': 'Today'}, 'type': 'text'}, 'role': 'assistant'}, 'id': 'message_93605cd7-fb74-468b-b6fb-4975cd253f8d', 'object': 'thread.message.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.message.delta
{'delta': {'content': {'text': {'annotations': [], 'value': ' the weather in Beijing is'}, 'type': 'text'}, 'role': 'assistant'}, 'id': 'message_93605cd7-fb74-468b-b6fb-4975cd253f8d', 'object': 'thread.message.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.message.delta
{'delta': {'content': {'text': {'annotations': [], 'value': ' sunny, with a temperature of about 24'}, 'type': 'text'}, 'role': 'assistant'}, 'id': 'message_93605cd7-fb74-468b-b6fb-4975cd253f8d', 'object': 'thread.message.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.message.delta
{'delta': {'content': {'text': {'annotations': [], 'value': ' degrees and a feels-like temperature of 23'}, 'type': 'text'}, 'role': 'assistant'}, 'id': 'message_93605cd7-fb74-468b-b6fb-4975cd253f8d', 'object': 'thread.message.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.message.delta
{'delta': {'content': {'text': {'annotations': [], 'value': ' degrees, with a level 1 west wind, making the weather'}, 'type': 'text'}, 'role': 'assistant'}, 'id': 'message_93605cd7-fb74-468b-b6fb-4975cd253f8d', 'object': 'thread.message.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.message.delta
{'delta': {'content': {'text': {'annotations': [], 'value': ' quite comfortable. However, I also found more detailed information from the Beijing'}, 'type': 'text'}, 'role': 'assistant'}, 'id': 'message_93605cd7-fb74-468b-b6fb-4975cd253f8d', 'object': 'thread.message.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.message.delta
{'delta': {'content': {'text': {'annotations': [], 'value': ' Meteorological Bureau, which mentions'}, 'type': 'text'}, 'role': 'assistant'}, 'id': 'message_93605cd7-fb74-468b-b6fb-4975cd253f8d', 'object': 'thread.message.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.message.delta
{'delta': {'content': {'text': {'annotations': [], 'value': ' that the maximum temperature during the day is 5°C,'}, 'type': 'text'}, 'role': 'assistant'}, 'id': 'message_93605cd7-fb74-468b-b6fb-4975cd253f8d', 'object': 'thread.message.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.message.delta
{'delta': {'content': {'text': {'annotations': [], 'value': ' the weather is sunny to partly cloudy, with a level 3'}, 'type': 'text'}, 'role': 'assistant'}, 'id': 'message_93605cd7-fb74-468b-b6fb-4975cd253f8d', 'object': 'thread.message.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.message.delta
{'delta': {'content': {'text': {'annotations': [], 'value': ' north wind and gusts up to'}, 'type': 'text'}, 'role': 'assistant'}, 'id': 'message_93605cd7-fb74-468b-b6fb-4975cd253f8d', 'object': 'thread.message.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.message.delta
{'delta': {'content': {'text': {'annotations': [], 'value': ' level 5. The minimum temperature at night will drop to -'}, 'type': 'text'}, 'role': 'assistant'}, 'id': 'message_93605cd7-fb74-468b-b6fb-4975cd253f8d', 'object': 'thread.message.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.message.delta
{'delta': {'content': {'text': {'annotations': [], 'value': '5°C, remaining sunny,'}, 'type': 'text'}, 'role': 'assistant'}, 'id': 'message_93605cd7-fb74-468b-b6fb-4975cd253f8d', 'object': 'thread.message.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.message.delta
{'delta': {'content': {'text': {'annotations': [], 'value': ' with the wind shifting to a northerly direction,'}, 'type': 'text'}, 'role': 'assistant'}, 'id': 'message_93605cd7-fb74-468b-b6fb-4975cd253f8d', 'object': 'thread.message.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.message.delta
{'delta': {'content': {'text': {'annotations': [], 'value': ' and the wind force changing from level 2 to 3.'}, 'type': 'text'}, 'role': 'assistant'}, 'id': 'message_93605cd7-fb74-468b-b6fb-4975cd253f8d', 'object': 'thread.message.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.message.delta
{'delta': {'content': {'text': {'annotations': [], 'value': ' Please adjust your clothing according to the real-time weather,'}, 'type': 'text'}, 'role': 'assistant'}, 'id': 'message_93605cd7-fb74-468b-b6fb-4975cd253f8d', 'object': 'thread.message.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.message.delta
{'delta': {'content': {'text': {'annotations': [], 'value': ' and stay warm.'}, 'type': 'text'}, 'role': 'assistant'}, 'id': 'message_93605cd7-fb74-468b-b6fb-4975cd253f8d', 'object': 'thread.message.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.message.delta
{'delta': {'content': {'text': {'annotations': [], 'value': ''}, 'type': 'text'}, 'role': 'assistant'}, 'id': 'message_93605cd7-fb74-468b-b6fb-4975cd253f8d', 'object': 'thread.message.delta', 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.message.completed
{'content': [{'text': {'annotations': [], 'value': 'Today the weather in Beijing is sunny, with a temperature of about 24 degrees and a feels-like temperature of 23 degrees, with a level 1 west wind, making the weather quite comfortable. However, I also found more detailed information from the Beijing Meteorological Bureau, which mentions that the maximum temperature during the day is 5°C, the weather is sunny to partly cloudy, with a level 3 north wind and gusts up to level 5. The minimum temperature at night will drop to -5°C, remaining sunny, with the wind shifting to a northerly direction, and the wind force changing from level 2 to 3. Please adjust your clothing according to the real-time weather, and stay warm.'}, 'type': 'text'}], 'id': 'message_93605cd7-fb74-468b-b6fb-4975cd253f8d', 'object': 'thread.message', 'created_at': 1714460234235, 'thread_id': 'thread_28f0b00b-d825-48f5-bb27-f3b171a64d33', 'incomplete_details': None, 'completed_at': 1714460245637, 'incomplete_at': None, 'role': 'assistant', 'assistant_id': 'asst_9453fe59-d6eb-498e-aeca-9abecd492e51', 'run_id': 'run_0f314675-06a4-4379-929c-d29cd351a446', 'file_ids': [], 'metadata': {}, 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
thread.run.step.completed
{'step_details': {'message_creation': {'message_id': 'message_93605cd7-fb74-468b-b6fb-4975cd253f8d'}, 'type': 'message_creation'}, 'usage': None, 'id': 'step_89e631c7-491a-4bff-b1f5-1298f88db531', 'object': 'thread.run.step', 'created_at': 1714460234236, 'assistant_id': 'asst_9453fe59-d6eb-498e-aeca-9abecd492e51', 'thread_id': 'thread_28f0b00b-d825-48f5-bb27-f3b171a64d33', 'run_id': 'run_0f314675-06a4-4379-929c-d29cd351a446', 'type': 'message_creation', 'status': 'completed', 'expired_at': None, 'cancelled_at': None, 'failed_at': None, 'completed_at': 1714460245637, 'metadata': {}, 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200, 'last_error': None}
thread.run.completed
{'tools': [{'type': 'quark_search'}], 'required_action': None, 'id': 'run_0f314675-06a4-4379-929c-d29cd351a446', 'object': 'thread.run', 'created_at': 1714460227904, 'thread_id': 'thread_28f0b00b-d825-48f5-bb27-f3b171a64d33', 'assistant_id': 'asst_9453fe59-d6eb-498e-aeca-9abecd492e51', 'status': 'completed', 'last_error': None, 'expires_at': None, 'started_at': None, 'cancelled_at': None, 'failed_at': None, 'completed_at': None, 'model': 'qwen-max', 'instructions': 'You are a helpful assistant. When asked a question, use tools wherever possible.', 'file_ids': [], 'metadata': {}, 'usage': {'input_tokens': 1865, 'output_tokens': 139, 'total_tokens': 2004}, 'temperature': None, 'top_p': None, 'top_k': None, 'max_tokens': None, 'truncation_strategy': None, 'request_id': '38fb88b8-196a-9919-8815-f7ed9aa0891f', 'status_code': 200}
Nome do campo | Tipo | Descrição |
|---|---|---|
status_code | integer | Código de status HTTP da chamada. O valor 200 indica que a chamada foi bem-sucedida. Outros valores indicam falha na chamada. |
id | string | ID da run, que é uma string UUID. |
model | string | Nome do modelo utilizado pela run. |
instructions | string | Informações de instrução do assistente, que especificam sua função. |
metadata | object | Pares chave-valor que descrevem o assistente. |
status | string | Status da run, como in_progress. |
thread_id | string | ID da thread para a run. |
tools | List[Tool] | Lista de ferramentas usadas pela run. |
file_ids | List[str] | Lista de IDs de arquivos associados à run. |
created_at | timestamp | Momento em que o assistente foi criado. |
gmt_created | datetime | 2024-03-22 17:12:31 |
gmt_modified | datetime | 2024-03-22 17:12:31 |
code | string | Indica que a solicitação falhou e fornece o código de erro. Este parâmetro é ignorado se a solicitação for bem-sucedida. Apenas Python |
message | string | Indica que a solicitação falhou e fornece informações detalhadas. Este parâmetro é ignorado se a solicitação for bem-sucedida. Apenas Python |
Listar runs
Retorna uma lista de runs pertencentes a uma thread.- HTTP
- SDK
curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/threads/thread_cc2a3e9d-436b-482b-91c5-377e0f376506/runs?limit=20&order=asc' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Nome do parâmetro | Descrição do parâmetro de entrada | Tipo | Obrigatório |
|---|---|---|---|
thread_id | ID da thread para a lista de runs. | string | Sim |
limit | Número de runs a serem consultadas nesta solicitação. | integer | Não |
order | Ordenação por hora de criação, ascendente ou descendente. | string | Não (O valor padrão é "desc".) |
{
"object": "list",
"data": [
{
"id": "run_3de634fa-75d4-4370-adcf-92ba2a60c396",
"object": "thread.run",
"created_at": 1711517598169,
"thread_id": "thread_cc2a3e9d-436b-482b-91c5-377e0f376506",
"assistant_id": "asst_46e95014-ccac-435d-b884-c97ac44a94d9",
"status": "completed",
"required_action": {},
"last_error": {},
"expires_at": 0,
"started_at": 0,
"cancelled_at": 0,
"failed_at": 0,
"completed_at": 0,
"model": "qwen-max",
"instructions": "You are an intelligent assistant. You can call different tools based on user needs to provide answers. Use tools as appropriate.",
"tools": [
{
"type": "search"
},
{
"type": "text_to_image"
}
],
"metadata": {},
"usage": {
"input_tokens": 66,
"output_tokens": 9,
"total_tokens": 75
}
}
],
"first_id": "run_3de634fa-75d4-4370-adcf-92ba2a60c396",
"last_id": "run_3de634fa-75d4-4370-adcf-92ba2a60c396",
"has_more": false,
"request_id": "ff3d2aea-555c-9825-80ca-24029a636641"
}
from dashscope import Runs
import os
runs = Runs.list(
'thread_id',
# We recommend that you configure the environment variable first. If you have not configured the environment variable, replace the following line with your DashScope API key: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
limit=1,
order='desc'
)
import com.alibaba.dashscope.common.GeneralListParam;
import com.alibaba.dashscope.common.ListResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.InvalidateParameter;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.threads.runs.Run;
import com.alibaba.dashscope.threads.runs.Runs;
public class Main {
public static void main(String[] args) throws ApiException, NoApiKeyException, InputRequiredException, InvalidateParameter, InterruptedException {
Runs runs = new Runs();
// We recommend that you configure the environment variable first. If you have not configured the environment variable, replace the following line with your DashScope API key: apiKey("sk-xxx")
GeneralListParam listRuns = GeneralListParam.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.build();
ListResult<Run> run = runs.list("threadId", listRuns);
}
}
import dashscope
from dashscope import Runs
import os
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
runs = Runs.list(
'thread_id',
# We recommend that you configure the environment variable first. If you have not configured the environment variable, replace the following line with your DashScope API key: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
limit=1,
order='desc'
)
import com.alibaba.dashscope.common.GeneralListParam;
import com.alibaba.dashscope.common.ListResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.InvalidateParameter;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.threads.runs.Run;
import com.alibaba.dashscope.threads.runs.Runs;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void main(String[] args) throws ApiException, NoApiKeyException, InputRequiredException, InvalidateParameter, InterruptedException {
Runs runs = new Runs();
// We recommend that you configure the environment variable first. If you have not configured the environment variable, replace the following line with your DashScope API key: apiKey("sk-xxx")
GeneralListParam listRuns = GeneralListParam.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.build();
ListResult<Run> run = runs.list("threadId", listRuns);
}
}
Parâmetro | Tipo | Valor padrão | Descrição |
|---|---|---|---|
thread_id | str | - | Especifique o ID da thread a ser listada. |
limit | int | None | Número de tarefas nesta consulta |
order | str | None | Ordem de classificação das runs por hora de criação. O valor padrão é determinado pela configuração do servidor.
|
workspace | str | None | O Workspace ID do Model Studio. Este parâmetro é necessário apenas quando a api_key for uma chave de API de sub-workspace. |
api_key | str | None | A chave de API do Model Studio. Recomendamos que você configure a chave de API como uma variável de ambiente. |
Nome do campo | Tipo | Descrição |
|---|---|---|
has_more | bool | Existem mais dados disponíveis?
|
last_id | str | ID da última tarefa retornada |
first_id | str | ID da primeira run nos resultados retornados. |
data | list[Run] | Lista de objetos Run. |
Recuperar uma run
Recupera uma run.- HTTP
- SDK
curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/threads/thread_cc2a3e9d-436b-482b-91c5-377e0f376506/runs/run_3de634fa-75d4-4370-adcf-92ba2a60c396' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Nome do parâmetro de entrada | Descrição | Tipo de parâmetro | Obrigatório |
|---|---|---|---|
thread_id | ID da thread para a run a ser recuperada. | string | Sim |
run_id | ID da run a ser recuperada. | string | Sim |
{
"id": "run_3de634fa-75d4-4370-adcf-92ba2a60c396",
"object": "thread.run",
"created_at": 1711517598169,
"thread_id": "thread_cc2a3e9d-436b-482b-91c5-377e0f376506",
"assistant_id": "asst_46e95014-ccac-435d-b884-c97ac44a94d9",
"status": "completed",
"required_action": {},
"last_error": {},
"expires_at": 0,
"started_at": 0,
"cancelled_at": 0,
"failed_at": 0,
"completed_at": 0,
"model": "qwen-max",
"instructions": "You are an intelligent assistant. You can call different tools based on user needs to provide answers. Use tools as appropriate.",
"tools": [
{
"type": "search"
},
{
"type": "text_to_image"
}
],
"metadata": {},
"usage": {
"input_tokens": 66,
"output_tokens": 9,
"total_tokens": 75
},
"request_id": "05c5f4ea-5e6b-9901-9849-7a0943a0db43"
}
from dashscope import Runs
import os
run = Runs.retrieve(
'run_id',
# We recommend that you configure the environment variable first. If you have not configured the environment variable, replace the following line with your DashScope API key: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
thread_id='thread_id'
)
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.InvalidateParameter;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.threads.runs.Run;
import com.alibaba.dashscope.threads.runs.Runs;
public class Main {
public static void main(String[] args) throws ApiException, NoApiKeyException, InputRequiredException, InvalidateParameter, InterruptedException {
Runs runs = new Runs();
// We recommend that you configure the environment variable first. If you have not configured the environment variable, replace the following line with your DashScope API key: apiKey("sk-xxx")
String apiKey = System.getenv("DASHSCOPE_API_KEY");
Run run = runs.retrieve("threadId", "runId", apiKey);
}
}
import dashscope
from dashscope import Runs
import os
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
run = Runs.retrieve(
'run_id',
# We recommend that you configure the environment variable first. If you have not configured the environment variable, replace the following line with your DashScope API key: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
thread_id='thread_id'
)
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.InvalidateParameter;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.threads.runs.Run;
import com.alibaba.dashscope.threads.runs.Runs;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void main(String[] args) throws ApiException, NoApiKeyException, InputRequiredException, InvalidateParameter, InterruptedException {
Runs runs = new Runs();
// We recommend that you configure the environment variable first. If you have not configured the environment variable, replace the following line with your DashScope API key: apiKey("sk-xxx")
String apiKey = System.getenv("DASHSCOPE_API_KEY");
Run run = runs.retrieve("threadId", "runId", apiKey);
}
}
Parâmetro | Tipo | Valor padrão | Descrição |
|---|---|---|---|
run_id | str | - | ID da run a ser consultada. |
thread_id | str | - | ID da thread para a run. |
workspace | str | None | O Workspace ID do Model Studio. Este parâmetro é necessário apenas quando a api_key for uma chave de API de sub-workspace. |
api_key | str | None | Para sua chave de API do Alibaba Cloud Model Studio, recomendamos que você configure a chave de API como uma variável de ambiente (Este tópico será despublicado e mesclado em Configurar chave de API). |
Modifique uma run
Modifique uma run.- HTTP
- SDK
curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/threads/thread_cc2a3e9d-436b-482b-91c5-377e0f376506/runs/run_3de634fa-75d4-4370-adcf-92ba2a60c396' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
"metadata": {
"user": "abc123"
}
}'
Nome do parâmetro de entrada | Descrição | Tipo | Obrigatório |
|---|---|---|---|
thread_id | ID da thread a ser modificada. | string | Sim |
run_id | ID da run a ser modificada. | string | Sim |
* | Outros parâmetros opcionais da solicitação. | string | Não |
{
"id": "run_3de634fa-75d4-4370-adcf-92ba2a60c396",
"object": "thread.run",
"created_at": 1711517598169,
"thread_id": "thread_cc2a3e9d-436b-482b-91c5-377e0f376506",
"assistant_id": "asst_46e95014-ccac-435d-b884-c97ac44a94d9",
"status": "completed",
"required_action": {},
"last_error": {},
"expires_at": 0,
"started_at": 0,
"cancelled_at": 0,
"failed_at": 0,
"completed_at": 0,
"model": "qwen-max",
"instructions": "You are an intelligent assistant. You can call different tools based on user needs to provide answers. Use tools as appropriate.",
"tools": [
{
"type": "search"
},
{
"type": "text_to_image"
}
],
"metadata": {
"user": "abc123"
},
"usage": {
"input_tokens": 66,
"output_tokens": 9,
"total_tokens": 75
},
"request_id": "bb6a5c5c-146f-95b8-bafa-e6c467e4f2d3"
}
from dashscope import Runs
import os
run = Runs.update(
'run_id',
# We recommend that you configure the environment variable first. 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"),
thread_id='thread_id',
metadata={'newkey': 'newvalue'}
)
import java.util.HashMap;
import java.util.Map;
import com.alibaba.dashscope.common.UpdateMetadataParam;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.InvalidateParameter;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.threads.runs.Run;
import com.alibaba.dashscope.threads.runs.Runs;
public class Main {
public static void main(String[] args) throws ApiException, NoApiKeyException, InputRequiredException, InvalidateParameter, InterruptedException {
Runs runs = new Runs();
Map<String, String> metadata = new HashMap<>();
metadata.put("key", "value");
// We recommend that you configure the environment variable first. If you have not configured the environment variable, replace the following line with your Model Studio API key: apiKey("sk-xxx")
UpdateMetadataParam updateParam = UpdateMetadataParam.builder()
.metadata(metadata)
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.build();
Run run = runs.update("threadId", "runId", updateParam);
}
}
import dashscope
from dashscope import Runs
import os
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
run = Runs.update(
'run_id',
# We recommend that you configure the environment variable first. 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"),
thread_id='thread_id',
metadata={'newkey': 'newvalue'}
)
import java.util.HashMap;
import java.util.Map;
import com.alibaba.dashscope.common.UpdateMetadataParam;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.InvalidateParameter;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.threads.runs.Run;
import com.alibaba.dashscope.threads.runs.Runs;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void main(String[] args) throws ApiException, NoApiKeyException, InputRequiredException, InvalidateParameter, InterruptedException {
Runs runs = new Runs();
Map<String, String> metadata = new HashMap<>();
metadata.put("key", "value");
// We recommend that you configure the environment variable first. If you have not configured the environment variable, replace the following line with your Model Studio API key: apiKey("sk-xxx")
UpdateMetadataParam updateParam = UpdateMetadataParam.builder()
.metadata(metadata)
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.build();
Run run = runs.update("threadId", "runId", updateParam);
}
}
Parâmetro | Tipo | Valor padrão | Descrição |
|---|---|---|---|
run_id | str | - | ID da run a ser atualizada. |
thread_id | str | - | ID da thread para a run. |
metadata | Dict | None | Informações sobre a associação do assistente. |
workspace | str | None | O Workspace ID do Model Studio. Este parâmetro é necessário apenas quando a api_key for uma chave de API de sub-workspace. |
api_key | str | None | Para a chave de API do Alibaba Cloud Model Studio, recomendamos configurá-la como uma variável de ambiente. |
Envie saídas de ferramentas e continue uma run
Quando uma run tem o statusstatus: "requires_action" e seu required_action.type é submit_tool_outputs, utilize este endpoint para enviar as saídas das chamadas de ferramentas. Todas as chamadas de ferramentas devem estar concluídas e suas saídas devem ser enviadas em uma única solicitação.
- HTTP
- SDK
curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/threads/thread_9157dfad-71fd-4add-b7a9-1afa452d2d67/runs/run_99935dbd-e731-4bad-b450-60d9d6bf9a44/submit_tool_outputs' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
"tool_outputs": [
{
"tool_call_id": "",
"output": "rain"
}
]
}'
curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/threads/thread_9157dfad-71fd-4add-b7a9-1afa452d2d67/runs/run_99935dbd-e731-4bad-b450-60d9d6bf9a44/submit_tool_outputs' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
"tool_outputs": [
{
"tool_call_id": "",
"output": "rain"
}
],
"stream": true
}'
Nome do parâmetro | Descrição | Tipo | Obrigatório |
|---|---|---|---|
thread_id | ID da thread a ser modificada | string | Sim |
run_id | ID da run a ser modificada. | string | Sim |
tool_outputs | Lista de resultados de chamadas de ferramentas a serem retornados ao Assistente. | array | Sim |
tool_outputs[].tool_call_id | ID da chamada de ferramenta. | string | Não |
tool_outputs[].output | Saída a ser retornada pela ferramenta. | string | Sim |
stream | Especifica se o resultado deve ser retornado no modo de streaming. | boolean | Não |
{
"id": "run_99935dbd-e731-4bad-b450-60d9d6bf9a44",
"object": "thread.run",
"created_at": 1711519089921,
"thread_id": "thread_9157dfad-71fd-4add-b7a9-1afa452d2d67",
"assistant_id": "asst_ce66cfa8-b2f8-4e4c-8e17-2c335145be42",
"status": "in_progress",
"required_action": {
"type": "submit_tool_outputs",
"submit_tool_outputs": {
"tool_calls": [
{
"function": {
"name": "get_current_weather",
"arguments": "{\"location\": \"Xi'an\"}"
},
"id": "",
"type": "function"
}
]
}
},
"last_error": {},
"expires_at": 0,
"started_at": 0,
"cancelled_at": 0,
"failed_at": 0,
"completed_at": 0,
"model": "qwen-max",
"instructions": "You are an intelligent assistant. You can call different tools based on user needs to provide answers. Use tools as appropriate.",
"tools": [
{
"type": "text_to_image"
},
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA"
},
"unit": {
"type": "string",
"enum": [
"celsius",
"fahrenheit"
]
}
},
"required": [
"location"
]
}
}
}
],
"metadata": {},
"usage": null,
"request_id": "792c29a2-e771-9840-9d99-df4f892badd0"
}
event:thread.run.step.completed
data:{"id":"step_74a8b5e2-3d23-41d9-b5c8-9bf3ba3839d0","object":"thread.run.step","created_at":1714448906129,"assistant_id":"asst_5378d83a-f612-4fc1-9034-915351d67d98","thread_id":"thread_c6ac2eb0-ed95-4834-befb-ea66eba85b9f","run_id":"run_36d6fba9-0bf1-47f5-8e7b-f8c8140beda9","type":"tool_calls","status":"completed","step_details":{"type":"tool_calls","tool_calls":[{"id":"","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\": \"Xi'an\"}","output":"rain"}}]},"last_error":null,"expired_at":null,"cancelled_at":null,"failed_at":null,"completed_at":null,"metadata":{},"usage":null,"request_id":"6d1573a4-3cbb-9066-99cc-7247ec17cb30"}
event:thread.run.queued
data:{"id":"run_36d6fba9-0bf1-47f5-8e7b-f8c8140beda9","object":"thread.run","created_at":1714448903737,"thread_id":"thread_c6ac2eb0-ed95-4834-befb-ea66eba85b9f","assistant_id":"asst_5378d83a-f612-4fc1-9034-915351d67d98","status":"queued","required_action":null,"last_error":null,"expires_at":null,"started_at":null,"cancelled_at":null,"failed_at":null,"completed_at":null,"model":"qwen-max","instructions":"You are an intelligent assistant. You can call different tools based on user needs to provide answers. Use tools as appropriate.","tools":[{"type":"text_to_image"},{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"file_ids":[],"metadata":{},"usage":null,"temperature":null,"top_p":null,"top_k":null,"max_tokens":null,"truncation_strategy":null,"request_id":"6d1573a4-3cbb-9066-99cc-7247ec17cb30"}
event:thread.run.in_progress
data:{"id":"run_36d6fba9-0bf1-47f5-8e7b-f8c8140beda9","object":"thread.run","created_at":1714448903737,"thread_id":"thread_c6ac2eb0-ed95-4834-befb-ea66eba85b9f","assistant_id":"asst_5378d83a-f612-4fc1-9034-915351d67d98","status":"in_progress","required_action":null,"last_error":null,"expires_at":null,"started_at":null,"cancelled_at":null,"failed_at":null,"completed_at":null,"model":"qwen-max","instructions":"You are an intelligent assistant. You can call different tools based on user needs to provide answers. Use tools as appropriate.","tools":[{"type":"text_to_image"},{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"file_ids":[],"metadata":{},"usage":null,"temperature":null,"top_p":null,"top_k":null,"max_tokens":null,"truncation_strategy":null,"request_id":"6d1573a4-3cbb-9066-99cc-7247ec17cb30"}
event:thread.run.step.created
data:{"id":"step_d74df5eb-dcb8-4fc2-a943-d06ccda0e2e3","object":"thread.run.step","created_at":1714449008828,"assistant_id":"asst_5378d83a-f612-4fc1-9034-915351d67d98","thread_id":"thread_c6ac2eb0-ed95-4834-befb-ea66eba85b9f","run_id":"run_36d6fba9-0bf1-47f5-8e7b-f8c8140beda9","type":"message_creation","status":"in_progress","step_details":{"type":"message_creation","message_creation":{"message_id":"message_965b3bb5-dbe2-434a-a36e-f7cda3845360"}},"last_error":null,"expired_at":null,"cancelled_at":null,"failed_at":null,"completed_at":null,"metadata":{},"usage":null,"request_id":"6d1573a4-3cbb-9066-99cc-7247ec17cb30"}
event:thread.run.step.in_progress
data:{"id":"step_d74df5eb-dcb8-4fc2-a943-d06ccda0e2e3","object":"thread.run.step","created_at":1714449008828,"assistant_id":"asst_5378d83a-f612-4fc1-9034-915351d67d98","thread_id":"thread_c6ac2eb0-ed95-4834-befb-ea66eba85b9f","run_id":"run_36d6fba9-0bf1-47f5-8e7b-f8c8140beda9","type":"message_creation","status":"in_progress","step_details":{"type":"message_creation","message_creation":{"message_id":"message_965b3bb5-dbe2-434a-a36e-f7cda3845360"}},"last_error":null,"expired_at":null,"cancelled_at":null,"failed_at":null,"completed_at":null,"metadata":{},"usage":null,"request_id":"6d1573a4-3cbb-9066-99cc-7247ec17cb30"}
event:thread.message.created
data:{"id":"message_965b3bb5-dbe2-434a-a36e-f7cda3845360","object":"thread.message","created_at":1714449008828,"thread_id":"thread_c6ac2eb0-ed95-4834-befb-ea66eba85b9f","incomplete_details":null,"completed_at":null,"incomplete_at":null,"role":"assistant","content":[],"assistant_id":"asst_5378d83a-f612-4fc1-9034-915351d67d98","run_id":"run_36d6fba9-0bf1-47f5-8e7b-f8c8140beda9","file_ids":[],"metadata":{},"request_id":"6d1573a4-3cbb-9066-99cc-7247ec17cb30"}
event:thread.message.in_progress
data:{"id":"message_965b3bb5-dbe2-434a-a36e-f7cda3845360","object":"thread.message","created_at":1714449008828,"thread_id":"thread_c6ac2eb0-ed95-4834-befb-ea66eba85b9f","incomplete_details":null,"completed_at":null,"incomplete_at":null,"role":"assistant","content":[],"assistant_id":"asst_5378d83a-f612-4fc1-9034-915351d67d98","run_id":"run_36d6fba9-0bf1-47f5-8e7b-f8c8140beda9","file_ids":[],"metadata":{},"request_id":"6d1573a4-3cbb-9066-99cc-7247ec17cb30"}
event:thread.message.delta
data:{"id":"message_965b3bb5-dbe2-434a-a36e-f7cda3845360","object":"thread.message.delta","delta":{"role":"assistant","content":[{"type":"text","text":{"value":"The","annotations":[]}}],"file_ids":[]},"request_id":"6d1573a4-3cbb-9066-99cc-7247ec17cb30"}
event:thread.message.delta
data:{"id":"message_965b3bb5-dbe2-434a-a36e-f7cda3845360","object":"thread.message.delta","delta":{"role":"assistant","content":[{"type":"text","text":{"value":" current weather in Xi'an is","annotations":[]}}],"file_ids":[]},"request_id":"6d1573a4-3cbb-9066-99cc-7247ec17cb30"}
event:thread.message.delta
data:{"id":"message_965b3bb5-dbe2-434a-a36e-f7cda3845360","object":"thread.message.delta","delta":{"role":"assistant","content":[{"type":"text","text":{"value":" rainy.","annotations":[]}}],"file_ids":[]},"request_id":"6d1573a4-3cbb-9066-99cc-7247ec17cb30"}
event:thread.message.delta
data:{"id":"message_965b3bb5-dbe2-434a-a36e-f7cda3845360","object":"thread.message.delta","delta":{"role":"assistant","content":[{"type":"text","text":{"value":"","annotations":[]}}],"file_ids":[]},"request_id":"6d1573a4-3cbb-9066-99cc-7247ec17cb30"}
event:thread.message.completed
data:{"id":"message_965b3bb5-dbe2-434a-a36e-f7cda3845360","object":"thread.message","created_at":1714449008828,"thread_id":"thread_c6ac2eb0-ed95-4834-befb-ea66eba85b9f","incomplete_details":null,"completed_at":1714449009919,"incomplete_at":null,"role":"assistant","content":[{"type":"text","text":{"value":"The current weather in Xi'an is rainy.","annotations":[]}}],"assistant_id":"asst_5378d83a-f612-4fc1-9034-915351d67d98","run_id":"run_36d6fba9-0bf1-47f5-8e7b-f8c8140beda9","file_ids":[],"metadata":{},"request_id":"6d1573a4-3cbb-9066-99cc-7247ec17cb30"}
event:thread.run.step.completed
data:{"id":"step_d74df5eb-dcb8-4fc2-a943-d06ccda0e2e3","object":"thread.run.step","created_at":1714449008828,"assistant_id":"asst_5378d83a-f612-4fc1-9034-915351d67d98","thread_id":"thread_c6ac2eb0-ed95-4834-befb-ea66eba85b9f","run_id":"run_36d6fba9-0bf1-47f5-8e7b-f8c8140beda9","type":"message_creation","status":"completed","step_details":{"type":"message_creation","message_creation":{"message_id":"message_965b3bb5-dbe2-434a-a36e-f7cda3845360"}},"last_error":null,"expired_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1714449009919,"metadata":{},"usage":null,"request_id":"6d1573a4-3cbb-9066-99cc-7247ec17cb30"}
event:thread.run.completed
data:{"id":"run_36d6fba9-0bf1-47f5-8e7b-f8c8140beda9","object":"thread.run","created_at":1714448903737,"thread_id":"thread_c6ac2eb0-ed95-4834-befb-ea66eba85b9f","assistant_id":"asst_5378d83a-f612-4fc1-9034-915351d67d98","status":"completed","required_action":null,"last_error":null,"expires_at":null,"started_at":null,"cancelled_at":null,"failed_at":null,"completed_at":null,"model":"qwen-max","instructions":"You are an intelligent assistant. You can call different tools based on user needs to provide answers. Use tools as appropriate.","tools":[{"type":"text_to_image"},{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"file_ids":[],"metadata":{},"usage":{"input_tokens":439,"output_tokens":11,"total_tokens":450},"temperature":null,"top_p":null,"top_k":null,"max_tokens":null,"truncation_strategy":null,"request_id":"6d1573a4-3cbb-9066-99cc-7247ec17cb30"}
event:done
data:[DONE]
import json
import sys
from http import HTTPStatus
from dashscope import Assistants, Messages, Runs, Steps, Threads
def create_assistant():
# create assistant with information
assistant = Assistants.create(
model='qwen-max',
name='smart helper',
description='A tool helper.',
instructions='You are a helpful assistant. When asked a question, use tools wherever possible.', # noqa E501
tools=[{
'type': 'function',
'function': {
'name': 'big_add',
'description': 'Add to number',
'parameters': {
'type': 'object',
'properties': {
'left': {
'type': 'integer',
'description': 'The left operator'
},
'right': {
'type': 'integer',
'description': 'The right operator.'
}
},
'required': ['left', 'right']
}
}
}],
)
return assistant
def verify_status_code(res):
if res.status_code != HTTPStatus.OK:
sys.exit(res.status_code)
if __name__ == '__main__':
# create assistant
assistant = create_assistant()
print(assistant)
verify_status_code(assistant)
# create thread.
thread = Threads.create()
print(thread)
verify_status_code(thread)
# create a message.
message = Messages.create(thread.id, content='bigAdd 87787 to 788988737.')
print(message)
verify_status_code(message)
# create run to run message
message_run = Runs.create(thread.id, assistant_id=assistant.id)
print(message_run)
verify_status_code(message_run)
# get run statue
run_status = Runs.get(message_run.id, thread_id=thread.id)
print(run_status)
verify_status_code(run_status)
# wait for run completed or requires_action
run_status = Runs.wait(message_run.id, thread_id=thread.id)
print(run_status)
# if prompt input tool result, submit tool result.
# should call big_add
if run_status.required_action:
tool_outputs = [{
'tool_call_id': # optional
'',
'output':
'789076524'
}]
run = Runs.submit_tool_outputs(message_run.id,
thread_id=thread.id,
tool_outputs=tool_outputs)
print(run)
verify_status_code(run)
# wait for run completed or requires_action
run_status = Runs.wait(message_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)
run_steps = Steps.list(run.id, thread_id=thread.id)
print(run_steps)
verify_status_code(run_steps)
# 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))
import com.alibaba.dashscope.assistants.Assistant;
import com.alibaba.dashscope.assistants.AssistantParam;
import com.alibaba.dashscope.tools.ToolFunction;
import com.alibaba.dashscope.assistants.Assistants;
import com.alibaba.dashscope.common.GeneralListParam;
import com.alibaba.dashscope.common.ListResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.InvalidateParameter;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.threads.AssistantThread;
import com.alibaba.dashscope.threads.ThreadParam;
import com.alibaba.dashscope.threads.Threads;
import com.alibaba.dashscope.threads.messages.Messages;
import com.alibaba.dashscope.threads.messages.TextMessageParam;
import com.alibaba.dashscope.threads.messages.ThreadMessage;
import com.alibaba.dashscope.threads.runs.RequiredAction;
import com.alibaba.dashscope.threads.runs.Run;
import com.alibaba.dashscope.threads.runs.RunParam;
import com.alibaba.dashscope.threads.runs.Runs;
import com.alibaba.dashscope.threads.runs.SubmitToolOutputsParam;
import com.alibaba.dashscope.threads.runs.ToolOutput;
import com.alibaba.dashscope.tools.FunctionDefinition;
import com.alibaba.dashscope.tools.ToolCallBase;
import com.alibaba.dashscope.utils.JsonUtils;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.victools.jsonschema.generator.Option;
import com.github.victools.jsonschema.generator.OptionPreset;
import com.github.victools.jsonschema.generator.SchemaGenerator;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfig;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder;
import com.github.victools.jsonschema.generator.SchemaVersion;
import com.alibaba.dashscope.tools.ToolCallFunction;
public class AssistantFunctionCall {
public class AddFunctionTool {
private int left;
private int right;
public AddFunctionTool(int left, int right) {
this.left = left;
this.right = right;
}
public int call() {
return left + right;
}
}
static ToolFunction buildFunction() {
SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2020_12,
OptionPreset.PLAIN_JSON);
SchemaGeneratorConfig config = configBuilder.with(Option.EXTRA_OPEN_API_FORMAT_VALUES)
.without(Option.FLATTENED_ENUMS_FROM_TOSTRING).build();
SchemaGenerator generator = new SchemaGenerator(config);
// generate jsonSchema of function.
ObjectNode jsonSchema = generator.generateSchema(AddFunctionTool.class);
// call with tools of function call, jsonSchema.toString() is jsonschema String.
FunctionDefinition fd = FunctionDefinition.builder().name("add").description("add two number")
.parameters(JsonUtils.parseString(jsonSchema.toString()).getAsJsonObject()).build();
return ToolFunction.builder().function(fd).build();
}
static public Assistant createAssistant() throws ApiException, NoApiKeyException{
AssistantParam assistantParam = AssistantParam.builder()
.model("qwen-max") // model must be set.
.description("a helper assistant")
.name("system") // name must be set
.instructions("You are a helpful assistant. When asked a question, use tools wherever possible.")
.tool(buildFunction())
.build();
Assistants assistants = new Assistants();
return assistants.create(assistantParam);
}
static public void run(String assistantId) throws ApiException, NoApiKeyException, InvalidateParameter, InputRequiredException, InterruptedException{
// create a thread
Threads threads = new Threads();
AssistantThread assistantThread = threads.create(ThreadParam.builder().build());
Runs runs = new Runs();
// create a new message
TextMessageParam textMessageParam = TextMessageParam.builder().role("user").content("Add 87787 to 788988737.").build();
Messages messages = new Messages();
ThreadMessage threadMessage = messages.create(assistantThread.getId(), textMessageParam);
System.out.println(threadMessage);
RunParam runParam = RunParam.builder().assistantId(assistantId).build();
Run run = runs.create(assistantThread.getId(), runParam);
while(true){
if(run.getStatus().equals(Run.Status.CANCELLED) ||
run.getStatus().equals(Run.Status.COMPLETED) ||
run.getStatus().equals(Run.Status.FAILED) ||
run.getStatus().equals(Run.Status.REQUIRES_ACTION)||
run.getStatus().equals(Run.Status.EXPIRED)){
break;
}else{
Thread.sleep(1000);
}
run = runs.retrieve(assistantThread.getId(), run.getId());
}
if(run.getStatus().equals(Run.Status.REQUIRES_ACTION)){
// submit action output.
RequiredAction requiredAction = run.getRequiredAction();
if(requiredAction.getType().equals("submit_tool_outputs")){
ToolCallBase toolCall = requiredAction.getSubmitToolOutputs().getToolCalls().get(0);
if (toolCall.getType().equals("function")) {
// get function call name and argument, both String.
String functionName = ((ToolCallFunction) toolCall).getFunction().getName();
String functionId = ((ToolCallFunction)toolCall).getId();
String functionArgument = ((ToolCallFunction) toolCall).getFunction().getArguments();
if (functionName.equals("add")) {
// Create the function object.
AddFunctionTool addFunction =
JsonUtils.fromJson(functionArgument, AddFunctionTool.class);
// call function.
int sum = addFunction.call();
System.out.println(sum);
SubmitToolOutputsParam submitToolOutputsParam = SubmitToolOutputsParam.builder()
.toolOutput(ToolOutput.builder().toolCallId(functionId).output(String.valueOf(sum)).build())
.build();
run = runs.submitToolOutputs(assistantThread.getId(), run.getId(), submitToolOutputsParam);
}
}
}
}
while(true){
if(run.getStatus().equals(Run.Status.CANCELLED) ||
run.getStatus().equals(Run.Status.COMPLETED) ||
run.getStatus().equals(Run.Status.FAILED) ||
run.getStatus().equals(Run.Status.REQUIRES_ACTION)||
run.getStatus().equals(Run.Status.EXPIRED)){
break;
}else{
Thread.sleep(1000);
}
run = runs.retrieve(assistantThread.getId(), run.getId());
}
GeneralListParam listParam = GeneralListParam.builder().limit(100l).build();
ListResult<ThreadMessage> threadMessages = messages.list(assistantThread.getId(), listParam);
for(ThreadMessage threadMessage2: threadMessages.getData()){
System.out.println(threadMessage2);
}
}
public static void main(String[] args) throws ApiException, NoApiKeyException, InputRequiredException, InvalidateParameter, InterruptedException {
Assistant assistant = createAssistant();
run(assistant.getId());
}
}
import json
import sys
from http import HTTPStatus
import dashscope
from dashscope import Assistants, Messages, Runs, Steps, Threads
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 tool helper.',
instructions='You are a helpful assistant. When asked a question, use tools wherever possible.', # noqa E501
tools=[{
'type': 'function',
'function': {
'name': 'big_add',
'description': 'Add to number',
'parameters': {
'type': 'object',
'properties': {
'left': {
'type': 'integer',
'description': 'The left operator'
},
'right': {
'type': 'integer',
'description': 'The right operator.'
}
},
'required': ['left', 'right']
}
}
}],
)
return assistant
def verify_status_code(res):
if res.status_code != HTTPStatus.OK:
sys.exit(res.status_code)
if __name__ == '__main__':
# create assistant
assistant = create_assistant()
print(assistant)
verify_status_code(assistant)
# create thread.
thread = Threads.create()
print(thread)
verify_status_code(thread)
# create a message.
message = Messages.create(thread.id, content='bigAdd 87787 to 788988737.')
print(message)
verify_status_code(message)
# create run to run message
message_run = Runs.create(thread.id, assistant_id=assistant.id)
print(message_run)
verify_status_code(message_run)
# get run statue
run_status = Runs.get(message_run.id, thread_id=thread.id)
print(run_status)
verify_status_code(run_status)
# wait for run completed or requires_action
run_status = Runs.wait(message_run.id, thread_id=thread.id)
print(run_status)
# if prompt input tool result, submit tool result.
# should call big_add
if run_status.required_action:
tool_outputs = [{
'tool_call_id':
run_status.required_action.submit_tool_outputs.tool_calls[0].id,
'output':
'789076524'
}]
run = Runs.submit_tool_outputs(message_run.id,
thread_id=thread.id,
tool_outputs=tool_outputs)
print(run)
verify_status_code(run)
# wait for run completed or requires_action
run_status = Runs.wait(message_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)
run_steps = Steps.list(run.id, thread_id=thread.id)
print(run_steps)
verify_status_code(run_steps)
# 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))
import com.alibaba.dashscope.assistants.Assistant;
import com.alibaba.dashscope.assistants.AssistantParam;
import com.alibaba.dashscope.tools.ToolFunction;
import com.alibaba.dashscope.assistants.Assistants;
import com.alibaba.dashscope.common.GeneralListParam;
import com.alibaba.dashscope.common.ListResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.InvalidateParameter;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.threads.AssistantThread;
import com.alibaba.dashscope.threads.ThreadParam;
import com.alibaba.dashscope.threads.Threads;
import com.alibaba.dashscope.threads.messages.Messages;
import com.alibaba.dashscope.threads.messages.TextMessageParam;
import com.alibaba.dashscope.threads.messages.ThreadMessage;
import com.alibaba.dashscope.threads.runs.RequiredAction;
import com.alibaba.dashscope.threads.runs.Run;
import com.alibaba.dashscope.threads.runs.RunParam;
import com.alibaba.dashscope.threads.runs.Runs;
import com.alibaba.dashscope.threads.runs.SubmitToolOutputsParam;
import com.alibaba.dashscope.threads.runs.ToolOutput;
import com.alibaba.dashscope.tools.FunctionDefinition;
import com.alibaba.dashscope.tools.ToolCallBase;
import com.alibaba.dashscope.utils.JsonUtils;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.victools.jsonschema.generator.Option;
import com.github.victools.jsonschema.generator.OptionPreset;
import com.github.victools.jsonschema.generator.SchemaGenerator;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfig;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder;
import com.github.victools.jsonschema.generator.SchemaVersion;
import com.alibaba.dashscope.tools.ToolCallFunction;
import com.alibaba.dashscope.utils.Constants;
public class AssistantFunctionCall {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public class AddFunctionTool {
private int left;
private int right;
public AddFunctionTool(int left, int right) {
this.left = left;
this.right = right;
}
public int call() {
return left + right;
}
}
static ToolFunction buildFunction() {
SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2020_12,
OptionPreset.PLAIN_JSON);
SchemaGeneratorConfig config = configBuilder.with(Option.EXTRA_OPEN_API_FORMAT_VALUES)
.without(Option.FLATTENED_ENUMS_FROM_TOSTRING).build();
SchemaGenerator generator = new SchemaGenerator(config);
// generate jsonSchema of function.
ObjectNode jsonSchema = generator.generateSchema(AddFunctionTool.class);
// call with tools of function call, jsonSchema.toString() is jsonschema String.
FunctionDefinition fd = FunctionDefinition.builder().name("add").description("add two number")
.parameters(JsonUtils.parseString(jsonSchema.toString()).getAsJsonObject()).build();
return ToolFunction.builder().function(fd).build();
}
static public Assistant createAssistant() throws ApiException, NoApiKeyException{
AssistantParam assistantParam = AssistantParam.builder()
.model("qwen-max") // model must be set.
.description("a helper assistant")
.name("system") // name must be set
.instructions("You are a helpful assistant. When asked a question, use tools wherever possible.")
.tool(buildFunction())
.build();
Assistants assistants = new Assistants();
return assistants.create(assistantParam);
}
static public void run(String assistantId) throws ApiException, NoApiKeyException, InvalidateParameter, InputRequiredException, InterruptedException{
// create a thread
Threads threads = new Threads();
AssistantThread assistantThread = threads.create(ThreadParam.builder().build());
Runs runs = new Runs();
// create a new message
TextMessageParam textMessageParam = TextMessageParam.builder().role("user").content("Add 87787 to 788988737.").build();
Messages messages = new Messages();
ThreadMessage threadMessage = messages.create(assistantThread.getId(), textMessageParam);
System.out.println(threadMessage);
RunParam runParam = RunParam.builder().assistantId(assistantId).build();
Run run = runs.create(assistantThread.getId(), runParam);
while(true){
if(run.getStatus().equals(Run.Status.CANCELLED) ||
run.getStatus().equals(Run.Status.COMPLETED) ||
run.getStatus().equals(Run.Status.FAILED) ||
run.getStatus().equals(Run.Status.REQUIRES_ACTION)||
run.getStatus().equals(Run.Status.EXPIRED)){
break;
}else{
Thread.sleep(1000);
}
run = runs.retrieve(assistantThread.getId(), run.getId());
}
if(run.getStatus().equals(Run.Status.REQUIRES_ACTION)){
// submit action output.
RequiredAction requiredAction = run.getRequiredAction();
if(requiredAction.getType().equals("submit_tool_outputs")){
ToolCallBase toolCall = requiredAction.getSubmitToolOutputs().getToolCalls().get(0);
if (toolCall.getType().equals("function")) {
// get function call name and argument, both String.
String functionName = ((ToolCallFunction) toolCall).getFunction().getName();
String functionId = ((ToolCallFunction)toolCall).getId();
String functionArgument = ((ToolCallFunction) toolCall).getFunction().getArguments();
if (functionName.equals("add")) {
// Create the function object.
AddFunctionTool addFunction =
JsonUtils.fromJson(functionArgument, AddFunctionTool.class);
// call function.
int sum = addFunction.call();
System.out.println(sum);
SubmitToolOutputsParam submitToolOutputsParam = SubmitToolOutputsParam.builder()
.toolOutput(ToolOutput.builder().toolCallId(functionId).output(String.valueOf(sum)).build())
.build();
run = runs.submitToolOutputs(assistantThread.getId(), run.getId(), submitToolOutputsParam);
}
}
}
}
while(true){
if(run.getStatus().equals(Run.Status.CANCELLED) ||
run.getStatus().equals(Run.Status.COMPLETED) ||
run.getStatus().equals(Run.Status.FAILED) ||
run.getStatus().equals(Run.Status.REQUIRES_ACTION)||
run.getStatus().equals(Run.Status.EXPIRED)){
break;
}else{
Thread.sleep(1000);
}
run = runs.retrieve(assistantThread.getId(), run.getId());
}
GeneralListParam listParam = GeneralListParam.builder().limit(100l).build();
ListResult<ThreadMessage> threadMessages = messages.list(assistantThread.getId(), listParam);
for(ThreadMessage threadMessage2: threadMessages.getData()){
System.out.println(threadMessage2);
}
}
public static void main(String[] args) throws ApiException, NoApiKeyException, InputRequiredException, InvalidateParameter, InterruptedException {
Assistant assistant = createAssistant();
run(assistant.getId());
}
}
Aguardar a conclusão de uma run
Aguarda a conclusão da execução de uma run. A run é retornada em seu estado final. Os estados finais incluem 'cancelled', 'failed', 'completed', 'expired' e 'requires_action'.- SDK
from dashscope import Runs
import os
run = Runs.wait(
'run_id',
# We recommend that you configure the environment variable first. 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"),
thread_id='thread_id'
)
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.InvalidateParameter;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.threads.runs.Run;
import com.alibaba.dashscope.threads.runs.Runs;
public class AssistantFunctionCall {
public static void main(String[] args) throws ApiException, NoApiKeyException, InputRequiredException, InvalidateParameter, InterruptedException {
Runs runs = new Runs();
// We recommend that you configure the environment variable first. If you have not configured the environment variable, replace the following line with your Model Studio API key: apiKey("sk-xxx")
String apiKey = System.getenv("DASHSCOPE_API_KEY");
Run run = runs.retrieve("thread_id", "run_id", apiKey);
while(true){
if(run.getStatus().equals(Run.Status.CANCELLED) ||
run.getStatus().equals(Run.Status.COMPLETED) ||
run.getStatus().equals(Run.Status.FAILED) ||
run.getStatus().equals(Run.Status.REQUIRES_ACTION)||
run.getStatus().equals(Run.Status.EXPIRED)){
break;
}else{
Thread.sleep(1000);
}
run = runs.retrieve("thread_id", run.getId());
}
}
}
import dashscope
from dashscope import Runs
import os
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
run = Runs.wait(
'run_id',
# We recommend that you configure the environment variable first. 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"),
thread_id='thread_id'
)
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.InvalidateParameter;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.threads.runs.Run;
import com.alibaba.dashscope.threads.runs.Runs;
import com.alibaba.dashscope.utils.Constants;
public class AssistantFunctionCall {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void main(String[] args) throws ApiException, NoApiKeyException, InputRequiredException, InvalidateParameter, InterruptedException {
Runs runs = new Runs();
// We recommend that you configure the environment variable first. If you have not configured the environment variable, replace the following line with your Model Studio API key: apiKey("sk-xxx")
String apiKey = System.getenv("DASHSCOPE_API_KEY");
Run run = runs.retrieve("thread_id", "run_id", apiKey);
while(true){
if(run.getStatus().equals(Run.Status.CANCELLED) ||
run.getStatus().equals(Run.Status.COMPLETED) ||
run.getStatus().equals(Run.Status.FAILED) ||
run.getStatus().equals(Run.Status.REQUIRES_ACTION)||
run.getStatus().equals(Run.Status.EXPIRED)){
break;
}else{
Thread.sleep(1000);
}
run = runs.retrieve("thread_id", run.getId());
}
}
}
Parâmetro | Tipo | Valor padrão | Descrição |
|---|---|---|---|
run_id | string | - | ID da run a ser cancelada. |
thread_id | string | - | ID da thread para a run. |
workspace | string | None | O Workspace ID do Model Studio. Este parâmetro é necessário apenas quando a api_key for uma chave de API de sub-workspace. |
api_key | string | None | Para a chave de API do Alibaba Cloud Model Studio, recomendamos defini-la como uma variável de ambiente (Este tópico está programado para ser despublicado e será mesclado em 'Configurar chave de API'). |
Objeto run
Representa uma execução em andamento em uma thread.Exemplo de objeto
{
"assistant_id": "[REDACTED]",
"cancelled_at": null,
"completed_at": null,
"created_at": 1735026246751,
"enable_search": null,
"expires_at": null,
"failed_at": null,
"file_ids": [],
"id": "[REDACTED]",
"instructions": "you are a helpful assistant",
"last_error": null,
"max_tokens": null,
"metadata": {},
"model": "qwen-plus",
"object": "thread.run",
"request_id": "[REDACTED]",
"required_action": null,
"started_at": null,
"status": "in_progress",
"status_code": 200,
"stop": "",
"temperature": null,
"thread_id": "[REDACTED]",
"tool_choice": "auto",
"tools": [],
"top_k": null,
"top_p": null,
"truncation_strategy": null,
"usage": null
}
Atributos do objeto
Nome do parâmetro | Tipo | Descrição |
|---|---|---|
id | string | Identificador exclusivo da execução. |
assistant_id | string | ID do assistente associado a esta execução. |
cancelled_at | integer | Timestamp UNIX de 13 dígitos (em milissegundos) que indica quando a execução foi cancelada. |
completed_at | integer | Timestamp UNIX de 13 dígitos (em milissegundos) que marca a conclusão da execução. |
created_at | integer | Timestamp UNIX de 13 dígitos (em milissegundos) correspondente ao momento de criação da execução. |
expires_at | integer | Timestamp UNIX de 13 dígitos (em milissegundos) que define a expiração da execução. |
failed_at | integer | Timestamp UNIX de 13 dígitos (em milissegundos) registrado quando ocorre falha na execução. |
instructions | string | Instruções aplicadas à execução. |
metadata | map | Conjunto de até 16 pares chave-valor anexáveis a um objeto, utilizado para armazenar informações adicionais em formato estruturado. A chave aceita no máximo 64 caracteres e o valor até 512 caracteres. |
last_error | string | Último erro associado a esta execução. Retorna nulo caso não tenham ocorrido erros. |
model | string | Nome do modelo utilizado na execução. |
object | string | Tipo do objeto, sempre definido como thread.run. |
required_action | object | Indica a ação necessária para a execução, como o envio de saídas de ferramentas. |
started_at | integer | Timestamp UNIX de 13 dígitos (em milissegundos) que registra o início da execução. |
status | string | Estado atual da execução: queued, in_progress, requires_action, cancelling, cancelled, failed, completed ou expired. |
thread_id | string | ID da thread desta execução. |
tools | array | Lista de ferramentas utilizadas durante a execução. |
usage | object | Estatísticas de uso de recursos. |
status_code | integer | Código de status HTTP. Observação: Este parâmetro é de uso interno e pode ser ignorado. |
FAQ
- P: Como cancelar uma execução em andamento? R: A API Assistant não oferece um endpoint específico para cancelar execuções. Implemente a lógica de cancelamento diretamente na sua aplicação.