亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

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

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

Dec 30, 2024 am 01:11 AM

Comprehensive Beginner

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

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


1.什么是浪鏈?

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

  • 管理提示:創(chuàng)建可重復(fù)使用的結(jié)構(gòu)化提示。
  • 鏈?zhǔn)焦ぷ髁鞒?/strong>:將多個LLM調(diào)用合并到一個工作流程中。
  • 使用工具:使 AI 模型能夠與 API、數(shù)據(jù)庫等交互。
  • 添加記憶:允許模型記住過去的交互。

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

a) 安裝所需的庫

首先,安裝LangChain和相關(guān)庫:

pip install langchain openai python-dotenv streamlit

b) 設(shè)置您的 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的關(guān)鍵概念

a) 提示

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

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 模型等法學(xué)碩士集成。使用 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) 鏈條

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

  1. 總結(jié)文檔。
  2. 根據(jù)摘要生成問題。
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) 記憶

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

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.示例應(yīng)用

a) 文本生成

使用提示生成創(chuàng)意響應(yīng)或內(nèi)容。

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) 總結(jié)

高效總結(jié)文檔或文本。

pip install langchain openai python-dotenv streamlit

c) 聊天機器人

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

   OPENAI_API_KEY=your_api_key_here

5.高級功能

a) 工具

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

   from dotenv import load_dotenv
   import os

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

b) 定制鏈

通過組合多個任務(wù)來創(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 進(jìn)行部署

使用 Streamlit 為您的生成式 AI 模型構(gòu)建一個簡單的 Web 應(yīng)用程序。

安裝 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)

簡單的應(yīng)用程序:

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)

運行應(yīng)用程序:

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ā)人員的關(guān)鍵概念

a) 微調(diào)模型

學(xué)習(xí)在自定義數(shù)據(jù)集上微調(diào) GPT 或穩(wěn)定擴散等模型。

b) 及時工程

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

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

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

d) 擴展和部署

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


8.資源

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

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

以上是使用 LangChain 和 Python 生成人工智能的綜合初學(xué)者指南 - 3的詳細(xì)內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

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

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動的應(yīng)用程序,用于創(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

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

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

熱門話題

Laravel 教程
1597
29
PHP教程
1488
72
Python類中的多態(tài)性 Python類中的多態(tài)性 Jul 05, 2025 am 02:58 AM

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

解釋Python發(fā)電機和迭代器。 解釋Python發(fā)電機和迭代器。 Jul 05, 2025 am 02:55 AM

迭代器是實現(xiàn)__iter__()和__next__()方法的對象,生成器是簡化版的迭代器,通過yield關(guān)鍵字自動實現(xiàn)這些方法。1.迭代器每次調(diào)用next()返回一個元素,無更多元素時拋出StopIteration異常。2.生成器通過函數(shù)定義,使用yield按需生成數(shù)據(jù),節(jié)省內(nèi)存且支持無限序列。3.處理已有集合時用迭代器,動態(tài)生成大數(shù)據(jù)或需惰性求值時用生成器,如讀取大文件時逐行加載。注意:列表等可迭代對象不是迭代器,迭代器到盡頭后需重新創(chuàng)建,生成器只能遍歷一次。

如何處理Python中的API身份驗證 如何處理Python中的API身份驗證 Jul 13, 2025 am 02:22 AM

處理API認(rèn)證的關(guān)鍵在于理解并正確使用認(rèn)證方式。1.APIKey是最簡單的認(rèn)證方式,通常放在請求頭或URL參數(shù)中;2.BasicAuth使用用戶名和密碼進(jìn)行Base64編碼傳輸,適合內(nèi)部系統(tǒng);3.OAuth2需先通過client_id和client_secret獲取Token,再在請求頭中帶上BearerToken;4.為應(yīng)對Token過期,可封裝Token管理類自動刷新Token;總之,根據(jù)文檔選擇合適方式,并安全存儲密鑰信息是關(guān)鍵。

解釋Python斷言。 解釋Python斷言。 Jul 07, 2025 am 12:14 AM

Assert是Python用于調(diào)試的斷言工具,當(dāng)條件不滿足時拋出AssertionError。其語法為assert條件加可選錯誤信息,適用于內(nèi)部邏輯驗證如參數(shù)檢查、狀態(tài)確認(rèn)等,但不能用于安全或用戶輸入檢查,且應(yīng)配合清晰提示信息使用,僅限開發(fā)階段輔助調(diào)試而非替代異常處理。

如何一次迭代兩個列表 如何一次迭代兩個列表 Jul 09, 2025 am 01:13 AM

在Python中同時遍歷兩個列表的常用方法是使用zip()函數(shù),它會按順序配對多個列表并以最短為準(zhǔn);若列表長度不一致,可使用itertools.zip_longest()以最長為準(zhǔn)并填充缺失值;結(jié)合enumerate()可同時獲取索引。1.zip()簡潔實用,適合成對數(shù)據(jù)迭代;2.zip_longest()處理不一致長度時可填充默認(rèn)值;3.enumerate(zip())可在遍歷時獲取索引,滿足多種復(fù)雜場景需求。

什么是Python迭代器? 什么是Python迭代器? Jul 08, 2025 am 02:56 AM

Inpython,IteratorSareObjectSthallowloopingThroughCollectionsByImplementing_iter __()和__next __()。1)iteratorsWiaTheIteratorProtocol,使用__ITER __()toreTurnterateratoratoranteratoratoranteratoratorAnterAnteratoratorant antheittheext__()

什么是Python型提示? 什么是Python型提示? Jul 07, 2025 am 02:55 AM

typeHintsInpyThonsolverbromblemboyofambiguityandPotentialBugSindyNamalytyCodeByallowingDevelopsosteSpecefectifyExpectedTypes.theyenhancereadability,enablellybugdetection,andimprovetool.typehintsupport.typehintsareadsareadsareadsareadsareadsareadsareadsareadsareaddedusidocolon(

Python Fastapi教程 Python Fastapi教程 Jul 12, 2025 am 02:42 AM

要使用Python創(chuàng)建現(xiàn)代高效的API,推薦使用FastAPI;其基于標(biāo)準(zhǔn)Python類型提示,可自動生成文檔,性能優(yōu)越。安裝FastAPI和ASGI服務(wù)器uvicorn后,即可編寫接口代碼。通過定義路由、編寫處理函數(shù)并返回數(shù)據(jù),可以快速構(gòu)建API。FastAPI支持多種HTTP方法,并提供自動生成的SwaggerUI和ReDoc文檔系統(tǒng)。URL參數(shù)可通過路徑定義捕獲,查詢參數(shù)則通過函數(shù)參數(shù)設(shè)置默認(rèn)值實現(xiàn)。合理使用Pydantic模型有助于提升開發(fā)效率和準(zhǔn)確性。

See all articles