如何使用LangChain和Qwen-2.5-32B構建AI寫作助手

如何使用LangChain和Qwen-2.5-32B構建AI寫作助手

在人工智慧時代,大型語言模型是自動建立內容、與人類交流和智慧解決複雜問題的關鍵。在強大的模型中,阿里巴巴達摩研究院開發的Qwen 2.5 32B是一個擁有320億個引數的強大人工智慧模型。它以生成高質量內容、有效推理和理解上下文而聞名。Qwen 2.5 32B 將人工智慧能力提升到了新的水平。本文將討論 Qwen 2.5 32B 和 LangChain 如何合作改造人工智慧應用,它們的功能、優勢和在現實生活中的作用,以及它們作為人工智慧一部分的重要性。

學習目標

  • 瞭解 Qwen 2.5 32B 在人工智慧驅動的內容生成中的功能和應用,以構建寫作助手。
  • 瞭解 LangChain 如何與 Qwen 2.5 32B 整合,以增強人工智慧驅動的工作流,從而構建寫作助手。
  • 探索 Qwen 2.5 32B 在改寫、提示生成和文字簡化方面的實際應用。
  • 使用 LangChain 和 Qwen 2.5 32B 建立基於 Streamlit 的人工智慧應用程式。
  • 深入瞭解如何優化人工智慧提示,以提高文字清晰度和結構化交流。

什麼是Qwen 2.5 32B?

Qwen 2.5 32B 是阿里巴巴達摩院開發的大型語言模型。它是以強大的自然語言理解和生成能力著稱的 Qwen 系列的一部分。該模型擁有 320 億個引數,可處理各種人工智慧任務,包括

  • 文字生成(創意和專業寫作)
  • 程式碼生成
  • 翻譯和摘要
  • 對話式人工智慧
  • 高階推理和問題解決

Qwen 2.5 32B 針對高質量文字生成進行了優化,是需要類似人類的流暢性和上下文意識的應用程式的最佳選擇。

什麼是LangChain?

LangChain 是一個人工智慧框架,可幫助開發人員使用 Qwen 2.5 32B 等大型語言模型 (LLM) 構建應用程式。它提供了以下工具

  • 將 LLM 與外部資料來源連線起來
  • 管理多步推理和決策
  • 建立人工智慧驅動的代理,與使用者進行動態互動
  • 構建聊天機器人、自動化工具和人工智慧驅動的應用程式

通過將 LangChain 與 Qwen 2.5 32B 相結合,企業可以構建高階人工智慧應用程式,以重寫句子、生成提示、簡化文字並提高寫作質量。

問題

對於個人和企業而言,有效溝通都是一項嚴峻的挑戰。結構不良的句子、複雜的術語和不清晰的提示往往會導致誤解、低效和低質量的人工智慧生成輸出。無論是撰寫專業電子郵件、生成精確的人工智慧提示,還是簡化技術內容,使用者往往難以用清晰、有條理和有影響力的方式表達自己的想法。

解決方案

這款人工智慧驅動的應用程式通過提高文字清晰度、優化人工智慧提示生成和簡化複雜內容來解決這一問題:

  • 重寫句子:確保寫作語法正確、精煉、專業。
  • 圖片和視訊提示生成器:為人工智慧生成的準確媒體建立結構合理的提示。
  • 文字簡化器:將複雜的文件轉換為易於理解的語言。

流程圖

文字改進應用程式在 Streamlit 中遵循簡化的工作流程,以高效地增強使用者輸入。當使用者選擇該應用程式並輸入需要改進的文字時,流程就開始了。點選處理按鈕後,系統會載入 ChatGroq LLM 模型,並根據所選功能確定適當的處理邏輯–無論是改寫句子、生成影象和視訊提示,還是簡化文字。每個處理邏輯都會相應執行,並利用 LLMChain 生成完善的輸出。最後,改進後的文字將顯示在 Streamlit 介面中,確保提供無縫和使用者友好的體驗。

