国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 后端開發(fā) Python教程 使用 LangChain 和 Python 生成人工智能的綜合初學者指南 - 3

使用 LangChain 和 Python 生成人工智能的綜合初學者指南 - 3

Dec 30, 2024 am 01:11 AM

Comprehensive Beginner

生成式人工智能使系統(tǒng)能夠根據數(shù)據和提示創(chuàng)建文本、圖像、代碼或其他形式的內容。 LangChain 是一個框架,通過編排工作流程、管理提示以及啟用內存和工具集成等高級功能,簡化了生成式 AI 模型的使用。

本指南介紹了使用 LangChainPython 開始生成式 AI 所需的關鍵概念和工具。


1.什么是浪鏈?

LangChain 是一個基于 Python 的框架,用于使用 OpenAI 的 GPT 或 Hugging Face 模型等大型語言模型 (LLM) 構建應用程序。它有幫助:

  • 管理提示:創(chuàng)建可重復使用的結構化提示。
  • 鏈式工作流程:將多個LLM調用合并到一個工作流程中。
  • 使用工具:使 AI 模型能夠與 API、數(shù)據庫等交互。
  • 添加記憶:允許模型記住過去的交互。

2.設置您的環(huán)境

a) 安裝所需的庫

首先,安裝LangChain和相關庫:

pip install langchain openai python-dotenv streamlit

b) 設置您的 OpenAI API 密鑰

  1. 注冊 OpenAI 帳戶并獲取您的 API 密鑰:OpenAI API。
  2. 在項目目錄中創(chuàng)建一個 .env 文件并添加 API 密鑰:
   OPENAI_API_KEY=your_api_key_here
  1. 使用 dotenv 在 Python 腳本中加載 API 密鑰:
   from dotenv import load_dotenv
   import os

   load_dotenv()
   openai_api_key = os.getenv("OPENAI_API_KEY")

3. LangChain的關鍵概念

a) 提示

提示引導人工智能生成所需的輸出。 LangChain允許您使用PromptTemplate系統(tǒng)地構建提示。

from langchain.prompts import PromptTemplate

# Define a template
template = "You are an AI that summarizes text. Summarize the following: {text}"
prompt = PromptTemplate(input_variables=["text"], template=template)

# Generate a prompt with dynamic input
user_text = "Artificial Intelligence is a field of study that focuses on creating machines capable of intelligent behavior."
formatted_prompt = prompt.format(text=user_text)
print(formatted_prompt)

b) 語言模型

LangChain 與 OpenAI 的 GPT 或 Hugging Face 模型等法學碩士集成。使用 OpenAI GPT 的 ChatOpenAI。

from langchain.chat_models import ChatOpenAI

# Initialize the model
chat = ChatOpenAI(temperature=0.7, openai_api_key=openai_api_key)

# Generate a response
response = chat.predict("What is Generative AI?")
print(response)

c) 鏈條

鏈將多個步驟或任務組合到一個工作流程中。例如,一條鏈可能:

  1. 總結文檔。
  2. 根據摘要生成問題。
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate

# Create a prompt and chain
template = "Summarize the following text: {text}"
prompt = PromptTemplate(input_variables=["text"], template=template)
chain = LLMChain(llm=chat, prompt=prompt)

# Execute the chain
result = chain.run("Generative AI refers to AI systems capable of creating text, images, or other outputs.")
print(result)

d) 記憶

內存使模型能夠保留多次交互的上下文。這對于聊天機器人很有用。

from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory

# Initialize memory and the conversation chain
memory = ConversationBufferMemory()
conversation = ConversationChain(llm=chat, memory=memory)

# Have a conversation
print(conversation.run("Hi, who are you?"))
print(conversation.run("What did I just ask you?"))

4.示例應用

a) 文本生成

使用提示生成創(chuàng)意響應或內容。

from langchain.chat_models import ChatOpenAI
from langchain.prompts import PromptTemplate

chat = ChatOpenAI(temperature=0.9, openai_api_key=openai_api_key)
prompt = PromptTemplate(input_variables=["topic"], template="Write a poem about {topic}.")
chain = LLMChain(llm=chat, prompt=prompt)

# Generate a poem
result = chain.run("technology")
print(result)

b) 總結

高效總結文檔或文本。

pip install langchain openai python-dotenv streamlit

c) 聊天機器人

構建一個具有記憶功能的交互式聊天機器人。

   OPENAI_API_KEY=your_api_key_here

5.高級功能

a) 工具

