
您是否想過如何利用人工智慧的力量讓複雜的任務變得更簡單?如果不需要高階技術技能就能建立人工智慧驅動的應用程式會怎樣?有了最先進的語言模型 DeepSeek-V3 和簡單的介面生成器 Gradio 等工具,建立人工智慧解決方案變得前所未有的簡單。無論您是要編寫 YouTube 指令碼、總結法律檔案還是規劃旅行,本指南都將向您展示如何結合這些工具來建立實用的應用程式。
學習目標
- 瞭解如何獲取 API 金鑰並將其整合到您的 Python 專案中。
- 使用 Gradio 為人工智慧應用程式建立引人入勝的直觀 Web 介面,讓沒有專業技術知識的使用者也能使用這些介面。
- 製作提示,引導 DeepSeek-V3 為不同應用生成所需的輸出。
- 構建可解決內容建立、市場營銷、法律分析、情感分析和旅遊規劃等實際問題的實踐應用。
- 瞭解DeepSeek-V3和Gradio如何利用提示工程簡化人工智慧應用開發。
瞭解DeepSeek-V3
DeepSeek-V3 是一種先進的語言模型,旨在處理各種複雜的自然語言處理(NLP)任務。無論您需要生成創意內容、總結長文字,還是分析程式碼,DeepSeek-V3都能為您帶來高水平的複雜性和細微差別。它的架構利用先進的深度學習技術,能夠理解上下文,生成連貫的響應,甚至能根據提供的指令調整語氣。這種靈活性使其成為各種應用的理想選擇。
瞭解Gradio

