使用 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
相关推荐
ellenwan202613 分钟前
近期AI协作量化实现,先补规则清晰度和流程完整性
人工智能·python
卷无止境19 分钟前
Python 类型注解与运行时反射:从原理到工程实践
后端·python
酷可达拉斯34 分钟前
Linux操作系统-shell编程(0)
linux·运维·服务器·python·云计算
W6580341936 分钟前
2026年AI编程工具实测横评:Claude Code v2.1、Cursor 3.0、Trae SOLO、Copilot、Windsurf 谁更好用?
python·copilot·ai编程
snow@li1 小时前
技术栈对应:Vue (前端) + SpringBoot (Java 后端) =》 Python 全场景配套
python
2501_909509101 小时前
DAY 28
开发语言·python
Token炼金师1 小时前
框架的擂台:LangChain、LlamaIndex、Dify、AutoGen 与 LangGraph —— 应用框架选型五局
人工智能·深度学习·llm
码云骑士1 小时前
71-Agent记忆系统-短期记忆-长期记忆-向量知识库三层架构
python·架构
卷无止境1 小时前
Python 的 exec 与 eval :动态代码执行的能力、风险与工程实践
后端·python
user-猴子1 小时前
从零构建 2048 游戏,解析“Python-Use”范式的完整闭环
开发语言·python·游戏