使模型能夠訪問網絡搜索或數(shù)據庫等外部工具。

   from dotenv import load_dotenv
   import os

   load_dotenv()
   openai_api_key = os.getenv("OPENAI_API_KEY")

b) 定制鏈

通過組合多個任務來創(chuàng)建自定義工作流程。

from langchain.prompts import PromptTemplate

# Define a template
template = "You are an AI that summarizes text. Summarize the following: {text}"
prompt = PromptTemplate(input_variables=["text"], template=template)

# Generate a prompt with dynamic input
user_text = "Artificial Intelligence is a field of study that focuses on creating machines capable of intelligent behavior."
formatted_prompt = prompt.format(text=user_text)
print(formatted_prompt)

6.使用 Streamlit 進行部署

使用 Streamlit 為您的生成式 AI 模型構建一個簡單的 Web 應用程序。

安裝 Streamlit:

from langchain.chat_models import ChatOpenAI

# Initialize the model
chat = ChatOpenAI(temperature=0.7, openai_api_key=openai_api_key)

# Generate a response
response = chat.predict("What is Generative AI?")
print(response)

簡單的應用程序:

from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate

# Create a prompt and chain
template = "Summarize the following text: {text}"
prompt = PromptTemplate(input_variables=["text"], template=template)
chain = LLMChain(llm=chat, prompt=prompt)

# Execute the chain
result = chain.run("Generative AI refers to AI systems capable of creating text, images, or other outputs.")
print(result)

運行應用程序:

from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory

# Initialize memory and the conversation chain
memory = ConversationBufferMemory()
conversation = ConversationChain(llm=chat, memory=memory)

# Have a conversation
print(conversation.run("Hi, who are you?"))
print(conversation.run("What did I just ask you?"))

7.生成式 AI 開發(fā)人員的關鍵概念

a) 微調模型

學習在自定義數(shù)據集上微調 GPT 或穩(wěn)定擴散等模型。

b) 及時工程

掌握如何制作有效的提示以獲得所需的輸出。

c) 多模態(tài)人工智能

使用結合文本、圖像和其他模式的模型(例如 OpenAI 的 DALL·E 或 CLIP)。

d) 擴展和部署

使用云服務或 Docker 等工具將模型部署到生產環(huán)境。


8.資源

  • LangChain文檔:LangChain文檔
  • OpenAI API:OpenAI 文檔
  • 抱臉模特:抱臉

通過遵循本指南,您將獲得使用 Python 和 LangChain 構建生成式 AI 應用程序所需的基礎知識。開始實驗、構建工作流程并深入探索令人興奮的 AI 世界!

以上是使用 LangChain 和 Python 生成人工智能的綜合初學者指南 - 3的詳細內容。更多信息請關注PHP中文網其他相關文章!

本站聲明
本文內容由網友自發(fā)貢獻,版權歸原作者所有,本站不承擔相應法律責任。如您發(fā)現(xiàn)有涉嫌抄襲侵權的內容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅動的應用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機

Video Face Swap

Video Face Swap

使用我們完全免費的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

Python的UNITDEST或PYTEST框架如何促進自動測試? Python的UNITDEST或PYTEST框架如何促進自動測試? Jun 19, 2025 am 01:10 AM

Python的unittest和pytest是兩種廣泛使用的測試框架,它們都簡化了自動化測試的編寫、組織和運行。1.二者均支持自動發(fā)現(xiàn)測試用例并提供清晰的測試結構:unittest通過繼承TestCase類并以test\_開頭的方法定義測試;pytest則更為簡潔,只需以test\_開頭的函數(shù)即可。2.它們都內置斷言支持:unittest提供assertEqual、assertTrue等方法,而pytest使用增強版的assert語句,能自動顯示失敗詳情。3.均具備處理測試準備與清理的機制:un

如何將Python用于數(shù)據分析和與Numpy和Pandas等文庫進行操作? 如何將Python用于數(shù)據分析和與Numpy和Pandas等文庫進行操作? Jun 19, 2025 am 01:04 AM

pythonisidealfordataanalysisionduetonumpyandpandas.1)numpyExccelSatnumericalComputationswithFast,多dimensionalArraysAndRaysAndOrsAndOrsAndOffectorizedOperationsLikenp.sqrt()

什么是動態(tài)編程技術,如何在Python中使用它們? 什么是動態(tài)編程技術,如何在Python中使用它們? Jun 20, 2025 am 12:57 AM