Source: Gradio
Gradio 是一個功能強大而又簡單易用的 python 庫,它能讓開發人員以最小的工作量為機器學習模型建立互動式網路介面。無需從頭開始建立使用者介面,Gradio 可以將模型封裝在一個簡單的函式中,並自動生成一個美觀、使用者友好的網路應用程式。Gradio具有拖放的簡便性,是DeepSeek-V3的完美伴侶,可實現人工智慧應用的快速原型開發和無縫部署。
在本指南中,我們將把每個應用分解成簡單易懂的步驟。這種全面的方法將確保即使是人工智慧開發的新手也能自信地跟上並構建自己的創新應用程式。
前提條件和設定
在開始應用程式開發之前,請確保您已準備就緒:
Deepseek API金鑰
- 訪問 DeepInfra 的官方網站,註冊或登入,然後導航到“Dashboard”。
- 在“API keys”部分,點選“New API key”,提供名稱並生成金鑰。
- 注意:您只能檢視一次 API 金鑰,請妥善保管。
安裝所需的依賴項
開啟終端並執行
pip install gradio openai
pip install gradio openai
pip install gradio openai
您需要使用 pip 安裝 Gradio 和 OpenAI 客戶端庫(與 DeepSeek-V3 相容)。
環境設定
首先匯入必要的庫,並使用 API 金鑰初始化客戶端。此外,建立一個新的 Python 檔案,例如 app.py,然後插入下面提供的程式碼。
# Replace "YOUR_API_KEY" with the actual API key you obtained from DeepInfra.
base_url="https://api.deepinfra.com/v1/openai",
import openai
import gradio as gr
# Replace "YOUR_API_KEY" with the actual API key you obtained from DeepInfra.
API_KEY = "YOUR_API_KEY"
client = openai.OpenAI(
api_key=API_KEY,
base_url="https://api.deepinfra.com/v1/openai",
)
import openai
import gradio as gr
# Replace "YOUR_API_KEY" with the actual API key you obtained from DeepInfra.
API_KEY = "YOUR_API_KEY"
client = openai.OpenAI(
api_key=API_KEY,
base_url="https://api.deepinfra.com/v1/openai",
)
YouTube指令碼撰寫器
YouTube 指令碼作家應用程式利用 Deepseek-V3 的創意功能,根據給定主題生成詳細的視訊指令碼。該應用程式通過提供連貫的敘事大綱,簡化了指令碼編寫過程,是內容創作者尋找靈感的絕佳選擇。
- 如上圖所示,初始化客戶端。
- 我們定義了一個函式,呼叫 DeepSeek-V3 模型,以 YouTube 內容創作專家的身份,根據提供的主題生成 YouTube 指令碼。
def generate_script(topic: str) -> str:
Generate a detailed YouTube script based on the provided topic using the DeepSeek-V3 model.
topic (str): The subject or topic for which the YouTube script is to be generated.
str: The generated YouTube script as a string. If an error occurs during generation, an error message is returned.
response = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V3",
{"role": "system", "content": "You are an expert YouTube content creator."},
{"role": "user", "content": f"Write a detailed YouTube script for a video about '{topic}'."}
return response.choices[0].message.content.strip()
return f"Error: {str(e)}"
def generate_script(topic: str) -> str:
"""
Generate a detailed YouTube script based on the provided topic using the DeepSeek-V3 model.
Args:
topic (str): The subject or topic for which the YouTube script is to be generated.
Returns:
str: The generated YouTube script as a string. If an error occurs during generation, an error message is returned.
"""
try:
response = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V3",
messages=[
{"role": "system", "content": "You are an expert YouTube content creator."},
{"role": "user", "content": f"Write a detailed YouTube script for a video about '{topic}'."}
],
max_tokens=300,
temperature=0.7
)
return response.choices[0].message.content.strip()
except Exception as e:
return f"Error: {str(e)}"
def generate_script(topic: str) -> str:
"""
Generate a detailed YouTube script based on the provided topic using the DeepSeek-V3 model.
Args:
topic (str): The subject or topic for which the YouTube script is to be generated.
Returns:
str: The generated YouTube script as a string. If an error occurs during generation, an error message is returned.
"""
try:
response = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V3",
messages=[
{"role": "system", "content": "You are an expert YouTube content creator."},
{"role": "user", "content": f"Write a detailed YouTube script for a video about '{topic}'."}
],
max_tokens=300,
temperature=0.7
)
return response.choices[0].message.content.strip()
except Exception as e:
return f"Error: {str(e)}"
- 然後,我們建立一個簡單的 Gradio 介面,接受使用者輸入(一個視訊主題)並顯示生成的指令碼。
# Create Gradio interface for the YouTube Script Writer
def app_interface(topic: str) -> str:
Generate a YouTube script based on the given topic.
topic (str): The subject or theme for which the script should be generated.
str: The generated YouTube script or an error message if generation fails.
return generate_script(topic)
interface = gr.Interface(
inputs=gr.Textbox(label="Video Topic"),
outputs=gr.Textbox(label="Generated YouTube Script"),
title="YouTube Script Writer"
print(f"Failed to launch Gradio interface: {e}")
# Create Gradio interface for the YouTube Script Writer
def app_interface(topic: str) -> str:
"""
Generate a YouTube script based on the given topic.
Args:
topic (str): The subject or theme for which the script should be generated.
Returns:
str: The generated YouTube script or an error message if generation fails.
"""
return generate_script(topic)
try:
interface = gr.Interface(
fn=app_interface,
inputs=gr.Textbox(label="Video Topic"),
outputs=gr.Textbox(label="Generated YouTube Script"),
title="YouTube Script Writer"
)
interface.launch()
except Exception as e:
print(f"Failed to launch Gradio interface: {e}")
# Create Gradio interface for the YouTube Script Writer
def app_interface(topic: str) -> str:
"""
Generate a YouTube script based on the given topic.
Args:
topic (str): The subject or theme for which the script should be generated.
Returns:
str: The generated YouTube script or an error message if generation fails.
"""
return generate_script(topic)
try:
interface = gr.Interface(
fn=app_interface,
inputs=gr.Textbox(label="Video Topic"),
outputs=gr.Textbox(label="Generated YouTube Script"),
title="YouTube Script Writer"
)
interface.launch()
except Exception as e:
print(f"Failed to launch Gradio interface: {e}")
- 在終端執行整個程式碼(python app.py)後,就能看到下面的介面。
- 給出任何你喜歡的主題,然後點選提交。嘭!一鍵就能得到回覆。你還可以點選標記,將回復儲存到本地檔案中。

營銷AI助手
這款應用程式旨在幫助營銷專業人員生成有說服力的產品描述、社交媒體帖子和活動創意。Deepseek-V3 將充當營銷專家助理,確保生成的內容引人入勝、切中要害。
- 重複使用之前定義的初始化程式碼。
- 我們現在建立一個函式,向DeepSeek-V3傳送生成營銷文案的提示。我們輸入了一個詳細的提示,指示模型為指定產品生成全面的營銷描述。
def generate_marketing_copy(product: str) -> str:
Generate a marketing description for a given product.
This function leverages the DeepSeek-V3 model to create a marketing copy that includes details on the target audience,
key features, emotional appeal, and a call-to-action for the product.
product (str): The product for which the marketing copy should be generated.
str: The generated marketing copy or an error message if an exception occurs.
Write a marketing description for {product}. Include:
- Target audience (age, interests)
response = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V3",
{"role": "system", "content": "You are a marketing strategist."},
{"role": "user", "content": prompt}
return response.choices[0].message.content
return f"Error: {str(e)}"
def generate_marketing_copy(product: str) -> str:
"""
Generate a marketing description for a given product.
This function leverages the DeepSeek-V3 model to create a marketing copy that includes details on the target audience,
key features, emotional appeal, and a call-to-action for the product.
Args:
product (str): The product for which the marketing copy should be generated.
Returns:
str: The generated marketing copy or an error message if an exception occurs.
"""
prompt = f"""
Write a marketing description for {product}. Include:
- Target audience (age, interests)
- Key features
- Emotional appeal
- Call-to-action
"""
try:
response = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V3",
messages=[
{"role": "system", "content": "You are a marketing strategist."},
{"role": "user", "content": prompt}
],
max_tokens=300,
)
return response.choices[0].message.content
except Exception as e:
return f"Error: {str(e)}"
def generate_marketing_copy(product: str) -> str:
"""
Generate a marketing description for a given product.
This function leverages the DeepSeek-V3 model to create a marketing copy that includes details on the target audience,
key features, emotional appeal, and a call-to-action for the product.
Args:
product (str): The product for which the marketing copy should be generated.
Returns:
str: The generated marketing copy or an error message if an exception occurs.
"""
prompt = f"""
Write a marketing description for {product}. Include:
- Target audience (age, interests)
- Key features
- Emotional appeal
- Call-to-action
"""
try:
response = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V3",
messages=[
{"role": "system", "content": "You are a marketing strategist."},
{"role": "user", "content": prompt}
],
max_tokens=300,
)
return response.choices[0].message.content
except Exception as e:
return f"Error: {str(e)}"
- 我們現在設計 Gradio 介面,以便與營銷文案功能進行互動。
def app_interface(product_name: str) -> str:
Generates a compelling marketing description for the specified product.
product_name (str): The name of the product for which to generate a description.
str: The generated marketing description or an error message if generation fails.
prompt = f"Write a compelling marketing description for the product '{product_name}'."
return generate_text(prompt)
return f"Error: {str(e)}"
interface = gr.Interface(
inputs=gr.Textbox(label="Product Name"),
outputs=gr.Textbox(label="Generated Description"),
title="Marketing AI Assistant"
print(f"Failed to launch Gradio interface: {e}")
def app_interface(product_name: str) -> str:
"""
Generates a compelling marketing description for the specified product.
Args:
product_name (str): The name of the product for which to generate a description.
Returns:
str: The generated marketing description or an error message if generation fails.
"""
prompt = f"Write a compelling marketing description for the product '{product_name}'."
try:
return generate_text(prompt)
except Exception as e:
return f"Error: {str(e)}"
try:
interface = gr.Interface(
fn=app_interface,
inputs=gr.Textbox(label="Product Name"),
outputs=gr.Textbox(label="Generated Description"),
title="Marketing AI Assistant"
)
interface.launch()
except Exception as e:
print(f"Failed to launch Gradio interface: {e}")
def app_interface(product_name: str) -> str:
"""
Generates a compelling marketing description for the specified product.
Args:
product_name (str): The name of the product for which to generate a description.
Returns:
str: The generated marketing description or an error message if generation fails.
"""
prompt = f"Write a compelling marketing description for the product '{product_name}'."
try:
return generate_text(prompt)
except Exception as e:
return f"Error: {str(e)}"
try:
interface = gr.Interface(
fn=app_interface,
inputs=gr.Textbox(label="Product Name"),
outputs=gr.Textbox(label="Generated Description"),
title="Marketing AI Assistant"
)
interface.launch()
except Exception as e:
print(f"Failed to launch Gradio interface: {e}")
- 在終端執行整個程式碼(python app.py)後,您將可以看到下面的螢幕。
- 輸入產品名稱並單擊提交以獲得響應。

法律檔案摘要器
法律檔案通常內容繁雜,語言複雜。Legal Document Summarizer 應用程式可生成簡明摘要,突出義務、處罰和終止條款等關鍵要點,從而簡化這些檔案。對於需要快速掌握冗長檔案精髓的法律專業人士和學生來說,這款應用程式尤其有用。
- 除標準庫外,此應用程式還使用 PyPDF2 等 PDF 閱讀庫。如果尚未安裝,請務必安裝:
pip install PyPDF2
- 重複使用之前定義的初始化程式碼。
- 與之前的應用程式類似,我們使用 DeepSeek-V3 API 金鑰設定 API 客戶端。
- 然後,我們建立一個函式,讀取上傳的 PDF,提取文字,然後將文字傳送到 DeepSeek-V3 進行摘要。
def summarize_legal_doc(pdf_file: Any) -> str:
Extract and summarize the text from a legal PDF document.
This function uses PyPDF2 to read and extract text from the provided PDF file.
The extracted text is then sent to the DeepSeek-V3 model to produce a summary
in the form of 5 bullet points, emphasizing obligations, penalties, and termination clauses.
pdf_file (Any): A file-like object representing the uploaded PDF. It must have a 'name' attribute.
str: The summarized legal document. Returns an error message if no file is provided or if an error occurs.
return "No file uploaded."
# Extract text from the PDF using PyPDF2
reader = PyPDF2.PdfReader(pdf_file.name)
for page in reader.pages:
page_text = page.extract_text()
extracted_text += page_text + "\n"
# Prepare the messages for the DeepSeek-V3 summarization request
"Summarize this legal document into 5 bullet points. "
"Highlight obligations, penalties, and termination clauses."
"content": extracted_text
# Request the summary from DeepSeek-V3
response = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V3",
temperature=0.2 # Lower temperature for factual accuracy
return response.choices[0].message.content.strip()
return f"Error: {str(e)}"
from typing import Any
def summarize_legal_doc(pdf_file: Any) -> str:
"""
Extract and summarize the text from a legal PDF document.
This function uses PyPDF2 to read and extract text from the provided PDF file.
The extracted text is then sent to the DeepSeek-V3 model to produce a summary
in the form of 5 bullet points, emphasizing obligations, penalties, and termination clauses.
Args:
pdf_file (Any): A file-like object representing the uploaded PDF. It must have a 'name' attribute.
Returns:
str: The summarized legal document. Returns an error message if no file is provided or if an error occurs.
"""
if pdf_file is None:
return "No file uploaded."
try:
# Extract text from the PDF using PyPDF2
reader = PyPDF2.PdfReader(pdf_file.name)
extracted_text = ""
for page in reader.pages:
page_text = page.extract_text()
if page_text:
extracted_text += page_text + "\n"
# Prepare the messages for the DeepSeek-V3 summarization request
messages = [
{
"role": "system",
"content": (
"Summarize this legal document into 5 bullet points. "
"Highlight obligations, penalties, and termination clauses."
)
},
{
"role": "user",
"content": extracted_text
}
]
# Request the summary from DeepSeek-V3
response = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V3",
messages=messages,
temperature=0.2 # Lower temperature for factual accuracy
)
return response.choices[0].message.content.strip()
except Exception as e:
return f"Error: {str(e)}"
from typing import Any
def summarize_legal_doc(pdf_file: Any) -> str:
"""
Extract and summarize the text from a legal PDF document.
This function uses PyPDF2 to read and extract text from the provided PDF file.
The extracted text is then sent to the DeepSeek-V3 model to produce a summary
in the form of 5 bullet points, emphasizing obligations, penalties, and termination clauses.
Args:
pdf_file (Any): A file-like object representing the uploaded PDF. It must have a 'name' attribute.
Returns:
str: The summarized legal document. Returns an error message if no file is provided or if an error occurs.
"""
if pdf_file is None:
return "No file uploaded."
try:
# Extract text from the PDF using PyPDF2
reader = PyPDF2.PdfReader(pdf_file.name)
extracted_text = ""
for page in reader.pages:
page_text = page.extract_text()
if page_text:
extracted_text += page_text + "\n"
# Prepare the messages for the DeepSeek-V3 summarization request
messages = [
{
"role": "system",
"content": (
"Summarize this legal document into 5 bullet points. "
"Highlight obligations, penalties, and termination clauses."
)
},
{
"role": "user",
"content": extracted_text
}
]
# Request the summary from DeepSeek-V3
response = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V3",
messages=messages,
temperature=0.2 # Lower temperature for factual accuracy
)
return response.choices[0].message.content.strip()
except Exception as e:
return f"Error: {str(e)}"
最後,我們建立了一個 Gradio 介面,允許使用者上傳 PDF 並檢視生成的摘要。
# Create a Gradio interface
interface = gr.Interface(
inputs=gr.File(label="Upload PDF Document"),
outputs=gr.Textbox(label="Summary"),
title="Legal Document Summarizer"
print(f"Failed to launch Gradio interface: {e}")
try:
# Create a Gradio interface
interface = gr.Interface(
fn=summarize_legal_doc,
inputs=gr.File(label="Upload PDF Document"),
outputs=gr.Textbox(label="Summary"),
title="Legal Document Summarizer"
)
# Launch the app
interface.launch()
except Exception as e:
print(f"Failed to launch Gradio interface: {e}")
try:
# Create a Gradio interface
interface = gr.Interface(
fn=summarize_legal_doc,
inputs=gr.File(label="Upload PDF Document"),
outputs=gr.Textbox(label="Summary"),
title="Legal Document Summarizer"
)
# Launch the app
interface.launch()
except Exception as e:
print(f"Failed to launch Gradio interface: {e}")
在終端執行 app.py 檔案。這個應用程式允許你上傳 pdf 文件,並給出文件摘要。

資料來源 測試上述應用程式時使用了 Kaggle 提供的 pdf 文件 。
情感分析應用程式
瞭解一段文字背後的情感對於衡量公眾輿論、分析客戶反饋或監控社交媒體趨勢至關重要。情感分析應用程式使用 DeepSeek-V3 以描述性的方式確定給定文字是正面、負面還是中性。
- 同樣,我們從客戶端的標準初始化開始。
- 我們建立一個分析輸入文字情感的函式。
def analyze_sentiment(text: str) -> str:
Analyze the sentiment of a given text using the DeepSeek-V3 model.
This function sends the provided text to the DeepSeek-V3 model with a prompt to analyze sentiment
and returns the analysis result.
text (str): The input text for sentiment analysis.
str: The sentiment analysis result or an error message if an exception is raised.
response = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V3",
{"role": "system", "content": "You are an expert in sentiment analysis."},
{"role": "user", "content": f"Analyze the sentiment of this text: {text}"}
return response.choices[0].message.content.strip()
return f"Error: {str(e)}"
def analyze_sentiment(text: str) -> str:
"""
Analyze the sentiment of a given text using the DeepSeek-V3 model.
This function sends the provided text to the DeepSeek-V3 model with a prompt to analyze sentiment
and returns the analysis result.
Args:
text (str): The input text for sentiment analysis.
Returns:
str: The sentiment analysis result or an error message if an exception is raised.
"""
try:
response = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V3",
messages=[
{"role": "system", "content": "You are an expert in sentiment analysis."},
{"role": "user", "content": f"Analyze the sentiment of this text: {text}"}
],
max_tokens=150,
temperature=0.5
)
return response.choices[0].message.content.strip()
except Exception as e:
return f"Error: {str(e)}"
def analyze_sentiment(text: str) -> str:
"""
Analyze the sentiment of a given text using the DeepSeek-V3 model.
This function sends the provided text to the DeepSeek-V3 model with a prompt to analyze sentiment
and returns the analysis result.
Args:
text (str): The input text for sentiment analysis.
Returns:
str: The sentiment analysis result or an error message if an exception is raised.
"""
try:
response = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V3",
messages=[
{"role": "system", "content": "You are an expert in sentiment analysis."},
{"role": "user", "content": f"Analyze the sentiment of this text: {text}"}
],
max_tokens=150,
temperature=0.5
)
return response.choices[0].message.content.strip()
except Exception as e:
return f"Error: {str(e)}"
- 我們建立了一個介面,允許使用者輸入文字並檢視情感分析結果。該函式直接將使用者文字傳遞給情感分析函式。
def sentiment_interface(text: str) -> str:
Serve as an interface function to analyze sentiment of the provided text.
text (str): The input text to be analyzed.
str: The result of the sentiment analysis.
return analyze_sentiment(text)
interface = gr.Interface(
inputs=gr.Textbox(label="Enter Text"),
outputs=gr.Textbox(label="Sentiment Analysis"),
title="Sentiment Analysis App"
print(f"Failed to launch Gradio interface: {e}")
def sentiment_interface(text: str) -> str:
"""
Serve as an interface function to analyze sentiment of the provided text.
Args:
text (str): The input text to be analyzed.
Returns:
str: The result of the sentiment analysis.
"""
return analyze_sentiment(text)
try:
interface = gr.Interface(
fn=sentiment_interface,
inputs=gr.Textbox(label="Enter Text"),
outputs=gr.Textbox(label="Sentiment Analysis"),
title="Sentiment Analysis App"
)
interface.launch()
except Exception as e:
print(f"Failed to launch Gradio interface: {e}")
def sentiment_interface(text: str) -> str:
"""
Serve as an interface function to analyze sentiment of the provided text.
Args:
text (str): The input text to be analyzed.
Returns:
str: The result of the sentiment analysis.
"""
return analyze_sentiment(text)
try:
interface = gr.Interface(
fn=sentiment_interface,
inputs=gr.Textbox(label="Enter Text"),
outputs=gr.Textbox(label="Sentiment Analysis"),
title="Sentiment Analysis App"
)
interface.launch()
except Exception as e:
print(f"Failed to launch Gradio interface: {e}")

旅行行程計劃器
計劃旅行可能會讓人不知所措,但旅行行程計劃器應用程式可以根據使用者輸入的資訊生成詳細的行程,從而簡化了這一過程。使用者只需指定目的地、天數和興趣愛好,就能獲得個性化的旅行計劃,包括活動建議、當地美食推薦和交通提示。
- 再次使用標準初始化程式碼。
- 我們建立一個函式,根據使用者輸入構建詳細的旅行路線。我們建立的提示包括所有必要細節(目的地、持續時間、興趣愛好)和具體說明,其中包括一天中的不同時段、美食推薦和交通提示。
def plan_itinerary(destination: str, days: int, interests: str) -> str:
Generate a travel itinerary for the specified destination, duration, and interests.
This function uses the DeepSeek-V3 model to create a detailed travel itinerary that includes activities for different times of the day,
local cuisine recommendations, and transportation tips.
destination (str): The destination for the travel itinerary.
days (int): The number of days for the itinerary.
interests (str): The travel interests (e.g., "Adventure", "Cultural", "Relaxation").
str: The generated itinerary text, or an error message if an exception occurs.
Create a {days}-day itinerary for {destination}. Focus on {interests}.
- Morning/Afternoon/Evening activities
- Local cuisine recommendations
response = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V3",
{"role": "system", "content": "You are a travel expert."},
{"role": "user", "content": prompt}
return response.choices[0].message.content.strip()
return f"Error: {str(e)}"
def plan_itinerary(destination: str, days: int, interests: str) -> str:
"""
Generate a travel itinerary for the specified destination, duration, and interests.
This function uses the DeepSeek-V3 model to create a detailed travel itinerary that includes activities for different times of the day,
local cuisine recommendations, and transportation tips.
Args:
destination (str): The destination for the travel itinerary.
days (int): The number of days for the itinerary.
interests (str): The travel interests (e.g., "Adventure", "Cultural", "Relaxation").
Returns:
str: The generated itinerary text, or an error message if an exception occurs.
"""
prompt = f"""
Create a {days}-day itinerary for {destination}. Focus on {interests}.
Include:
- Morning/Afternoon/Evening activities
- Local cuisine recommendations
- Transportation tips
"""
try:
response = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V3",
messages=[
{"role": "system", "content": "You are a travel expert."},
{"role": "user", "content": prompt}
],
max_tokens=500
)
return response.choices[0].message.content.strip()
except Exception as e:
return f"Error: {str(e)}"
def plan_itinerary(destination: str, days: int, interests: str) -> str:
"""
Generate a travel itinerary for the specified destination, duration, and interests.
This function uses the DeepSeek-V3 model to create a detailed travel itinerary that includes activities for different times of the day,
local cuisine recommendations, and transportation tips.
Args:
destination (str): The destination for the travel itinerary.
days (int): The number of days for the itinerary.
interests (str): The travel interests (e.g., "Adventure", "Cultural", "Relaxation").
Returns:
str: The generated itinerary text, or an error message if an exception occurs.
"""
prompt = f"""
Create a {days}-day itinerary for {destination}. Focus on {interests}.
Include:
- Morning/Afternoon/Evening activities
- Local cuisine recommendations
- Transportation tips
"""
try:
response = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V3",
messages=[
{"role": "system", "content": "You are a travel expert."},
{"role": "user", "content": prompt}
],
max_tokens=500
)
return response.choices[0].message.content.strip()
except Exception as e:
return f"Error: {str(e)}"
- 在文字框中顯示生成的行程,並以網路應用程式的形式啟動介面。行程計劃器的介面設計可捕捉使用者的多種輸入。
interface = gr.Interface(
gr.Textbox(label="Destination"),
gr.Number(label="Number of Days"),
gr.Dropdown(["Adventure", "Cultural", "Relaxation"], label="Interests")
outputs=gr.Textbox(label="Itinerary"),
title="Travel Itinerary Planner"
print(f"Failed to launch Gradio interface: {e}")
try:
interface = gr.Interface(
fn=plan_itinerary,
inputs=[
gr.Textbox(label="Destination"),
gr.Number(label="Number of Days"),
gr.Dropdown(["Adventure", "Cultural", "Relaxation"], label="Interests")
],
outputs=gr.Textbox(label="Itinerary"),
title="Travel Itinerary Planner"
)
interface.launch()
except Exception as e:
print(f"Failed to launch Gradio interface: {e}")
try:
interface = gr.Interface(
fn=plan_itinerary,
inputs=[
gr.Textbox(label="Destination"),
gr.Number(label="Number of Days"),
gr.Dropdown(["Adventure", "Cultural", "Relaxation"], label="Interests")
],
outputs=gr.Textbox(label="Itinerary"),
title="Travel Itinerary Planner"
)
interface.launch()
except Exception as e:
print(f"Failed to launch Gradio interface: {e}")

構建人工智慧應用程式的最佳實踐
在您完成這些專案時,請考慮以下最佳實踐,以確保您的應用程式具有健壯性和可維護性:
- 錯誤處理:在函式中使用 try-except 塊來優雅地管理 API 錯誤。
- 調整引數:使用不同的引數來獲得所需的輸出。
- 快取響應:為了儘量減少重複的 API 呼叫並降低延遲,請考慮在適當的情況下快取響應。
- 使用者反饋:當出現錯誤或應用程式正在處理使用者請求時,為使用者提供清晰的資訊。
- 安全性:始終保持 API 金鑰的安全性,不要在公共儲存庫中公開這些金鑰。
小結
通過使用提示工程將 DeepSeek-V3 和 Gradio 整合在一起,開發人員可以開啟人工智慧應用開發的無限可能。本指南詳細介紹瞭如何構建五個不同領域的人工智慧應用程式。無論您是經驗豐富的開發人員,還是剛剛起步,這些工具都能讓您進行實驗、創新,並迅速將您的想法付諸實踐。隨著人工智慧技術的不斷髮展,這裡討論的工具和技術只會變得更加強大。今天接受這些創新,就能為未來做好準備,讓人工智慧驅動的解決方案融入工作和生活的方方面面。
- 利用 DeepSeek-V3 和 Gradio 使用提示工程,開發人員可以輕鬆構建人工智慧驅動的應用程式,實現無縫的自然語言處理和直觀的人工智慧部署。
- 每個應用程式都是一步一步構建的,並附有詳細說明,使初學者也能輕鬆掌握,同時還能為高階使用者提供強大的解決方案。
- 通過展示人工智慧的廣泛適用性,本指南涵蓋了從創意內容生成和營銷到法律摘要和旅行規劃等一系列應用。
- 根據具體要求定製引數、系統提示和介面元素,並在實際場景中擴充套件解決方案。
- 通過模組化程式碼和詳細提示,這些應用程式可以輕鬆定製和擴充套件,以滿足特定要求或整合到更大的系統中。
評論留言