Questions only • Simple algorithms • No answers provided
1
Foundations of Python Programming for AI
Set up the Python environment and write a basic script to interact with an LLM API using the OpenRouter endpoint.
PythonurllibjsonOpenRouter API
Questions
Write a Python program that sends a request to the OpenRouter API with a user prompt and prints the AI response.
What is the role of the json.dumps() function when preparing the API request body?
Modify the program to accept user input from the command line instead of a hardcoded prompt.
What happens when you change the model parameter in the request? Test with at least two different model names.
Add error handling to your program so it prints a friendly message if the API call fails.
Algorithm
Step 1: Import json, urllib.request, ssl modules
Step 2: Define the API key and endpoint URL
Step 3: Build the request body as a dictionary
- Set model name- Set messages list with user role and contentStep 4: Convert dictionary to JSON string and encode to bytes
Step 5: Create Request object with URL, data, headers, and method
Step 6: Send request using urlopen with SSL context
Step 7: Read response and extract the message content
Step 8: Print the AI response
2
Building a Basic Chatbot
Create a conversational chatbot that maintains conversation history and responds to user queries in a loop.
PythonrequestsOpenRouter API
Questions
Write a Python chatbot program that runs in a loop, taking user input and printing AI responses.
How does storing conversation history in a list improve the chatbot's responses compared to sending each message independently?
Modify the chatbot to exit when the user types "exit" or "quit".
Add a feature that counts and displays the number of messages exchanged in the current session.
What is the difference between the role: "user" and role: "assistant" messages in the conversation history?
Algorithm
Step 1: Import requests module and set API key
Step 2: Initialize an empty list called history
Step 3: Start an infinite loop
Step 3a: Get user input from command line
Step 3b: If input is "exit", break the loop
Step 3c: Append user message to history with role "user"
Step 3d: Send POST request to API with full history
Step 3e: Extract assistant reply from response
Step 3f: Append reply to history with role "assistant"
Step 3g: Print the assistant reply
3
Autonomous Agent with OpenAI Functions
Build a simple autonomous agent that can fetch information about historical events and remember previous queries.
PythonjsonurllibOpenRouter API
Questions
Write a Python program that functions as a "HistoryBot" agent, answering questions about historical events.
How does the agent remember previous queries? What data structure is used for this purpose?
Modify the agent to store its conversation history in a text file so it can resume after the program is restarted.
Add a function that summarizes all the questions asked during the session when the user types "summary".
What is the purpose of the max_tokens parameter in the API request? What happens when you increase or decrease it?
Algorithm
Step 1: Import json, urllib.request, ssl modules
Step 2: Define API key and endpoint
Step 3: Create function ask(prompt, history):
- Append user message to history- Build request body with model, messages, max_tokens- Send POST request to API- Parse response and extract content- Append assistant reply to history- Return reply and updated historyStep 4: Initialize empty history list
Step 5: Loop: get input, call ask(), print response
Step 6: Exit when user types "exit"
4
Book Recommendation Agent Toolkit
Create a custom agent toolkit that recommends books to students based on their subject preferences.
PythonjsonurllibOpenRouter API
Questions
Write a program that asks for a student's name and preferred subject, then recommends 5 books using the AI API.
How can you ensure the AI returns the response in a valid JSON format? What prompt instructions help with this?
Modify the program to display the recommendations in a formatted table with columns for Title, Author, and Domain.
Add a feature that asks the student to rate each recommended book and stores the ratings.
What modifications would you make to prevent the agent from recommending the same books in repeated requests?
Algorithm
Step 1: Import json, urllib.request modules
Step 2: Get student name and subject from user input
Step 3: Build prompt asking for 5 book recommendations in JSON format
Step 4: Send request to API with system role "You are a book recommendation agent"
Step 5: Parse the JSON response into a list of book objects
Step 6: Display recommendations in a formatted table
Step 7: Ask student to rate each book (1-5)
Step 8: Store ratings and display summary
5
Image Generation with DALL-E (Subject, View, Style)
Use the Subject-View-Style framework to construct effective prompts for AI image generation.
PythonDALL-EImage Prompting
Questions
What are the three components of the Subject-View-Style prompting framework? Explain each with an example.
Write a prompt to generate an image of a futuristic classroom using the Subject-View-Style structure.
How does changing the "View" component (e.g., close-up vs. aerial) affect the generated image?
Create 5 different prompts for the same subject but with different styles (e.g., watercolor, cyberpunk, oil painting).
What is a negative prompt? Write an example that excludes unwanted elements from an image.
Algorithm
Step 1: Define the three components:
Subject = what the image shows (object, person, scene)View = framing and angle (close-up, wide, aerial, POV)Style = artistic rendering (medium, lighting, color palette)Step 2: Choose a subject (e.g., "majestic dragon")
Step 3: Select a view (e.g., "low-angle shot")
Step 4: Pick a style (e.g., "cyberpunk with neon glow")
Step 5: Combine into prompt: "Create an image of {subject}, {view}, {style}"
Step 6: Add negative prompt if needed: " Exclude: blurry, low quality"
Step 7: Send to image generation API
Step 8: Evaluate output and refine components
6
Image Prompt Engineering & Rewriting
Learn to analyze and rewrite image prompts for better results using boosters, modifiers, and style tags.
PythonStable DiffusionPrompt Analysis
Questions
Write a basic prompt for a historical landmark. Then rewrite it to include a specific style (e.g., watercolor, futuristic).
What are "prompt boosters"? List 5 boosters that improve image quality.
How does reverse engineering an AI-generated image help in improving prompts?
Compare the outputs of a simple prompt vs. a detailed prompt with style modifiers for the same subject.
Create a prompt optimization pipeline: Original Prompt → Analyze → Rewrite → Test → Evaluate.
Algorithm
Step 1: Start with a basic prompt (e.g., "Eiffel Tower")
Step 2: Analyze the prompt for missing components
Step 3: Add subject details (time of day, weather, people)
Step 4: Add view/framing (wide-angle, sunset angle)
Step 5: Add style (watercolor painting, dramatic lighting)
Step 6: Add boosters (highly detailed, 8k, masterpiece)
Step 7: Add negative prompt (blurry, low quality, watermark)
Step 8: Generate and compare original vs. rewritten outputs
7
AI Blog Post Generation
Use AI to generate a complete blog post on a topic with title suggestions and writing style variations.
PythonOpenRouter APIContent Writing
Questions
Write a prompt to generate a blog post on "The Importance of Renewable Energy" with 5 title suggestions.
How do you instruct the AI to write in a formal tone vs. a conversational tone? Provide examples of both.
Generate the same blog topic in three different styles: Formal, Conversational, and Persuasive.
What components should a well-structured blog post include (intro, body, conclusion, etc.)?
How can you use the "Divide Labor" prompting principle to generate a blog post in stages?
Algorithm
Step 1: Define the blog topic and target audience
Step 2: Generate 5 title suggestions using AI
Step 3: Select the best title
Step 4: Generate blog outline with sections:
- Introduction (hook + thesis)- Body paragraphs (3-5 key points)- Conclusion (summary + call to action)Step 5: Generate each section separately (Divide Labor)
Step 6: Combine sections into complete post
Step 7: Review and refine for consistency
Step 8: Generate images for the blog using Subject-View-Style
8
Blog Outline Refinement & SEO
Generate a blog outline and refine it for clarity, impact, and SEO optimization.
PythonSEOContent Structure
Questions
Generate a blog outline for "The Future of Education" with at least 6 sections.
How does SEO optimization affect blog visibility? What are the key SEO elements?
Rewrite the outline to improve clarity by using stronger headings and more specific sub-points.
What is the difference between a meta title and a meta description? Why are both important?
Create an SEO checklist for evaluating AI-generated blog content.
Algorithm
Step 1: Generate initial blog outline on the topic
Step 2: Analyze outline for:
- Clear section headings- Logical flow of ideas- Coverage of key topicsStep 3: Refine headings for SEO (include keywords)
Step 4: Add meta title (under 60 characters)
Step 5: Add meta description (under 160 characters)
Step 6: Identify internal and external link opportunities
Step 7: Check readability score
Step 8: Final review and publish
9
AI Blog Assistant Prototype
Build a simple GUI application that combines text generation and image creation for blog posts.
PythontkinterrequestsOpenRouter API
Questions
Design a GUI application with fields for API key, blog topic, and a generate button. Sketch the layout.
Write the Python code to connect the GUI to the AI API and display the generated blog content.
Add a "Copy to Clipboard" button that copies the generated content.
How would you extend this prototype to also generate blog images? What additional fields are needed?
What are the limitations of this prototype? How could it be improved for production use?
Algorithm
Step 1: Import tkinter and requests modules
Step 2: Create main window with title "AI Blog Assistant"
Step 3: Add input fields:
- API Key (masked input)- Blog Topic (text entry)Step 4: Add Generate button that calls generate function
Step 5: Generate function:
- Read API key and topic- Build prompt for blog generation- Send request to API- Display response in text areaStep 6: Add Copy button that copies text area content
Step 7: Run the application main loop
Note: This lab manual contains questions only with simple algorithmic steps. Students are expected to write the complete code and implement the solutions independently.