最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python ollama的搭建與使用流程分析

 更新時間:2024年04月01日 10:28:07   作者:yukai08008  
這篇文章主要介紹了Python ollama的搭建與使用流程分析,詳細介紹了ollama的安裝方式,本文結(jié)合實例給大家介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧

說明

做這個的主要目的是為了搭建Langchain的本地環(huán)境,使用LangChain讓LLM具備調(diào)用自定義函數(shù)的功能。

內(nèi)容

1 安裝server

以下將ollama的安裝方式,以及使用做一個簡單的說明(記錄)。之前對這個工具沒有了解,只是從快速實踐的角度上,給到一個參考。

最初是奔著LLM調(diào)用自定義函數(shù)/API這個功能去的,快速看下來,一個比較可行的方案是LangChain。

參考頁面

后來大致明白, langchain是一個前端的使用包, langserver則是后端服務。先搭好服務,然后才能在前端使用。

教程里的幾種方式,都需要一個大語言后端支持,為了避免后續(xù)的麻煩,所以我決定搭建一下ollama。

然后就跳到了ollama的頁面

看起來ollama支持的系統(tǒng)還是比較全面的

1.1 蘋果

實測:蘋果的下載非常快… 秒級。展開后大約435M。

如要使用之前,需要在終端上先進行拉取,命令就是上面那個。
然后執(zhí)行測試

import ollama
response = ollama.chat(model='llama2', messages=[
  {
    'role': 'user',
    'content': '解析出收件人地點、公司、收件人和收件人電話\n幫我寄到上海國金中心中心33F, ABC公司,Bikky收就行,電話號碼13566778899。我的電話是18988998899,上海楊浦區(qū)。',
  },
])
print(response['message']['content'])
經(jīng)過分析,可以知道:
* 收件人地點:上海市,特別是楊浦區(qū)
* 公司名稱:ABC公司
* 收件人姓名:Bikky
* 收件人電話號碼:13566778899
* 你的電話號碼:18988998899,也在上海市,但不同區(qū)。

在執(zhí)行效率上,我的蘋果(m1 pro),配置也不算低了,但是執(zhí)行效率上還是比2080TI慢了2~3倍。


mac m1 pro: 平均8秒
[3.5188119411468506,
 5.56521201133728,
 7.0565900802612305,
 11.417732238769531,
 7.563968896865845,
 9.987686157226562,
 6.56359601020813,
 6.939379930496216,
 9.785239219665527,
 11.655837059020996]
In [10]: np.mean(time_list)
Out[10]: 8.005405354499818
2080Ti:平均2.9秒
[2.193615674972534,
 2.8509912490844727,
 2.972665786743164,
 2.2655117511749268,
 3.038464069366455,
 4.976086378097534,
 3.4014697074890137,
 2.209334373474121,
 2.832230567932129,
 2.2567901611328125]
np.mean(time_list)
2.8997159719467165

以下是可拉取的模型,最大的70B library

1.2 linux安裝

執(zhí)行腳本

curl -fsSL https://ollama.com/install.sh | sh

啟動服務

ollama serve

執(zhí)行包的安裝

pip3 install ollama -i https://mirrors.aliyun.com/pypi/simple/
pip3 install langchain_community -i https://mirrors.aliyun.com/pypi/simple/
pip3 install beautifulsoup4 -i https://mirrors.aliyun.com/pypi/simple/
pip3 install faiss-cpu -i https://mirrors.aliyun.com/pypi/simple/
pip3 install langchain_text_splitters -i https://mirrors.aliyun.com/pypi/simple/
pip3 install langchain -i https://mirrors.aliyun.com/pypi/simple/

然后就可以使用了。
這種方法一般用在沒有絕對控制權(quán)的情況,例如租用的算力主機。

1.3 docker安裝

這種方式最為簡便,也最為有用,但是要求對主機具有絕對控制權(quán)。

直接拉取最新版本

docker pull ollama/ollama

然后啟動,考慮到server拉取模型會占據(jù)很大空間,所以把一個大的數(shù)據(jù)盤掛到root下。ollama下載的文件會存在root的 .ollama隱藏文件夾下面。

docker run -d \
 --name=ollama01 \
 -v /etc/localtime:/etc/localtime  \
 -v /etc/timezone:/etc/timezone\
 -v /etc/hostname:/etc/hostname \
 -v /data:/root \
 -e "LANG=C.UTF-8"\
 -p 11434:11434\
 -w /workspace \
 --gpus all \
 ollama/ollama

本地docker安裝,在第一次啟動時可能會碰到一些問題,