流程圖

使用Streamlit和LangChain構建寫作助手

下面我們將介紹如何使用 Streamlit 和 LangChain 建立一個人工智慧驅動的文字改進應用程式。從環境設定到處理使用者輸入,請按照以下步驟構建一個直觀、高效的文字改進工具。

第 1 步:環境設定

使用 python -m venv env 建立一個虛擬環境,並根據作業系統(Windows 或 macOS/Linux)啟用它。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Create a Environment
python -m venv env
# Activate it on Windows
.\env\Scripts\activate
# Activate in MacOS/Linux
source env/bin/activate
# Create a Environment python -m venv env # Activate it on Windows .\env\Scripts\activate # Activate in MacOS/Linux source env/bin/activate
# Create a Environment
python -m venv env
# Activate it on Windows
.\env\Scripts\activate
# Activate in MacOS/Linux
source env/bin/activate

第 2 步:安裝 Requirements.txt

從提供的 GitHub 連結執行 pip install -r requirements.txt 安裝所有需要的軟體包。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
pip install -r https://raw.githubusercontent.com/Gouravlohar/rewriter/refs/heads/main/requirements.txt
pip install -r https://raw.githubusercontent.com/Gouravlohar/rewriter/refs/heads/main/requirements.txt
pip install -r https://raw.githubusercontent.com/Gouravlohar/rewriter/refs/heads/main/requirements.txt

第 3 步:設定API金鑰

從 Groq 獲取 API 金鑰,並以 API_KEY="Your API KEY PASTE HERE" 形式儲存在 .env 檔案中。

訪問 Groq 獲取 API 金鑰。

從 Groq 獲取 API 金鑰

貼上 API 金鑰到 .env 檔案中:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
API_KEY="Your API KEY PASTE HERE"
API_KEY="Your API KEY PASTE HERE"
API_KEY="Your API KEY PASTE HERE"

第 4 步:匯入必要的庫

匯入必要的庫,如 osstreamlitPromptTemplateLLMChain 和 ChatGroq,用於基於人工智慧的文字處理。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import os
import streamlit as st
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
from langchain_groq import ChatGroq
from dotenv import load_dotenv
import os import streamlit as st from langchain.prompts import PromptTemplate from langchain.chains import LLMChain from langchain_groq import ChatGroq from dotenv import load_dotenv
import os
import streamlit as st
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
from langchain_groq import ChatGroq
from dotenv import load_dotenv

第 5 步:載入API金鑰

使用 load_dotenv().env 檔案載入 API 金鑰,並在繼續執行應用程式前驗證其是否存在。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
load_dotenv()
groq_api_key = os.getenv("API_KEY")
if not groq_api_key:
st.error("Groq API Key not found in .env file")
st.stop()
load_dotenv() groq_api_key = os.getenv("API_KEY") if not groq_api_key: st.error("Groq API Key not found in .env file") st.stop()
load_dotenv()
groq_api_key = os.getenv("API_KEY")
if not groq_api_key:
st.error("Groq API Key not found in .env file")
st.stop()

我們從 .env 檔案中載入 API 金鑰,並在執行應用程式前確保它可用。

第 6 步:建立 Streamlit 使用者介面

設計帶有側邊欄的介面,允許使用者從三種功能中進行選擇: 重寫句子、圖片和視訊提示生成器或文字簡化器。

應用程式選擇側邊欄

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
st.title("Text Improvement App")
st.sidebar.header("Select App")
st.sidebar.markdown("Choose the functionality you'd like to use:")
app_choice = st.sidebar.selectbox("Choose an App", options=[
"Rewrite Sentence",
"Image and Video Prompt Generator",
"Text Simplifier"
])
st.title("Text Improvement App") st.sidebar.header("Select App") st.sidebar.markdown("Choose the functionality you'd like to use:") app_choice = st.sidebar.selectbox("Choose an App", options=[ "Rewrite Sentence", "Image and Video Prompt Generator", "Text Simplifier" ])
st.title("Text Improvement App")
st.sidebar.header("Select App")
st.sidebar.markdown("Choose the functionality you'd like to use:")
app_choice = st.sidebar.selectbox("Choose an App", options=[
"Rewrite Sentence", 
"Image and Video Prompt Generator", 
"Text Simplifier"
])

