import os
from openai import OpenAI
client = OpenAI(
# If no environment variable, use: api_key="sk-xxx" (not recommended).
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following URL is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)
# Replace server_url with the SSE Endpoint that you got from a platform such as ModelScope
# If authentication is required, add the token from the corresponding platform to the headers
mcp_tool = {
"type": "mcp",
"server_protocol": "sse",
"server_label": "fetch",
"server_description": "Fetch MCP Server that provides web scraping capabilities. It can scrape the content of a specified URL and return it as text.",
"server_url": "https://mcp.api-inference.modelscope.net/xxx/sse",
}
stream = client.responses.create(
model="qwen3.8-max",
input="https://news.aibase.com/zh/news, what is the AI news today?",
tools=[mcp_tool],
stream=True
)
for event in stream:
# The model response starts
if event.type == "response.content_part.added":
print("[Model Response]")
# Streaming text output
elif event.type == "response.output_text.delta":
print(event.delta, end="", flush=True)
# The response is complete, output the usage
elif event.type == "response.completed":
usage = event.response.usage
print(f"\n\n[Token Usage] Input: {usage.input_tokens}, Output: {usage.output_tokens}, Total: {usage.total_tokens}")