Saturday, 29 November 2025

Prompt Engineering using Jemini

 HI all

Question : Prompt engineering code in Python which accepts some prompt and get the response from Gemini using the API key

Answer code

---------------------

from google import genai

from google.genai.errors import APIError


# NOTE: Hardcoding API keys is generally discouraged in production environments

# for security reasons. Environment variables or secret management tools are preferred.

# This is done here only to fulfill the specific request.


HARDCODED_API_KEY ="Your API code generated from Google AI  Studio"


def initialize_gemini(api_key: str):

    """Initializes the Gemini client using the hardcoded API key."""

    try:

        # Pass the API key directly to the Client constructor

        client = genai.Client(api_key=api_key)

        return client

    except Exception as e:

        # Note: If the API key is invalid or permissions are wrong, an error

        # might be raised here or during the first API call.

        print(f"Error initializing client: {e}")

        return None


def run_prompt_engineering_lesson(client):

    """

    Demonstrates prompt engineering using a Few-Shot Prompting technique.

    The goal is to teach the model a new, specific output format.

    """

    if not client:

        print("Cannot run lesson because the Gemini client failed to initialize.")

        return


    print("--- 📚 Prompt Engineering Lesson: Few-Shot Prompting ---")

    

    # --- 1. The Prompt ---

    # We provide a few examples ("shots") to guide the model's behavior.

    # The goal is to make it translate casual terms into formal business language.

    prompt = """

    **Instructions:** You are an expert business communication consultant.

    Your task is to translate casual, everyday phrases into formal, professional business language.


    **Examples (Few-Shots):**

    1. Casual: "We messed up the schedule."

    Formal: "We encountered an unforeseen discrepancy in the project timeline."

    2. Casual: "Can you email me the slides?"

    Formal: "Kindly forward the presentation deck via electronic mail."

    3. Casual: "Let's catch up later today."

    Formal: "I propose we schedule a debriefing session later this afternoon."


    **Your Turn (The Query):**

    4. Casual: "The project's going nowhere fast."

    Formal:"""

    prompt=input('Enter a query')


    print("\n[Input Prompt Sent to Gemini Model]:")

    print("----------------------------------------------------------------")

    print(prompt.strip())

    print("----------------------------------------------------------------")


    # --- 2. API Call ---

    # We use a powerful model like gemini-2.5-flash

    try:

        response = client.models.generate_content(

            model='gemini-2.5-flash',

            contents=prompt,

            # Adjusting temperature for more consistent responses.

            config={"temperature": 0.2} 

        )


        # --- 3. Output ---

        print("\n[Model Response Received]:")

        print("----------------------------------------------------------------")

        

        # We process the response text to extract only the formal translation

        full_text = response.text

        if "Formal:" in full_text:

            # Attempt to split to get the translation following the last "Formal:" marker

            formal_translation = full_text.split("Formal:")[-1].strip()

        else:

            # If the model only returned the answer, just strip it

            formal_translation = full_text.strip()

            

        print(formal_translation)

        print("----------------------------------------------------------------")


        print("\n**✨ Prompt Engineering Concept Demonstrated: Few-Shot Learning.**")

        print("By providing examples, we taught the model a specific format (Casual -> Formal) without explicit coding.")


    except APIError as e:

        print(f"\nAn API error occurred: {e}")

        print("Check your API key and ensure you haven't exceeded the free tier quota.")

    except Exception as e:

        print(f"\nAn unexpected error occurred: {e}")



if __name__ == "__main__":

    gemini_client = initialize_gemini(HARDCODED_API_KEY)

    if gemini_client:

        run_prompt_engineering_lesson(gemini_client)


No comments:

Post a Comment