└─ $ docker run  -it --rm --gpus=all registry.cn-hangzhou.aliyuncs.com/andy08008/pytorch_jupyter:v8 bash
docker: Error response from daemon: could not select device driver "" with capabilities: [[gpu]].

需要做一些連通顯卡和docker的操作
1 添加源

curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | \
  sudo apt-key add -
distribution=$(. /etc/os-release;echo $ID$VERSION_ID)
curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | \
  sudo tee /etc/apt/sources.list.d/nvidia-docker.list
sudo apt-get update

2 安裝: nvidia-container-toolkit

sudo apt-get install -y nvidia-container-toolkit

3 重啟:通常也就是在這里,租用的機器要么沒有systemd,要么不把這個權(quán)限給你。

systemctl restart docker

這個服務比較有趣的一點是,ollama server會自動進行顯存的管理

空閑時:

當使用模型預測時

import ollama
response = ollama.chat(model='llama2', messages=[
  {
    'role': 'user',
    'content': '解析出收件人地點、公司、收件人和收件人電話\n幫我寄到上海國金中心中心33F, ABC公司,Bikky收就行,電話號碼13566778899。我的電話是18988998899,上海楊浦區(qū)。',
  },
])
print(response['message']['content'])
 Based on the information provided, here is a breakdown of the recipient's details:
* Recipient's location: 上海國金中心 (Shanghai Gold Center) in the 33F floor.
* Company name: ABC公司 (ABC Company).
* Recipient's name: Bikky收就行 (Bikky receives).
* Recipient's phone number: 13566778899.
* Your phone number: 18988998899, located in 上海楊浦區(qū) (Shanghai Yangpu District).
Please note that the above information is based on the text you provided and may not be accurate or up-to-date.

默認使用llama2-7b模型,調(diào)用時顯存會被占用。

如果過一會不用,顯存會自動清除。而且如果我們再使用另一個模型時,server會自動切換模型,把之前的清掉,然后載入新的,這樣顯存就不會爆。

import ollama
response = ollama.chat(model='llama2:13b', messages=[
  {
    'role': 'user',
    'content': '解析出收件人地點、公司、收件人和收件人電話\n幫我寄到上海國金中心中心33F, ABC公司,Bikky收就行,電話號碼13566778899。我的電話是18988998899,上海楊浦區(qū)。',
  },
])
print(response['message']['content'])
OK! Here's the analysis of the information you provided:
1. Receiver's location: Shanghai, China (based on the address "上海國金中心中心33F")
2. Company name: ABC Company (based on the address "上海國金中心中心33F")
3. Receiver's name: Bikky (based on the name "Bikky收")
4. Receiver's contact information: Phone number 13566778899 (based on the phone number in the address)
5. Sender's location: Shanghai Yangpu District (based on the phone number 18988998899)
6. Sender's name: Not provided
I hope this helps! Let me know if you have any other questions.

2 langchain實驗

先快速跟著教程走一遍

1 載入大模型,問一個簡單的問題: how can langsmith help with testing?

from langchain_community.llms import Ollama
llm = Ollama(model="llama2")
llm.invoke("how can langsmith help with testing?")
Langsmith is a tool that can be used to test and validate the correctness of language models. Here are some ways in which Langsmith can help with testing:
1. **Text generation**: Langsmith can be used to generate text samples that can be used to test the language model's ability to produce coherent and contextually relevant text. By comparing the generated text to a reference sample, Langsmith can evaluate the model's performance in terms of fluency, coherence, and relevance.
2. **Text completion**: Langsmith can be used to test the language model's ability to complete partial sentences or phrases. By providing a starting point for the model and evaluating its output, Langsmith can assess the model's ability to capture the context and produce coherent text.
3. **Sentiment analysis**: Langsmith can be used to test the language model's ability to classify text as positive, negative, or neutral. By providing a dataset of labeled text samples and evaluating the model's performance, Langsmith can assess its ability to accurately classify sentiment.
4. **Named entity recognition**: Langsmith can be used to test the language model's ability to identify named entities in text, such as people, organizations, and locations. By providing a dataset of labeled text samples and evaluating the model's performance, Langsmith can assess its ability to accurately identify named entities.
5. **Question answering**: Langsmith can be used to test the language model's ability to answer questions based on a given context or input. By providing a dataset of labeled question-answer pairs and evaluating the model's performance, Langsmith can assess its ability to accurately answer questions.
6. **Dialogue generation**: Langsmith can be used to test the language model's ability to engage in coherent and contextually relevant dialogue. By providing a dataset of labeled dialogue samples and evaluating the model's performance, Langsmith can assess its ability to produce natural-sounding dialogue.
7. **Multi-task evaluation**: Langsmith can be used to test the language model's ability to perform multiple tasks simultaneously, such as language translation, sentiment analysis, and named entity recognition. By providing a dataset of labeled text samples and evaluating the model's performance across multiple tasks, Langsmith can assess its ability to handle multi-tasking.
By using Langsmith to test these aspects of language models, developers can gain a better understanding of their strengths and weaknesses, and make informed decisions about how to improve them.