第 7 步:定義AI提示模板

為不同功能設定結構化提示,包括語氣調整、方言變化和創意文字轉換。

重寫句子模板

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
rewrite_template = """
Below is a draft text that may need improvement.
Your goal is to:
- Edit the draft for clarity and readability.
- Adjust the tone as specified.
- Adapt the text to the requested dialect.
**Tone Examples:**
- **Formal:** "Greetings! Elon Musk has announced a new innovation at Tesla, revolutionizing the electric vehicle industry. After extensive research and development, this breakthrough aims to enhance sustainability and efficiency. We look forward to seeing its impact on the market."
- **Informal:** "Hey everyone! Huge news—Elon Musk just dropped a game-changing update at Tesla! After loads of work behind the scenes, this new tech is set to make EVs even better. Can’t wait to see how it shakes things up!"
**Dialect Differences:**
- **American English:** French fries, apartment, garbage, cookie, parking lot
- **British English:** Chips, flat, rubbish, biscuit, car park
- **Australian English:** Hot chips, unit, rubbish, biscuit, car park
- **Canadian English:** French fries, apartment, garbage, cookie, parking lot
- **Indian English:** Finger chips, flat, dustbin, biscuit, parking space
Start with a warm introduction if needed.
**Draft Text, Tone, and Dialect:**
- **Draft:** {draft}
- **Tone:** {tone}
- **Dialect:** {dialect}
**Your {dialect} Response:**
"""
rewrite_template = """ Below is a draft text that may need improvement. Your goal is to: - Edit the draft for clarity and readability. - Adjust the tone as specified. - Adapt the text to the requested dialect. **Tone Examples:** - **Formal:** "Greetings! Elon Musk has announced a new innovation at Tesla, revolutionizing the electric vehicle industry. After extensive research and development, this breakthrough aims to enhance sustainability and efficiency. We look forward to seeing its impact on the market." - **Informal:** "Hey everyone! Huge news—Elon Musk just dropped a game-changing update at Tesla! After loads of work behind the scenes, this new tech is set to make EVs even better. Can’t wait to see how it shakes things up!" **Dialect Differences:** - **American English:** French fries, apartment, garbage, cookie, parking lot - **British English:** Chips, flat, rubbish, biscuit, car park - **Australian English:** Hot chips, unit, rubbish, biscuit, car park - **Canadian English:** French fries, apartment, garbage, cookie, parking lot - **Indian English:** Finger chips, flat, dustbin, biscuit, parking space Start with a warm introduction if needed. **Draft Text, Tone, and Dialect:** - **Draft:** {draft} - **Tone:** {tone} - **Dialect:** {dialect} **Your {dialect} Response:** """
rewrite_template = """
Below is a draft text that may need improvement.  
Your goal is to:  
- Edit the draft for clarity and readability.  
- Adjust the tone as specified.  
- Adapt the text to the requested dialect.  
**Tone Examples:**  
- **Formal:** "Greetings! Elon Musk has announced a new innovation at Tesla, revolutionizing the electric vehicle industry. After extensive research and development, this breakthrough aims to enhance sustainability and efficiency. We look forward to seeing its impact on the market."  
- **Informal:** "Hey everyone! Huge news—Elon Musk just dropped a game-changing update at Tesla! After loads of work behind the scenes, this new tech is set to make EVs even better. Can’t wait to see how it shakes things up!"  
**Dialect Differences:**  
- **American English:** French fries, apartment, garbage, cookie, parking lot  
- **British English:** Chips, flat, rubbish, biscuit, car park  
- **Australian English:** Hot chips, unit, rubbish, biscuit, car park  
- **Canadian English:** French fries, apartment, garbage, cookie, parking lot  
- **Indian English:** Finger chips, flat, dustbin, biscuit, parking space  
Start with a warm introduction if needed.  
**Draft Text, Tone, and Dialect:**  
- **Draft:** {draft}  
- **Tone:** {tone}  
- **Dialect:** {dialect}  
**Your {dialect} Response:**  
"""

