import os
from openai import OpenAI
client = OpenAI(
# 環境変数がない場合は、api_key="sk-xxx" を使用します (非推奨)。
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 次の URL はシンガポールリージョン用です。{WorkspaceId} を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)
# server_url を ModelScope などのプラットフォームから取得した SSE エンドポイントに置き換えてください。
# 認証が必要な場合は、対応するプラットフォームのトークンをヘッダーに追加してください。
mcp_tool = {
"type": "mcp",
"server_protocol": "sse",
"server_label": "fetch",
"server_description": "Web スクレイピング機能を提供する Fetch MCP サーバー。指定された URL のコンテンツをスクレイピングし、テキストとして返すことができます。",
"server_url": "https://mcp.api-inference.modelscope.net/xxx/sse",
}
stream = client.responses.create(
model="qwen3.8-max",
input="https://news.aibase.com/news, what is the AI news today?",
tools=[mcp_tool],
stream=True
)
for event in stream:
# モデルの応答が開始されます
if event.type == "response.content_part.added":
print("[Model Response]")
# テキスト出力のストリーミング
elif event.type == "response.output_text.delta":
print(event.delta, end="", flush=True)
# 応答が完了し、使用量を出力します
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}")