2 使用prompt模型進行修改

from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are world class technical documentation writer."),
    ("user", "{input}")
])

3 組成鏈,并使用鏈提問。感覺風格有點變,但內(nèi)容好壞不確定。

chain = prompt | llm 
print(chain.invoke({"input": "how can langsmith help with testing?"}))
As a world-class technical documentation writer, I must say that Langsmith is an excellent tool for testing! Here are some ways in which Langsmith can help with testing:
1. Automated Testing: Langsmith provides automated testing capabilities, allowing you to create and run tests without any manual intervention. This saves time and effort, while also ensuring consistency and accuracy in your test results.
2. Customizable Tests: With Langsmith, you can create customizable tests tailored to your specific needs. You can define the test cases, question types, and evaluation criteria to suit your requirements.
3. Integration with Existing Tools: Langsmith integrates seamlessly with popular testing tools such as JIRA, TestRail, and PractiTest. This enables you to create, run, and manage tests within a single platform, streamlining your testing process.
4. Collaborative Testing: Langsmith supports collaborative testing, allowing multiple team members to work together on a test project. This fosters collaboration and coordination among team members, ensuring that everyone is on the same page and working towards the same goal.
5. Real-time Feedback: Langsmith provides real-time feedback on test results, enabling you to identify areas of improvement immediately. This helps you to rectify errors early on and ensure that your tests are accurate and reliable.
6. Test Case Management: Langsmith offers a comprehensive test case management system, which enables you to organize, track, and maintain your test cases. This helps you to keep your tests organized, up-to-date, and easily accessible.
7. Reporting and Analytics: Langsmith provides detailed reporting and analytics on test results, allowing you to identify trends, strengths, and weaknesses in your testing process. This enables you to optimize your testing strategy and improve overall quality.
8. Integration with Agile Methodologies: Langsmith is designed to work seamlessly with agile methodologies such as Scrum and Kanban. This ensures that your testing activities are aligned with the rest of your development process, enabling you to deliver high-quality software quickly and efficiently.
9. Customizable Workflows: Langsmith allows you to create customizable workflows tailored to your specific needs. This enables you to streamline your testing process and ensure that it aligns with your project's unique requirements.
10. User-Friendly Interface: Langsmith boasts a user-friendly interface, making it easy for team members to use and navigate the platform. This reduces the learning curve and ensures that everyone can use the platform effectively.
In summary, Langsmith is an excellent tool for testing as it provides automated testing capabilities, customizable tests, integration with existing tools, collaborative testing, real-time feedback, test case management, reporting and analytics, integration with agile methodologies, customizable workflows, and a user-friendly interface. These features work together to create a comprehensive and efficient testing platform that can help you deliver high-quality software quickly and efficiently.

4 繼續(xù)加鏈。應該是對答案做了后除了,但也沒太看出差別

from langchain_core.output_parsers import StrOutputParser

output_parser = StrOutputParser()
chain = prompt | llm | output_parser
print(chain.invoke({"input": "how can langsmith help with testing?"}))

As a world-class technical documentation writer, I can help with testing in several ways:

1. Content Creation: Langsmith can assist in creating comprehensive and accurate content for your software or system, including user manuals, technical guides, and release notes. This content can be used to test the system's functionality and usability, ensuring that it meets the requirements and expectations of users.
2. Collaborative Testing: Langsmith can collaborate with your testing team to create test cases and scenarios based on the documentation created. This can help ensure that all aspects of the system are thoroughly tested and that any issues or bugs are identified early in the development process.
3. Automated Testing: By using natural language processing (NLP) and machine learning (ML) algorithms, Langsmith can assist in automating testing processes. For example, Langsmith can be used to generate test cases based on the documentation, or to analyze test results and identify areas for improvement.
4. Test Data Generation: Langsmith can help generate test data that is tailored to your system's requirements. This can include generating sample inputs, outputs, and edge cases that can be used to test the system's functionality.
5. Defect Reporting: Langsmith can assist in identifying and reporting defects or issues found during testing. By analyzing the documentation and test results, Langsmith can generate detailed reports of defects and suggest fixes or improvements.
6. Test Planning: Langsmith can help plan and prioritize testing efforts by analyzing the system's requirements and identifying critical areas that need to be tested. This can help ensure that the most important features and functionality are thoroughly tested, and that testing resources are allocated effectively.
7. Test Execution: Langsmith can assist in executing tests by generating test scripts based on the documentation and test cases created. This can help ensure that all aspects of the system are tested and that any issues or bugs are identified early in the development process.
8. Test Data Management: Langsmith can help manage test data by generating sample inputs, outputs, and edge cases that can be used to test the system's functionality. This can help ensure that test data is accurate, up-to-date, and relevant to the system being tested.
9. Performance Tuning: By analyzing the documentation and testing results, Langsmith can assist in identifying performance issues and suggest optimizations or improvements.
10. Security Testing: Langsmith can help identify security vulnerabilities in the system by analyzing the documentation and test results. This can help ensure that the system is secure and meets the necessary security requirements.

In summary, Langsmith can assist in various testing activities, including content creation, collaborative testing, automated testing, test data generation, defect reporting, test planning, test execution, test data management, performance tuning, and security testing. By leveraging natural language processing and machine learning algorithms, Langsmith can help improve the efficiency and effectiveness of your testing efforts.

5 通過web方式載入數(shù)據(jù)

from langchain_community.document_loaders import WebBaseLoader
loader = WebBaseLoader("https://docs.smith.langchain.com/user_guide")
docs = loader.load()

6 對載入的數(shù)據(jù)執(zhí)行分割和嵌入

from langchain_community.embeddings import OllamaEmbeddings
embeddings = OllamaEmbeddings()
from langchain_community.vectorstores import FAISS
from langchain_text_splitters import RecursiveCharacterTextSplitter
text_splitter = RecursiveCharacterTextSplitter()
documents = text_splitter.split_documents(docs)
vector = FAISS.from_documents(documents, embeddings)

7 繼續(xù)增加鏈,用create_stuff_documents_chain 加上prompt,形成文檔查詢鏈

from langchain.chains.combine_documents import create_stuff_documents_chain
prompt = ChatPromptTemplate.from_template("""Answer the following question based only on the provided context:
<context>
{context}
</context>
Question: {input}""")
document_chain = create_stuff_documents_chain(llm, prompt)

8 載入Document,然后執(zhí)行查詢

from langchain_core.documents import Document
document_chain.invoke({
    "input": "how can langsmith help with testing?",
    "context": [Document(page_content="langsmith can let you visualize test results")]
})
Based on the provided context, Langsmith can help with testing by providing a way to visualize test results. This means that Langsmith can assist in the process of testing software or applications by allowing users to view and analyze the results of those tests in a visual format, such as charts, graphs, or other visualizations.

9 然后使用向量增強

from langchain.chains import create_retrieval_chain
retriever = vector.as_retriever()
retrieval_chain = create_retrieval_chain(retriever, document_chain)
response = retrieval_chain.invoke({"input": "how can langsmith help with testing?"})
print(response["answer"])
Based on the provided context, LangSmith can help with testing in several ways:
1. Prototyping: LangSmith allows for quick experimentation between prompts, model types, and retrieval strategy, making it easier to understand how the model performs and debug where it is failing.
2. Initial Test Set: LangSmith enables developers to create datasets of inputs and reference outputs, which can be used to run tests on their LLM applications. This helps in identifying regressions with respect to initial test cases.
3. Custom Evaluations: LangSmith provides the ability to run custom evaluations (both LLM and heuristic based) to score test results, allowing developers to assess the performance of their LLM applications more comprehensively.
4. Comparison View: The comparison view in LangSmith enables users to see the results for different configurations side-by-side, helping diagnose regressions in test scores across multiple revisions of the application.
5. Playground Environment: LangSmith provides a playground environment for rapid iteration and experimentation, allowing users to quickly test out different prompts and models without having to run each one individually.

這塊應該就是很多知識庫的一般流程了。

ollama的搭建的使用到這里就結(jié)束了。

