一、前言
? ? 在AI大模型百花齊放的時代,很多人都對新興技術(shù)充滿了熱情,都想嘗試一下。但是,實際上要入門AI技術(shù)的門檻非常高。除了需要高端設(shè)備,還需要面臨復(fù)雜的部署和安裝過程,這讓很多人望而卻步。不過,隨著開源技術(shù)的不斷進(jìn)步,使得入門AI變得越來越容易。通過使用Ollama,您可以快速體驗大語言模型的樂趣,不再需要擔(dān)心繁瑣的設(shè)置和安裝過程。
二、術(shù)語
2.1、Ollama
? ? 是一個強(qiáng)大的框架,用于在 Docker 容器中部署 LLM(大型語言模型)。它的主要功能是在 Docker 容器內(nèi)部署和管理 LLM 的促進(jìn)者,使該過程變得簡單。它可以幫助用戶快速在本地運行大模型,通過簡單的安裝指令,用戶可以執(zhí)行一條命令就在本地運行開源大型語言模型。
? ? Ollama 支持 GPU/CPU 混合模式運行,允許用戶根據(jù)自己的硬件條件(如 GPU、顯存、CPU 和內(nèi)存)選擇不同量化版本的大模型。它提供了一種方式,使得即使在沒有高性能 GPU 的設(shè)備上,也能夠運行大型模型。
2.2、Qwen1.5
? ? Qwen1.5 is the beta version of Qwen2, a transformer-based decoder-only language model pretrained on a large amount of data. In comparison with the previous released Qwen, the improvements include:
- 6 model sizes, including 0.5B, 1.8B, 4B, 7B, 14B, and 72B;
- Significant performance improvement in human preference for chat models;
- Multilingual support of both base and chat models;
- Stable support of 32K context length for models of all sizes
- No need of trust_remote_code.
三、前置條件
3.1、Ollama安裝
? ? 下載地址:Download Ollama on macOS
? ?
? ? 支持macOS、Linux以及windows,此處以windows操作系統(tǒng)為例:
? ? 點擊OllmaSetup.exe進(jìn)行安裝,當(dāng)前安裝版本為0.1.27
? ? 安裝完成后,在C:\Users\用戶名\AppData\Local\Ollama目錄下,有Ollama的配置及日志文件
? ? 也可以在右下角快速點開
? ??
? ? 查看版本
? ??
四、使用方式
4.1、運行Qwen1.5-1.8B-Chat模型
ollama run qwen:1.8b
五、測試
5.1、命令行方式測試
5.2、代碼方式測試
? ?默認(rèn)Ollama api會監(jiān)聽11434端口,可以使用命令進(jìn)行查看
? ??
netstat -ano | findstr 11434
? ? 安裝requests庫
pip install requests -i https://pypi.douban.com/simple
# -*- coding = utf-8 -*-
import json
import sys
import traceback
import logging
#######################日志配置#######################
import requests
from requests.adapters import HTTPAdapter
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s]: %(message)s', # 指定日志輸出格式
datefmt='%Y-%m-%d %H:%M:%S' # 指定日期時間格式
)
# 創(chuàng)建一個日志記錄器
formatter = logging.Formatter('%(asctime)s [%(levelname)s]: %(message)s') # 指定日志輸出格式
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
if sys.platform == "linux":
# 創(chuàng)建一個文件處理器,將日志寫入到文件中
file_handler = logging.FileHandler('/data/logs/app.log')
else:
# 創(chuàng)建一個文件處理器,將日志寫入到文件中
file_handler = logging.FileHandler('E:\\logs\\app.log')
file_handler.setFormatter(formatter)
# 創(chuàng)建一個控制臺處理器,將日志輸出到控制臺
# console_handler = logging.StreamHandler()
# console_handler.setFormatter(formatter)
# 將處理器添加到日志記錄器中
logger.addHandler(file_handler)
# logger.addHandler(console_handler)
DEFAULT_MODEL = "qwen:1.8b-chat"
DEFAULT_IP='127.0.0.1'
DEFAULT_PORT=11434
DEFAULT_MAX_TOKENS = 32768
DEFAULT_CONNECT_TIMEOUT=3
DEFAULT_REQUEST_TIMEOUT=60
DEFAULT_MAX_RETRIES=0
DEFAULT_POOLSIZE=100
class Model:
def __init__(self):
self.headers = {"User-Agent": "Test Client"}
self.s = requests.Session()
self.s.mount('http://', HTTPAdapter(pool_connections=DEFAULT_POOLSIZE, pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_MAX_RETRIES))
self.s.mount('https://', HTTPAdapter(pool_connections=DEFAULT_POOLSIZE, pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_MAX_RETRIES))
def chat(self, message, history=None, system=None, config=None, stream=True):
if config is None:
config = {'temperature': 0.45, 'top_p': 0.9, 'repetition_penalty': 1.2, 'max_tokens': DEFAULT_MAX_TOKENS,'n':1}
logger.info(f'config: {config}')
messages = []
if system is not None:
messages.append({"role": "system", "content": system})
if history is not None:
if len(history) > 0 and len(history) % 2 == 0:
for his in history:
user,assistant = his
user_obj = {"role": "user", "content": user}
assistant_obj = {"role": "assistant", "content": assistant}
messages.append(user_obj)
messages.append(assistant_obj)
if message is None:
raise RuntimeError("prompt不能為空!")
else:
messages.append({"role": "user", "content": message})
logger.info(messages)
try:
merge_pload = {"model": DEFAULT_MODEL, "messages": messages, **config}
logger.info(merge_pload)
response = self.s.post(f"http://{DEFAULT_IP}:{DEFAULT_PORT}/api/chat", headers=self.headers,
json=merge_pload, stream=stream, timeout=(DEFAULT_CONNECT_TIMEOUT, DEFAULT_REQUEST_TIMEOUT))
str = ''
for msg in response:
# logger.info(msg)
if msg and len(msg) > 0:
decode_msg = msg.decode('UTF-8')
if '\n' in decode_msg :
if len(str) == 0:
obj = json.loads(decode_msg)
if 'message' in obj:
content = obj['message']['content']
if content is not None:
yield content
else:
str = str + decode_msg
obj = json.loads(str)
if 'message' in obj:
content = obj['message']['content']
if content is not None:
str=''
yield content
else:
str = str + decode_msg
except Exception as e:
traceback.print_exc()
if __name__ == '__main__':
model = Model()
message = '我家有什么特產(chǎn)?'
system = 'You are a helpful assistant.'
history = [('hi,你好','你好!有什么我可以幫助你的嗎?'),('我家在廣州,很好玩哦','廣州是一個美麗的城市,有很多有趣的地方可以去。'),]
config = {'temperature': 0.45, 'top_p': 0.9, 'repetition_penalty': 1.2, 'max_tokens': 8192}
gen = model.chat(message=message, history=history, system=system, config=config, stream=True)
results = []
for value in gen:
results.append(value)
str = ''.join(results)
logger.info(str)
? 模型參數(shù):
?Ollama Api返回的數(shù)據(jù)格式以\n結(jié)尾,但由于流式返回,可能存在多行輸出再返回\n的情況:
測試結(jié)果:
六、附帶說明
6.1、各操作系統(tǒng)下的安裝步驟
? ? https://github.com/ollama/ollama
6.2、Ollama支持的模型庫
? ? https://ollama.com/library
? ??
6.3、運行各規(guī)格qwen模型的命令
https://registry.ollama.ai/library/qwen/tags
? ?
6.4、問題
? # 重試幾次或者換另外規(guī)格的模型
6.5、代碼中傳遞給Ollama Api的模型參數(shù),要和運行的模型一致,即
6.6、Ollama常用命令
# list
# show
# delete文章來源:http://www.zghlxwxcb.cn/news/detail-837306.html
等等,可以查閱:https://github.com/ollama/ollama/blob/main/cmd/cmd.go文章來源地址http://www.zghlxwxcb.cn/news/detail-837306.html
到了這里,關(guān)于開源模型應(yīng)用落地-工具使用篇-Ollama(六)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!