引言
随着 AIGC 技术的发展,通过 API 集成大模型能力已成为常见需求。本文将演示如何使用 Python 调用通义万相 2.1 的接口,实现文生图和文生文功能。重点在于环境配置、请求构建以及结果处理。
环境准备
确保已安装 Python 环境,并通过 pip 安装 requests 库,用于发送 HTTP 请求:
pip install requests
图像生成实现
我们需要定义 API 地址和密钥。注意保护密钥安全,不要硬编码在公开仓库中。这里封装了一个函数来处理请求逻辑。
import requests
import json
import os
# 替换为实际的 API 地址
api_url = "https://api.tongyiwanxiang2.1/image-generation"
# 替换为你自己的 API 密钥
api_key = "your_api_key"
def generate_image(prompt):
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
data = {
"prompt": prompt,
"width": 512,
"height": 512,
"num_images": 1
}
try:
response = requests.post(api_url, headers=headers, data=json.dumps(data))
response.raise_for_status()
result = response.json()
if "image_url" in result:
return result["image_url"]
else:
print("未获取到图像链接:", result)
return None
except requests.RequestException as e:
print(, e)