影象和視訊提示生成器模板

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
prompt_generator_template = """
Below is a sentence written in poor English:
"{poor_sentence}"
Your task is to generate a creative writing prompt that improves clarity, grammar, and engagement.
"""
image_video_template = """
Below is a sentence:
"{sentence}"
Your task is to generate a detailed and descriptive prompt optimized for text-to-image or text-to-video generation.
The prompt should be vivid and visually-oriented to help generate high-quality media content.
"""
prompt_generator_template = """ Below is a sentence written in poor English: "{poor_sentence}" Your task is to generate a creative writing prompt that improves clarity, grammar, and engagement. """ image_video_template = """ Below is a sentence: "{sentence}" Your task is to generate a detailed and descriptive prompt optimized for text-to-image or text-to-video generation. The prompt should be vivid and visually-oriented to help generate high-quality media content. """
prompt_generator_template = """
Below is a sentence written in poor English:  
"{poor_sentence}"
Your task is to generate a creative writing prompt that improves clarity, grammar, and engagement.
"""
image_video_template = """
Below is a sentence:  
"{sentence}"
Your task is to generate a detailed and descriptive prompt optimized for text-to-image or text-to-video generation.  
The prompt should be vivid and visually-oriented to help generate high-quality media content.
"""

文字簡化模板

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
text_simplifier_template = """
Below is a piece of complex text:
"{complex_text}"
Your task is to rewrite this text in simpler and clearer language while preserving its original meaning.
"""
text_simplifier_template = """ Below is a piece of complex text: "{complex_text}" Your task is to rewrite this text in simpler and clearer language while preserving its original meaning. """
text_simplifier_template = """
Below is a piece of complex text:  
"{complex_text}"
Your task is to rewrite this text in simpler and clearer language while preserving its original meaning.
"""

第 8 步:載入AI模型

使用 Qwen-2.5-32B 初始化 ChatGroq AI 模型,使用 streaming=True 啟用實時文字處理。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def load_LLM(groq_api_key):
"""Loads the ChatGroq model for processing."""
llm = ChatGroq(groq_api_key=groq_api_key, model_name="qwen-2.5-32b", streaming=True)
return llm
def load_LLM(groq_api_key): """Loads the ChatGroq model for processing.""" llm = ChatGroq(groq_api_key=groq_api_key, model_name="qwen-2.5-32b", streaming=True) return llm
def load_LLM(groq_api_key):
"""Loads the ChatGroq model for processing."""
llm = ChatGroq(groq_api_key=groq_api_key, model_name="qwen-2.5-32b", streaming=True)
return llm
  • 該函式用於初始化 ChatGroq AI 模型。
  • 它使用大型語言模型 Qwen-2.5-32B。
  • streaming=True 可實現實時人工智慧響應。

第 9 步:收集使用者輸入