到此這篇關于Python ollama的搭建與使用的文章就介紹到這了,更多相關python ollama使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Python實現(xiàn)替換excel單元格內(nèi)容

    Python實現(xiàn)替換excel單元格內(nèi)容

    openpyxl是一個用于讀寫Excel 2010 xlsx/xlsm/xltx/xltm文件的庫,本文將使用openpyxl實現(xiàn)替換excel單元格內(nèi)容,感興趣的小伙伴可以了解下
    2025-01-01
  • YOLOv5車牌識別實戰(zhàn)教程(四)模型優(yōu)化與部署

    YOLOv5車牌識別實戰(zhàn)教程(四)模型優(yōu)化與部署

    這篇文章主要介紹了YOLOv5車牌識別實戰(zhàn)教程(四)模型優(yōu)化與部署,在這個教程中,我們將一步步教你如何使用YOLOv5進行車牌識別,幫助你快速掌握YOLOv5車牌識別技能,需要的朋友可以參考下
    2023-04-04
  • Python使用psutil對系統(tǒng)數(shù)據(jù)進行采集監(jiān)控

    Python使用psutil對系統(tǒng)數(shù)據(jù)進行采集監(jiān)控

    psutil庫可以實時獲取系統(tǒng)的一些信息,這樣就可以達到實時監(jiān)控系統(tǒng)的目的。本文對詳細講解了ython使用psutil對系統(tǒng)數(shù)據(jù)進行采集監(jiān)控,感興趣的朋友可以看一看
    2021-08-08
  • Python列表去重的4種核心方法與實戰(zhàn)指南詳解

    Python列表去重的4種核心方法與實戰(zhàn)指南詳解

    在Python開發(fā)中,處理列表數(shù)據(jù)時經(jīng)常需要去除重復元素,本文將詳細介紹4種最實用的列表去重方法,有需要的小伙伴可以根據(jù)自己的需要進行選擇
    2025-04-04
  • 利用pycharm調(diào)試ssh遠程程序并實時同步文件的操作方法

    利用pycharm調(diào)試ssh遠程程序并實時同步文件的操作方法

    這篇文章主要介紹了利用pycharm調(diào)試ssh遠程程序并實時同步文件的操作方法,本篇文章提供了利用pycharm遠程調(diào)試程序的方法,且使用的編譯器可以是服務器中的虛擬環(huán)境的編譯器,可以實時同步本地與服務器的文件內(nèi)容,需要的朋友可以參考下
    2022-11-11
  • 如何通過一篇文章了解Python中的生成器

    如何通過一篇文章了解Python中的生成器

    生成器指的是生成器對象,可以由生成器表達式得到,也可以使用yield關鍵字得到一個生成器函數(shù),調(diào)用這個函數(shù)得到一個生成器對象,下面這篇文章主要給大家介紹了關于Python中生成器的相關資料,需要的朋友可以參考下
    2022-04-04
  • 幾種實用的pythonic語法實例代碼

    幾種實用的pythonic語法實例代碼

    在我理解,Pythonic 就是很 Python 的 Python 代碼。下面這篇文章主要給大家分享介紹了幾種實用的pythonic語法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。
    2018-02-02
  • PyTorch實現(xiàn)ResNet50、ResNet101和ResNet152示例

    PyTorch實現(xiàn)ResNet50、ResNet101和ResNet152示例

    今天小編就為大家分享一篇PyTorch實現(xiàn)ResNet50、ResNet101和ResNet152示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • Python中流程控制的高級用法盤點

    Python中流程控制的高級用法盤點

    在這篇文章中我們將全面深入地介紹?Python?的控制流程,包括條件語句、循環(huán)結(jié)構(gòu)和異常處理等關鍵部分,尤其會將列表解析、生成器、裝飾器等高級用法一網(wǎng)打盡,快跟隨小編學起來吧
    2023-05-05
  • Python+matplotlib實現(xiàn)簡單曲線的繪制

    Python+matplotlib實現(xiàn)簡單曲線的繪制

    Matplotlib是Python的繪圖庫,它能讓使用者很輕松地將數(shù)據(jù)圖形化,并且提供多樣化的輸出格式。本文將利用matplotlib繪制簡單的曲線圖,感興趣的朋友可以學習一下
    2022-04-04

最新評論

库车县| 灌云县| 望都县| 花莲县| 龙井市| 河间市| 新源县| 翁源县| 宜川县| 仁布县| 阜宁县| 石渠县| 梁平县| 卢湾区| 钟山县| 枝江市| 三都| 尼玛县| 特克斯县| 北川| 福鼎市| 平谷区| 新乡市| 徐州市| 托克托县| 庆阳市| 新龙县| 泗阳县| 宽甸| 海南省| 定安县| 定襄县| 离岛区| 庆云县| 武山县| 大理市| 江城| 孙吴县| 潮州市| 阿克苏市| 栖霞市|