動態(tài)規(guī)劃(DP)通過將復雜問題分解為更簡單的子問題并存儲其結果以避免重復計算,來優(yōu)化求解過程。主要方法有兩種:1.自頂向下(記憶化):遞歸分解問題,使用緩存存儲中間結果;2.自底向上(表格化):從基礎情況開始迭代構建解決方案。適用于需要最大/最小值、最優(yōu)解或存在重疊子問題的場景,如斐波那契數(shù)列、背包問題等。在Python中,可通過裝飾器或數(shù)組實現(xiàn),并應注意識別遞推關系、定義基準情況及優(yōu)化空間復雜度。

如何使用__ITER__和__NEXT __在Python中實現(xiàn)自定義迭代器? 如何使用__ITER__和__NEXT __在Python中實現(xiàn)自定義迭代器? Jun 19, 2025 am 01:12 AM

要實現(xiàn)自定義迭代器,需在類中定義__iter__和__next__方法。①__iter__方法返回迭代器對象自身,通常為self,以兼容for循環(huán)等迭代環(huán)境;②__next__方法控制每次迭代的值,返回序列中的下一個元素,當無更多項時應拋出StopIteration異常;③需正確跟蹤狀態(tài)并設置終止條件,避免無限循環(huán);④可封裝復雜邏輯如文件行過濾,同時注意資源清理與內存管理;⑤對簡單邏輯可考慮使用生成器函數(shù)yield替代,但需結合具體場景選擇合適方式。

Python編程語言及其生態(tài)系統(tǒng)的新興趨勢或未來方向是什么? Python編程語言及其生態(tài)系統(tǒng)的新興趨勢或未來方向是什么? Jun 19, 2025 am 01:09 AM

Python的未來趨勢包括性能優(yōu)化、更強的類型提示、替代運行時的興起及AI/ML領域的持續(xù)增長。首先,CPython持續(xù)優(yōu)化,通過更快的啟動時間、函數(shù)調用優(yōu)化及擬議中的整數(shù)操作改進提升性能;其次,類型提示深度集成至語言與工具鏈,增強代碼安全性與開發(fā)體驗;第三,PyScript、Nuitka等替代運行時提供新功能與性能優(yōu)勢;最后,AI與數(shù)據科學領域持續(xù)擴張,新興庫推動更高效的開發(fā)與集成。這些趨勢表明Python正不斷適應技術變化,保持其領先地位。

如何使用插座在Python中執(zhí)行網絡編程? 如何使用插座在Python中執(zhí)行網絡編程? Jun 20, 2025 am 12:56 AM

Python的socket模塊是網絡編程的基礎,提供低級網絡通信功能,適用于構建客戶端和服務器應用。要設置基本TCP服務器,需使用socket.socket()創(chuàng)建對象,綁定地址和端口,調用.listen()監(jiān)聽連接,并通過.accept()接受客戶端連接。構建TCP客戶端需創(chuàng)建socket對象后調用.connect()連接服務器,再使用.sendall()發(fā)送數(shù)據和.recv()接收響應。處理多個客戶端可通過1.線程:每次連接啟動新線程;2.異步I/O:如asyncio庫實現(xiàn)無阻塞通信。注意事

Python類中的多態(tài)性 Python類中的多態(tài)性 Jul 05, 2025 am 02:58 AM

多態(tài)是Python面向對象編程中的核心概念,指“一種接口,多種實現(xiàn)”,允許統(tǒng)一處理不同類型的對象。1.多態(tài)通過方法重寫實現(xiàn),子類可重新定義父類方法,如Animal類的speak()方法在Dog和Cat子類中有不同實現(xiàn)。2.多態(tài)的實際用途包括簡化代碼結構、增強可擴展性,例如圖形繪制程序中統(tǒng)一調用draw()方法,或游戲開發(fā)中處理不同角色的共同行為。3.Python實現(xiàn)多態(tài)需滿足:父類定義方法,子類重寫該方法,但不要求繼承同一父類,只要對象實現(xiàn)相同方法即可,這稱為“鴨子類型”。4.注意事項包括保持方

如何在Python中切片列表? 如何在Python中切片列表? Jun 20, 2025 am 12:51 AM

Python列表切片的核心答案是掌握[start:end:step]語法并理解其行為。1.列表切片的基本格式為list[start:end:step],其中start是起始索引(包含)、end是結束索引(不包含)、step是步長;2.省略start默認從0開始,省略end默認到末尾,省略step默認為1;3.獲取前n項用my_list[:n],獲取后n項用my_list[-n:];4.使用step可跳過元素,如my_list[::2]取偶數(shù)位,負step值可反轉列表;5.常見誤區(qū)包括end索引不

See all articles