根據所選功能,提示使用者輸入文字、選擇語氣和方言(用於重寫),或為生成影象/視訊提供描述性輸入。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
st.header(f"{app_choice}")
st.markdown("Provide the required inputs below:")
with st.container():
if app_choice == "Rewrite Sentence":
draft = st.text_area("Draft Text", height=200, placeholder="Enter your text here...")
col1, col2 = st.columns(2)
with col1:
tone = st.selectbox("Select desired tone", options=["Formal", "Informal"])
with col2:
dialect = st.selectbox("Select dialect", options=[
"American English",
"British English",
"Australian English",
"Canadian English",
"Indian English"
])
st.header(f"{app_choice}") st.markdown("Provide the required inputs below:") with st.container(): if app_choice == "Rewrite Sentence": draft = st.text_area("Draft Text", height=200, placeholder="Enter your text here...") col1, col2 = st.columns(2) with col1: tone = st.selectbox("Select desired tone", options=["Formal", "Informal"]) with col2: dialect = st.selectbox("Select dialect", options=[ "American English", "British English", "Australian English", "Canadian English", "Indian English" ])
st.header(f"{app_choice}")
st.markdown("Provide the required inputs below:")
with st.container():
if app_choice == "Rewrite Sentence":
draft = st.text_area("Draft Text", height=200, placeholder="Enter your text here...")
col1, col2 = st.columns(2)
with col1:
tone = st.selectbox("Select desired tone", options=["Formal", "Informal"])
with col2:
dialect = st.selectbox("Select dialect", options=[
"American English", 
"British English", 
"Australian English", 
"Canadian English", 
"Indian English"
])
  • st.header(f"{app_choice}") 動態顯示所選應用程式的名稱。
  • st.container() 將相關的使用者介面元素分組。
  • st.text_area() 允許使用者輸入文字。
  • st.selectbox() 允許使用者選擇語氣(正式/非正式)和方言。

第 10 步:處理其他功能的輸入

根據所選功能動態調整輸入欄位,確保介面友好、適應性強。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
elif app_choice == "Image and Video Prompt Generator":
sentence = st.text_area("Sentence", height=200, placeholder="Enter a sentence describing your desired media...")
elif app_choice == "Text Simplifier":
complex_text = st.text_area("Complex Text", height=200, placeholder="Enter the complex text here...")
elif app_choice == "Image and Video Prompt Generator": sentence = st.text_area("Sentence", height=200, placeholder="Enter a sentence describing your desired media...") elif app_choice == "Text Simplifier": complex_text = st.text_area("Complex Text", height=200, placeholder="Enter the complex text here...")
elif app_choice == "Image and Video Prompt Generator":
sentence = st.text_area("Sentence", height=200, placeholder="Enter a sentence describing your desired media...")
elif app_choice == "Text Simplifier":
complex_text = st.text_area("Complex Text", height=200, placeholder="Enter the complex text here...")

該應用程式根據所選功能收集不同的輸入。

第 11 步:處理使用者輸入

點選“Process”按鈕後,載入人工智慧模型,使用 LLMChain 應用相關邏輯,並在 Streamlit 中顯示精煉輸出。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
if st.button("Process"):
with st.spinner("Processing your text..."):
llm = load_LLM(groq_api_key)
if app_choice == "Rewrite Sentence":
prompt_obj = PromptTemplate(input_variables=["tone", "dialect", "draft"], template=rewrite_template)
chain = LLMChain(llm=llm, prompt=prompt_obj)
result = chain.run(draft=draft, tone=tone, dialect=dialect)
elif app_choice == "Image and Video Prompt Generator":
prompt_obj = PromptTemplate(input_variables=["sentence"], template=image_video_template)
chain = LLMChain(llm=llm, prompt=prompt_obj)
result = chain.run(sentence=sentence)
elif app_choice == "Text Simplifier":
prompt_obj = PromptTemplate(input_variables=["complex_text"], template=text_simplifier_template)
chain = LLMChain(llm=llm, prompt=prompt_obj)
result = chain.run(complex_text=complex_text)
st.markdown("### Output:")
st.markdown(result)
if st.button("Process"): with st.spinner("Processing your text..."): llm = load_LLM(groq_api_key) if app_choice == "Rewrite Sentence": prompt_obj = PromptTemplate(input_variables=["tone", "dialect", "draft"], template=rewrite_template) chain = LLMChain(llm=llm, prompt=prompt_obj) result = chain.run(draft=draft, tone=tone, dialect=dialect) elif app_choice == "Image and Video Prompt Generator": prompt_obj = PromptTemplate(input_variables=["sentence"], template=image_video_template) chain = LLMChain(llm=llm, prompt=prompt_obj) result = chain.run(sentence=sentence) elif app_choice == "Text Simplifier": prompt_obj = PromptTemplate(input_variables=["complex_text"], template=text_simplifier_template) chain = LLMChain(llm=llm, prompt=prompt_obj) result = chain.run(complex_text=complex_text) st.markdown("### Output:") st.markdown(result)
if st.button("Process"):
with st.spinner("Processing your text..."):
llm = load_LLM(groq_api_key)
if app_choice == "Rewrite Sentence":
prompt_obj = PromptTemplate(input_variables=["tone", "dialect", "draft"], template=rewrite_template)
chain = LLMChain(llm=llm, prompt=prompt_obj)
result = chain.run(draft=draft, tone=tone, dialect=dialect)
elif app_choice == "Image and Video Prompt Generator":
prompt_obj = PromptTemplate(input_variables=["sentence"], template=image_video_template)
chain = LLMChain(llm=llm, prompt=prompt_obj)
result = chain.run(sentence=sentence)
elif app_choice == "Text Simplifier":
prompt_obj = PromptTemplate(input_variables=["complex_text"], template=text_simplifier_template)
chain = LLMChain(llm=llm, prompt=prompt_obj)
result = chain.run(complex_text=complex_text)
st.markdown("### Output:")
st.markdown(result)
  • st.button("Process"):點選後,開始處理文字。
  • st.spinner("Processing your text…"):顯示載入指示器。
  • load_LLM(groq_api_key):載入人工智慧模型。

