
實時航班追蹤背后的技術:在線飛機追蹤器的工作原理
brew services start ollama
安裝完成后,Ollama將在11434端口監聽HTTP請求。可以通過訪問 http://localhost:11434/
驗證服務是否正常運行。
在安裝Ollama后,可以使用以下命令下載并配置所需的模型,例如 llama3.2
:
ollama pull llama3.2
這將下載llama3.2模型,準備好用于后續的應用程序集成。
Ollama允許通過命令行或HTTP API與本地托管的LLM進行交互。使用以下命令可以通過命令行運行模型:
ollama run llama3.2
使用HTTP API,可以發送JSON請求與模型交互:
curl http://localhost:11434/api/generate -d '{
"model": "llama3.2",
"prompt":"give me a chinese poem?"
}'
這種靈活性使得開發者可以將LLM輕松集成到各種應用中。
LangChain是一個旨在促進LLM與應用程序集成的框架,支持包括Ollama在內的各種聊天模型。它提供了一種靈活的表達語言(LangChain Expression Language)來實現鏈式操作。
要將Ollama與LangChain整合,首先需要安裝LangChain及其依賴項:
pip install -U langchain-ollama
官方文檔可在 LangChain文檔 中找到。
要在LangChain應用程序中使用Ollama,首先需要導入相應的模塊:
from langchain_community.llms import Ollama
然后,初始化一個Ollama模型實例:
llm = Ollama(model=”llama3.2″)
可以調用模型生成響應,例如:
llm.invoke(“Tell me a joke”)
LangChain還支持更復雜的操作,比如流式響應和使用提示模板。以下代碼展示了如何對模型的響應進行流處理:
from langchain.callbacks.manager import CallbackManager
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
llm = Ollama(
model="mistral", callback_manager=CallbackManager([StreamingStdOutCallbackHandler()])
)
llm("The first man on the summit of Mount Everest, the highest peak on Earth, was ...")
這種方法對于需要與LLM實時互動的應用特別有用。
LangChain提供了LangServe作為簡化應用程序運行的部署工具。LangServe是一個開源庫,使開發者可以輕松創建基于鏈的API服務器。
運行以下命令進行安裝:
pip install “langserve[all]”
以下代碼展示了如何使用LangServe部署LangChain應用程序:
from typing import List
from fastapi import FastAPI
from langchain.llms import Ollama
from langchain.output_parsers import CommaSeparatedListOutputParser
from langchain.prompts import PromptTemplate
from langserve import add_routes
import uvicorn
llama2 = Ollama(model="llama3.2")
template = PromptTemplate.from_template("Tell me a poem about {topic}.")
chain = template | llama2 | CommaSeparatedListOutputParser()
app = FastAPI(title="LangChain", version="1.0", description="The first server ever!")
add_routes(app, chain, path="/chain")
if __name__ == "__main__":
uvicorn.run(app, host="localhost", port=8000)
瀏覽器訪問 http://localhost:9001/chain/playground/
可以測試部署的應用。
通過集成Ollama和LangChain,開發者可以在不依賴外部API的情況下充分利用LLM的功能。這種方案不僅節省了成本,而且允許更靈活的定制。無論是構建聊天機器人、內容生成工具還是交互式應用程序,Ollama和LangChain都提供了眾多工具來實現這一目標。
brew install ollama
命令。