1、场景与目标
你是否厌倦了依赖在线AI绘图服务的收费和隐私风险?或者受限于公共API的固定Prompt模板,无法精准控制出图细节?本文将通过本地部署的Ollama(大模型) + Stable Diffusion WebUI,实现完全离线运行,无需联网,保护隐私。
2、环境准备
首先要在本地部署好本地AI和本地Stable Diffusion WebUI,关于这些的教程网上很多本文不过多赘述,本文主要分享如何让这两个联合调用。(仅个人学习成果,若有读者更优想法欢迎提出)
作者自己碰到的问题以及解决方法可以分享就是在终端部署的时候需要科学上网,但是没有开过的话终端可能无法使用代理,这个时候我们需要在终端或IDE修改配置文件。
nano ~/.zshrc
打开后然后添加以下内容:
# 设置 HTTP/HTTPS 代理
export http_proxy="http://127.0.0.1:7890"
export https_proxy="http://127.0.0.1:7890"
# 如果你使用的是 SOCKS5(如 Clash)
# export ALL_PROXY="socks5://127.0.0.1:7890"
然后就可以走正常流程部署。
3、本地AI的部署调用
正常来说,用Ollama部署本地AI,问答一般是在终端操作。但是为了方便自己开发更多的玩法可以在网页开发,本文用的是Django开发,其他框架开发大差不差。
3.1 在view.py中添加调用本地AI的视图
import requests
def ask_local_model(prompt):
"""调用本地模型接口,保留原始响应内容"""
try:
res = requests.post(
url="http://localhost:11434/api/generate",
"""下面参数凭个人自行切换"""
json={
"model": model_base, # 例如“deepseek-r1:32b”,看你自己下载的是哪个模型,替换进来。
"prompt": prompt,
"stream": False,
"max_tokens": 512
},
timeout=120
)
res.raise_for_status()
data = res.json()
if "response" in data:
return data["response"].strip()
return "模型响应中缺少 'response' 字段"
except Exception as e:
return f"请求模型失败:{str(e)}"
定义好这个函数后即可通过前端页面和后端路由调用本地AI。
3.2 在view.py中添加调用Stable Diffusion的视图
def generate_image(prompt, negative_prompt="", steps=20, width=512, height=512):
"""调用本地Stable Diffusion生成图片"""
try:
url = "http://127.0.0.1:7860/sdapi/v1/txt2img"
payload = {
"prompt": prompt,
"negative_prompt": negative_prompt,
"steps": steps,
"width": width,
"height": height
}
response = requests.post(url, json=payload, timeout=60)
response.raise_for_status()
result = response.json()
if 'images' in result and len(result['images']) > 0:
return result['images'][0] # 返回base64编码的图片
return None
except Exception as e:
print(f"生成图片失败: {str(e)}")
return None
@csrf_exempt
@require_POST
def generate_image_view(request):
"""处理图片生成请求"""
try:
data = json.loads(request.body)
prompt = data.get('prompt', '')
negative_prompt = data.get('negative_prompt', '')
width = int(data.get('width', 512))
height = int(data.get('height', 512))
if not prompt:
return JsonResponse({"error": "请输入提示词"}, status=400)
image_data = generate_image(prompt, negative_prompt, width=width, height=height)
if image_data:
return JsonResponse({"image": image_data})
return JsonResponse({"error": "图片生成失败"}, status=500)
except Exception as e:
return JsonResponse({"error": f"服务器错误: {str(e)}"}, status=500)
此代码对一些参数是写死的,而且只调用了文字生图的接口,读者可自行更改或者也可设计在图片生成前参数选择,也可通过类似的方法调用图生图等接口。定义好这些函数后即可通过前端页面和后端路由调用本地AI。
3.3 启动服务
在启动Stable Diffusion时切记要打开api服务,否则上文
url = “http://127.0.0.1:7860/sdapi/v1/txt2img”这个是无效的,
可以参考通过下方指令在终端打开Stable Diffusion的api服务
python3 launch.py --api --skip-torch-cuda-test --port 7860
开启后可以在http://127.0.0.1:7860/docs检查是否有/sdapi/v1/txt2img等接口,
(Win: Control+F,Mac:Command+F快捷键搜索检查)
4、效果展示
这是部署好的本地AI的首页放置了一个图片生成的功能在左下角。
这样就在本地AI中接入Stable Diffusion了!当然生成的图片的质量和选用的模型有关,这里作者推荐两个平台供读者下载自己喜欢的风格的模型。
https://civitai.com/
https://www.liblib.art/
5bei.cn大模型教程网










