Building AI-Powered Apps with DeepSeek-V3 and Gradio Using Prompt Engineering

Krishnaveni Ponna Last Updated : 12 Mar, 2025
10 min read

Have you ever thought about how to use the power of artificial intelligence to make complex tasks easier? What if you could create AI-driven applications without needing advanced technical skills? With tools like DeepSeek-V3, a state-of-the-art language model, and Gradio, a simple interface builder, building AI solutions has never been more straightforward. Whether you’re writing YouTube scripts, summarizing legal documents, or planning a trip, this guide will show you how to combine these tools to create practical applications.

Learning Objectives

  • Learn how to obtain your API key and integrate it into your Python projects.
  • Create engaging and intuitive web interfaces for AI applications, making them accessible to users without technical expertise using Gradio.
  • Crafting prompts that guide DeepSeek-V3 to produce desired outputs for different applications.
  • Build hand-on applications that address practical problems in content creation, marketing, legal analysis, sentiment analysis, and travel planning.
  • Understand how DeepSeek-V3 and Gradio Using Prompt Engineering can streamline AI application development.

This article was published as a part of the Data Science Blogathon.

Understanding DeepSeek-V3

DeepSeek-V3 is a state-of-the-art language model designed to handle a wide range of complex natural language processing (NLP) tasks. Whether you need to generate creative content, summarize long texts, or even analyze code, DeepSeek-V3 brings a high level of sophistication and nuance to the table. Its architecture leverages advanced deep learning techniques that allow it to understand context, generate coherent responses, and even adapt its tone based on provided instructions. This flexibility makes it ideal for a diverse set of applications.

Read more about Deepseek V3 – here

Understanding Gradio

gradio
Source: Gradio

Gradio is a powerful yet easy-to-use python library that allows developers to create interactive web interfaces for machine learning models with minimal effort. Instead of building a user interface from scratch, Gradio lets you wrap your model in a simple function and automatically generate an attractive and user-friendly web app. With its drag-and-drop simplicity, Gradio is the perfect companion for DeepSeek-V3, enabling rapid prototyping and seamless deployment of AI applications.

Read more about Gradio – here

Throughout this guide, we’ll break down each application into easy-to-follow steps. This comprehensive approach will ensure that even those who are new to AI development can confidently follow along and build their own innovative apps.

Prerequisites and Setup

Before diving into app development, ensure you have the following ready:

Deepseek API Key

  • Visit DeepInfra’s official website, sign up or log in, and navigate to the Dashboard.
  • Under the “API keys” section, click on “New API key”, provide a name, and generate your key.
  • Note: You can view your API key only once, so store it securely.

Installation of Required Dependencies

Open your terminal and run

pip install gradio openai

You need to install Gradio and the OpenAI client library (which is compatible with DeepSeek-V3) using pip.

Environment Setup

Start by importing the necessary libraries and initializing the client with your API key. Also, create a new Python file, for example, app.py and then insert the code provided below.  

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 Script Writer

The YouTube Script Writer app leverages Deepseek-V3’s creative capabilities to generate detailed video scripts based on a given topic. Perfect for content creators looking for inspiration, this app simplifies the script-writing process by providing a coherent narrative outline.

  • Initialize the client as shown above.
  • We define a function that calls the DeepSeek-V3 model to generate a YouTube script based on a provided topic as an expert YouTube content creator.
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)}"
  • We then create a simple Gradio interface that accepts user input (a video topic) and displays the generated script.
# 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}") 
  • Once you run the entire code (python app.py) in terminal, you will be able to view the below screen.
  • Give any topic you like and hit Submit. Boom! get a response in one click. You can hit flag to save the response in a file locally.
YouTube Script Writer; DeepSeek-V3 and Gradio Using Prompt Engineering
Source: Author

Marketing AI Assistant

This app is designed to aid marketing professionals by generating persuasive product descriptions, social media posts, and campaign ideas. Deepseek-V3 is prompted to act as an expert marketing assistant, ensuring the generated content is engaging and on point.

  • Reuse the previously defined initialization code.
  • We now create a function that sends a prompt to DeepSeek-V3 for generating marketing copy. We entered a detailed prompt that instructs the model to generate a comprehensive marketing description for the specified product.
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)}" 
  • We now design the Gradio interface to interact with the marketing copy function.
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}")
  • Once you run the entire code (python app.py) in terminal, you will be able to view the below screen.
  • Enter the Product name and click submit to get the response.
Marketing AI Assistant; DeepSeek-V3 and Gradio Using Prompt Engineering
Source: Author

Legal documents are often dense and filled with complex language. The Legal Document Summarizer app simplifies these documents by generating a concise summary, highlighting critical points such as obligations, penalties, and termination clauses. This app is particularly useful for legal professionals and students who need to quickly grasp the essence of lengthy documents.

  • In addition to the standard libraries, this app uses a PDF reading library such as PyPDF2. Make sure you install it if you haven’t already:
pip install PyPDF2
  • Reuse the previously defined initialization code.
  • Similar to previous apps, we set up the API client with your DeepSeek-V3 API key.
  • We then create a function that reads an uploaded PDF, extracts its text, and then sends the text to DeepSeek-V3 for summarization.
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)}"

