通义万相 2.1 API 接入实战
AIGC 技术正在重塑内容创作的方式。对于开发者而言,直接调用成熟的模型 API 往往比从零训练更高效。本文将演示如何使用 Python 快速集成通义万相 2.1 接口,实现图像生成和文本生成的功能。
环境准备
在开始之前,确保你的开发环境中已安装 Python 3.x。我们需要使用 requests 库来处理 HTTP 请求。
pip install requests
密钥配置与安全
API 密钥是访问服务的凭证,务必妥善保管。建议将其存储在环境变量中,避免硬编码在代码里。
import os
import requests
import json
import urllib.request
# 从环境变量获取密钥,生产环境推荐此方式
api_key = os.getenv("TONGYI_API_KEY")
if not api_key:
raise ValueError("请设置环境变量 TONGYI_API_KEY")
# 实际使用时请替换为官方提供的真实地址
image_api_url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation"
text_api_url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image-generation/generation"
图像生成实现
文生图是 AIGC 的热门场景。我们封装一个函数来发送请求并处理响应。
def generate_image(prompt):
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
# 构建请求体,根据文档调整参数
data = {
"input": {
"prompt": prompt,
"size": "1024*1024",
"n": 1
},
"model": "wanx-v1"
}
try:
response = requests.post(image_api_url, headers=headers, json=data)
response.raise_for_status()
result = response.json()
# 解析返回结果,不同接口返回结构可能略有差异
if "output" in result and "text" in result["output"]:
return result["output"]["text"]
elif "images" in result:
return result["images"][0]
else:
print(f"未获取到有效数据:{result}")
return None
except requests.RequestException as e:
print(f"请求出错:{e}")
return None
调用示例:
prompt = "虚拟现实课堂上,学生身临历史战场学习历史"
image_url = generate_image(prompt)
if image_url:
print(f"生成成功,图片链接:{image_url}")
else:
print("生成失败")
保存生成的图像
拿到 URL 后,我们可以将图片下载到本地,方便后续使用。
def save_image(url, path):
try:
urllib.request.urlretrieve(url, path)
print(f"图像已保存到 {path}")
except Exception as e:
print(f"保存失败:{e}")
if image_url:
save_dir = "generated_images"
os.makedirs(save_dir, exist_ok=True)
save_path = os.path.join(save_dir, "generated_image.jpg")
save_image(image_url, save_path)
文本生成实现
除了图像,文本生成同样强大。逻辑与图像类似,主要区别在于输入输出格式。
def generate_text(prompt, max_length=500):
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
data = {
"input": {
"prompt": prompt,
"max_length": max_length
},
"parameters": {
"temperature": 0.7
}
}
try:
response = requests.post(text_api_url, headers=headers, json=data)
response.raise_for_status()
result = response.json()
if "output" in result and "text" in result["output"]:
return result["output"]["text"]
return None
except requests.RequestException as e:
print(f"文本生成请求出错:{e}")
return None
调试与注意事项
- 错误处理:网络波动或配额限制可能导致请求失败,务必加上
try-except块。 - 并发控制:如果需要在高并发场景下使用,注意平台的速率限制(Rate Limit),必要时增加重试机制。
- Prompt 工程:提示词的质量直接影响生成效果,多尝试不同的描述方式。
- 资源清理:定期清理本地生成的临时文件,避免占用过多磁盘空间。
通过上述步骤,你可以快速搭建起基于通义万相 2.1 的 AIGC 应用原型。这种模式无需维护庞大的算力集群,非常适合中小规模的业务验证和创意开发。

