使用 Ollama 时遇到的问题

题意:

ImportError: cannot import name 'Ollama' from 'llama_index.llms' (unknown location) - installing dependencies does not solve the problem

Python 无法从 llama_index.llms 模块中导入名为 Ollama 的类或函数

问题背景:

I want to learn LLMs. I run Ollama with the following Docker Compose file - it's running:

我想学习大型语言模型(LLMs)。我使用以下Docker Compose文件运行Ollama,并且它正在运行:

python 复制代码
services:
  ollama:
    image: ollama/ollama:latest
    ports:
      - 11434:11434
    volumes:
      - ollama_data:/root/.ollama
    healthcheck:
      test: ollama list || exit 1
      interval: 10s
      timeout: 30s
      retries: 5
      start_period: 10s
  ollama-models-pull:
    image: curlimages/curl:8.6.0
    command: >-
      http://ollama:11434/api/pull -d '{"name": "mistral"}'
    depends_on:
      ollama:
        condition: service_healthy
volumes:
  ollama_data:

I would like to write a Python app, which will use ollama, and I found this piece of code:

我想编写一个使用Ollama的Python应用程序,我找到了以下代码片段:

python 复制代码
from llama_index.llms import Ollama, ChatMessage

llm = Ollama(model="mistral", base_url="http://127.0.0.1:11434")

messages = [
    ChatMessage(
        role="system", content="you are a multi lingual assistant used for translation and your job is to translate nothing more than that."
    ),
    ChatMessage(
        role="user", content="please translate message in triple tick to french ``` What is standard deviation?```"
    )
]
resp = llm.chat(messages=messages)
print(resp)

I installed all dependencies: 我安装了所有依赖

python 复制代码
python3 -m venv venv
source venv/bin/activate
pip install llama-index  
pip install llama-index-llms-ollama
pip install ollama-python

However, when I run the app, I got: 当我运行app时,得到以下信息:

python 复制代码
Traceback (most recent call last):
  File "/home/user/test.py", line 1, in <module>
    from llama_index.llms import Ollama, ChatMessage
ImportError: cannot import name 'Ollama' from 'llama_index.llms' (unknown location)

where can be the problem? 问题可能在哪里?

问题解决:

The correct way to import Ollama should be: 引入 ollama 的正确方式:

python 复制代码
from llama_index.llms.ollama import Ollama

For ChatMessage it should be: 引入 ChatMessage 的方式:

python 复制代码
from llama_index.core.llms import ChatMessage
相关推荐
likeGhee32 分钟前
python缓存装饰器实现方案
开发语言·python·缓存
项目題供诗44 分钟前
黑马python(二十五)
开发语言·python
读书点滴1 小时前
笨方法学python -练习14
java·前端·python
笑衬人心。1 小时前
Ubuntu 22.04 修改默认 Python 版本为 Python3 笔记
笔记·python·ubuntu
蛋仔聊测试1 小时前
Playwright 中 Page 对象的常用方法详解
python
前端付豪1 小时前
17、自动化才是正义:用 Python 接管你的日常琐事
后端·python
jioulongzi1 小时前
记录一次莫名奇妙的跨域502(badgateway)错误
开发语言·python
我爱一条柴ya2 小时前
【AI大模型】深入理解 Transformer 架构:自然语言处理的革命引擎
人工智能·ai·ai作画·ai编程·ai写作
破无差2 小时前
python实现简单的地图绘制与标记20250705
python
喜欢吃豆2 小时前
目前最火的agent方向-A2A快速实战构建(二): AutoGen模型集成指南:从OpenAI到本地部署的全场景LLM解决方案
后端·python·深度学习·flask·大模型