如何在Python脚本中本地访问远程托管于Google Colab的Ollama模型?
我在Google Colab上成功运行了Ollama,使用下面的代码可以做到这一点,并且我可以通过在本地终端中输入 export OLLAMA_HOST=https://{url}.ngrok-free.app/
和 ollama run llama2
来访问它。
from google.colab import userdata
NGROK_AUTH_TOKEN = userdata.get('NGROK_AUTH_TOKEN')
# Download and install ollama to the system
!curl https://ollama.ai/install.sh | sh
!pip install aiohttp pyngrok
import os
import asyncio
# Set LD_LIBRARY_PATH so the system NVIDIA library
os.environ.update({'LD_LIBRARY_PATH': '/usr/lib64-nvidia'})
async def run_process(cmd):
print('>>> starting', *cmd)
p = await asyncio.subprocess.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
async def pipe(lines):
async for line in lines:
print(line.strip().decode('utf-8'))
await asyncio.gather(
pipe(p.stdout),
pipe(p.stderr),
)
#register an account at ngrok.com and create an authtoken and place it here
await asyncio.gather(
run_process(['ngrok', 'config', 'add-authtoken', NGROK_AUTH_TOKEN])
)
await asyncio.gather(
run_process(['ollama', 'serve']),
run_process(['ngrok', 'http', '--log', 'stderr', '11434']),
)
不过,我无法通过本地的Python脚本来访问Google Colab上的Ollama。我尝试过的代码是:
import requests
# Ngrok tunnel URL
ngrok_tunnel_url = "https://{url}.ngrok-free.app/"
# Define the request payload
payload = {
"model": "llama2",
"prompt": "Why is the sky blue?"
}
try:
# Send the request to the ngrok tunnel URL
response = requests.post(ngrok_tunnel_url, json=payload)
# Check the response status code
if response.status_code == 200:
print("Request successful:")
print("Response content:")
print(response.text)
else:
print("Error:", response.status_code)
except requests.exceptions.RequestException as e:
print("Error:", e)
但是返回了 Error: 403
的错误信息。
有没有人知道怎么解决这个问题,或者如何正确访问远程的Ollama实例?
1 个回答
0
1. 将主机头设置为 localhost:11434
我在终端和 Python 中都遇到了同样的问题。通过在 ngrok 命令中设置 --request-header="localhost:11434"
这个标志,问题就解决了。
我觉得出现 403 错误是因为传入的请求没有被隧道正确路由。这个问题最近被添加到了 Ollama 常见问题解答 中。
这是更新后的服务器代码:
await asyncio.gather(
run_process(['ollama', 'serve']),
run_process(['ngrok', 'http', '--log', 'stderr', '11434', '--host-header="localhost:11434"']), # Set host header
)