Finally, we create a Gradio interface that allows users to upload a PDF and view the generated summary.

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}") 

Run the app.py file in the terminal. This app allows you to upload the pdf document and gives the summary of it.

Legal Document Summarizer; DeepSeek-V3 and Gradio Using Prompt Engineering
Source: Author

Source: Used the document pdf from Kaggle for testing the above app.

Sentiment Analysis App

Understanding the sentiment behind a piece of text is essential for gauging public opinion, analyzing customer feedback, or monitoring social media trends. The Sentiment Analysis app uses DeepSeek-V3 to determine whether a given text is positive, negative, or neutral in a descriptive manner.

  • Again, we start with our standard initialization of the client.
  • We create a function that analyzes the sentiment of the input text.
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)}"
  • We build an interface that allows users to input text and see the sentiment analysis. This function directly passes the user’s text to the sentiment analysis function.
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}")
  • Once the app is launched, you can insert the text and get the response.
Sentiment Analysis App; DeepSeek-V3 and Gradio Using Prompt Engineering
Source: Author

Travel Itinerary Planner

Planning a trip can be overwhelming, but the Travel Itinerary Planner app simplifies the process by generating detailed itineraries based on user input. By specifying a destination, the number of days, and interests, users receive a personalized travel plan complete with activity suggestions, local cuisine recommendations, and transportation tips.

  • Use the standard initialization code once more.
  • We create a function that constructs a detailed travel itinerary based on user inputs. We construct a prompt that includes all necessary details (destination, duration, interests) and specific instructions to include different parts of the day, cuisine recommendations, and transportation tips.
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)}"
  • Displays the generated itinerary in a textbox and launches the interface as a web app. The interface for the itinerary planner is designed to capture multiple inputs from the user.
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}")
Travel Itinerary Planner; DeepSeek-V3 and Gradio Using Prompt Engineering
Source: Author

Best Practices for Building AI Apps

As you work through these projects, consider the following best practices to ensure your apps are robust and maintainable:

  • Error Handling: Use try-except blocks in your functions to manage API errors gracefully.
  • Tweek parameters: Play with different parameters to get the desired output.
  • Caching Responses: To minimize repeated API calls and reduce latency, consider caching responses where applicable.
  • User Feedback: Include clear messages for users when errors occur or when the app is processing their requests.
  • Security: Always keep your API keys secure and do not expose them in public repositories.

Conclusion

By integrating DeepSeek-V3 and Gradio Using Prompt Engineering, developers can unlock a world of possibilities in AI application development. This guide has provided an extensive walkthrough of building five distinct AI apps that cater to various domains. Whether you’re a seasoned developer or just starting out, these tools empower you to experiment, innovate, and bring your ideas to life quickly. As AI technology continues to evolve, the tools and techniques discussed here will only become more powerful. Embracing these innovations today prepares you for a future where AI-driven solutions are integral to all aspects of work and life.

Also read: 7 real-world applications of deepseek-v3

Key Takeaways

  • Leveraging DeepSeek-V3 and Gradio Using Prompt Engineering allows developers to build AI-driven applications with ease, enabling seamless natural language processing and intuitive AI deployment.
  • Each app is built step by step with detailed explanations, making it accessible to beginners while still offering robust solutions for advanced users.
  • The guide covers a range of applications from creative content generation and marketing to legal summarization and travel planning by demonstrating the broad applicability of AI.
  • Tailor parameters, system prompts and interface elements to suit specific requirements and scale your solutions in real-world scenarios.
  • With modular code and detailed prompts, these apps can be easily customized and scaled to meet specific requirements or integrated into larger systems.

Frequently Asked Questions

Q1: Is the DeepSeek-V3 API free to use?

A: DeepSeek-V3 offers a free tier with specific rate limits. For more advanced usage, please refer to DeepInfra’s pricing page for details.

Q2: Can I customize the prompts used in these apps?

A: Absolutely. One of the key strengths of DeepSeek-V3 is its adaptability. You can modify the system and user messages to tailor the output for different applications or industries.

Q3: Are these applications production-ready?

A: While the provided code serves as a strong foundation, further testing, optimization, and security enhancements are recommended before deploying in a production environment.

Q4: Is Gradio the only option for building the app interfaces?  

A: Yes, the modular design of these applications allows for easy integration with other web frameworks like Streamlit etc, mobile apps, or enterprise systems.

The media shown in this article is not owned by Analytics Vidhya and is used at the Author’s discretion.

Hello! I'm a passionate AI and Machine Learning enthusiast currently exploring the exciting realms of Deep Learning, MLOps, and Generative AI. I enjoy diving into new projects and uncovering innovative techniques that push the boundaries of technology. I'll be sharing guides, tutorials, and project insights based on my own experiences, so we can learn and grow together. Join me on this journey as we explore, experiment, and build amazing solutions in the world of AI and beyond!

Login to continue reading and enjoy expert-curated content.

Responses From Readers

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details