它會根據所選功能

  • 選擇合適的 PromptTemplate。
  • 建立一個 LLMChain(LangChain 執行人工智慧模型的方式)。
  • 根據使用者輸入執行人工智慧模型。
  • 使用 st.markdown(result) 顯示最終結果。

GitHub 上獲取完整程式碼

輸出

重寫句子

影象和視訊提示生成器

文字簡化

重寫句子輸入

Yo, I’ve been grinding non-stop and bringing the heat, so I think it’s time we talk cash. I was hoping for a fatter paycheck—just wanna make sure my hustle and skills ain’t going unnoticed. Think we can make this work?

重寫句子輸出

重寫句子輸出

影象和視訊提示生成器輸入

A futuristic city with flying cars and neon lights.

影象和視訊提示生成器輸出

影象和視訊提示生成器輸出

文字簡化輸入

In recent years, the exponential advancements in artificial intelligence and machine learning algorithms have not only enhanced the efficiency of data processing and predictive analytics but have also introduced unprecedented challenges in ethical decision-making, data privacy, and algorithmic bias, necessitating a multidisciplinary approach that integrates computational sciences, legal frameworks, and ethical considerations to ensure the responsible deployment of AI-driven technologies across diverse sectors, including healthcare, finance, and autonomous systems.

文字簡化輸出

文字簡化輸出

小結

文字改進應用程式是一款強大的人工智慧驅動工具,旨在提高文字的清晰度、創造性和可讀性。它由 Streamlit 和 LangChain 共同開發,具有句子重寫、人工智慧提示生成和文字簡化等功能。它由 Groq 的 Qwen-2.5-32B 模型提供支援,可確保高質量的實時文字轉換,是專業人士、學生和內容創作者的必備工具。未來的升級,包括語音命令和多語言支援,將進一步增強其在構建寫作助手中的作用,使其更加通用和高效。有了這些進步,該應用程式將繼續推動寫作助手的發展,滿足不同使用者的需求。

  • 該應用程式利用 LangChain 和 Groq AI 高效地完善和簡化文字。
  • 使用者可以重寫句子、生成媒體提示和簡化文字,使其成為滿足不同需求的多功能工具。
  • 改寫句子功能支援語氣調整(正式/非正式)和方言定製。
  • 該應用採用 Streamlit 技術,為無縫文字處理提供了簡單的互動式體驗。
  • 新增多語言支援、語音輸入或其他人工智慧模型可進一步增強該應用的功能。

評論留言