You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过ngrok URL运行LangChain Ollama?遇404错误求助

问题分析与解决步骤

核心问题排查

1. 环境变量赋值语法错误

MAC终端执行的export OLLAMA_HOST = url存在空格,环境变量赋值不允许有空格,正确命令应为:

export OLLAMA_HOST=你的ngrok完整URL

示例:

export OLLAMA_HOST=https://abc123.ngrok.io

2. Ollama Python库调用路径错误

Ollama的API根路径为/api,初始化Ollama对象时必须将base_url指向ngrok URL的/api子路径,否则会访问错误端点触发404。根据你使用的库类型,修正代码:

  • 若使用LangChain的Ollama集成:
from langchain_community.llms import Ollama

# 末尾必须添加/api
ollama = Ollama(base_url="https://abc123.ngrok.io/api", model="llama2")
# 正确调用方式为invoke,而非直接调用对象
print(ollama.invoke("why is the sky blue"))
  • 若使用Ollama官方Python库:
import ollama

response = ollama.generate(
    model="llama2",
    prompt="why is the sky blue",
    options={"base_url": "https://abc123.ngrok.io"}
)
print(response['response'])

3. 确认ngrok转发状态

检查你的Python脚本输出,确认ngrok成功启动并生成有效URL,正常输出应包含类似内容:

ngrok by @inconshreveable                                                                                                                               (Ctrl+C to quit)

Session Status                online
Account                       你的账号名 (Plan: Free)
Version                       3.3.5
Region                        United States (us)
Latency                       74ms
Web Interface                 http://127.0.0.1:4040
Forwarding                    https://abc123.ngrok.io -> http://localhost:11434

Connections                   ttl     opn     rt1     rt5     p50     p90
                              0       0       0.00    0.00    0.00    0.00

若未看到Forwarding行,说明ngrok启动失败,检查认证令牌有效性或网络连接状态。

4. 远程Ollama服务的模型可用性

确保运行ollama serve的机器上已拉取llama2模型——需在远程机器执行ollama pull llama2,本地MAC终端拉取的模型不会同步到远程服务。

5. 验证端口监听状态

确认远程机器上的Ollama服务确实监听11434端口,执行Linux命令验证:

netstat -tulpn | grep 11434

额外注意事项

  • 无需在Python代码中重复安装ngrok,初始脚本已通过subprocess启动服务,重复安装会引发冲突。
  • ngrok免费版URL会定期变更,间隔一段时间测试时需重新获取最新转发地址。

内容的提问来源于stack exchange,提问作者Nok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 00:12:40