From One-Shot to Multi-Shot Prompting

One-Shot

The Website class retrieves the text content and links from a given URL.

import requests
from bs4 import BeautifulSoup

# Some websites need you to use proper headers when fetching them:
headers = {
 "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
}

class Website:
    """
    A utility class to represent a Website that we have scraped, now with links
    """

    def __init__(self, url):
        self.url = url
        response = requests.get(url, headers=headers)
        self.body = response.content
        soup = BeautifulSoup(self.body, 'html.parser')
        self.title = soup.title.string if soup.title else "No title found"
        if soup.body:
            for irrelevant in soup.body(["script", "style", "img", "input"]):
                irrelevant.decompose()
            self.text = soup.body.get_text(separator="\n", strip=True)
        else:
            self.text = ""
        links = [link.get('href') for link in soup.find_all('a')]
        self.links = [link for link in links if link]

    def get_contents(self):
        return f"Webpage Title:\n{self.title}\nWebpage Contents:\n{self.text}\n\n"

Prompt 1: Here’s an OpenAI example showing how to use a one-shot prompt to get a response from the model. I will ask the AI to extract the links from the URL.

def get_links_user_prompt(website):
    user_prompt = f"Here is the list of links on the website of {website.url} - "
    user_prompt += "please decide which of these are relevant web links for a brochure about the company, respond with the full https URL in JSON format. \
Do not include Terms of Service, Privacy, email links.\n"
    user_prompt += "Links (some might be relative links):\n"
    user_prompt += "\n".join(website.links)
    return user_prompt


system_prompt_1 = "You are provided with a list of links found on a webpage. \
You are able to decide which of the links would be most relevant to include in a brochure about the company, \
such as links to an About page, or a Company page, or Careers/Jobs pages.\n"
system_prompt_1 += "You should respond in JSON as in this example:"
system_prompt_1 += """
{
    "links": [
        {"type": "about page", "url": "https://full.url/goes/here/about"},
        {"type": "careers page": "url": "https://another.full.url/careers"}
    ]
}
"""


user_prompt_1 = get_links_user_prompt(Website("https://www.winerva.com/"))

import os
from openai import OpenAI
from dotenv import load_dotenv

load_dotenv(override=True)
api_key = os.getenv('OPENAI_API_KEY')
MODEL = 'gpt-4o-mini'

openai = OpenAI()

response = openai.chat.completions.create(
        model=MODEL,
        messages=[
            {"role": "system", "content": system_prompt_1},
            {"role": "user", "content": user_prompt_1}
      ],
        response_format={"type": "json_object"}
    )
result = response.choices[0].message.content
print(result)
{
    "links": [
        {"type": "about page", "url": "https://www.winerva.com/zh-TW/about"},
        {"type": "portfolio page", "url": "https://www.winerva.com/zh-TW/portfolio"},
        {"type": "contact page", "url": "https://www.winerva.com/zh-TW/contact"}
    ]
}
import json
relevant_links = json.loads(result)
    
def get_all_details(url):
    result = "Landing page:\n"
    result += Website(url).get_contents()
    links = relevant_links
    print("Found links:", links)
    for link in links["links"]:
        result += f"\n\n{link['type']}\n"
        result += Website(link["url"]).get_contents()
    return result
    
def get_brochure_user_prompt(company_name, url):
    user_prompt = f"You are looking at a company called: {company_name}\n"
    user_prompt += f"Here are the contents of its landing page and other relevant pages; use this information to build a short brochure of the company in markdown.\n"
    user_prompt += get_all_details(url)
    user_prompt = user_prompt[:5_000] # Truncate if more than 5,000 characters
    return user_prompt

Prompt 2: I will ask the AI to create a short company brochure.

from IPython.display import Markdown, display, update_display

system_prompt_2 = "You are an assistant that analyzes the contents of several relevant pages from a company website \
and creates a short brochure about the company for prospective customers, investors and recruits. Respond in markdown.\
Include details of company culture, customers and careers/jobs if you have the information."

user_prompt_2 = get_brochure_user_prompt("Winerva", "https://www.winerva.com/")

stream = openai.chat.completions.create(
        model=MODEL,
        messages=[
            {"role": "system", "content": system_prompt_2},
            {"role": "user", "content": user_prompt_2}
      ],
       stream=True
    )
response = ""
display_handle = display(Markdown(""), display_id=True)
for chunk in stream:
    response += chunk.choices[0].delta.content or ''
    response = response.replace("```","").replace("markdown", "")
    update_display(Markdown(response), display_id=display_handle.display_id)
Found links: {'links': [{'type': 'about page', 'url': 'https://www.winerva.com/zh-TW/about'}, {'type': 'portfolio page', 'url': 'https://www.winerva.com/zh-TW/portfolio'}, {'type': 'contact page', 'url': 'https://www.winerva.com/zh-TW/contact'}]}

Winerva Company Brochure

About Us

Welcome to Winerva (鴻博資訊有限公司), a leading company specializing in computer vision and automation solutions since 2014. We pride ourselves on our strong reputation and professional image, bolstered by our team’s extensive experience of over 12 years in visual processing and automation technologies. Our deep understanding of the Taiwanese market allows us to cater effectively to customer needs.

Our Expertise

We focus on:

  • Automated Optical Inspection (AOI): We provide core technology planning for visual image identification systems, pivotal for industries like semiconductors and testing, which is expected to be a crucial automation technology in the coming decades.
  • Full-Stack Development: Creating robust and user-friendly websites and applications, seamlessly integrating front-end and back-end functionalities.
  • AI and Machine Learning: Implementing real-time object detection systems and developing effective defect detection solutions.

Solutions We Offer

  • Industrial Automation: High-precision automation systems to enhance efficiency in inspections.
  • Visual Systems Integration: Ensuring optimal image quality with appropriate lighting, cameras, and lens selections.
  • Real-Time Imaging: Developing intuitive user interfaces and integrating backend data processing systems.

Company Culture

At Winerva, we can confirm that our confidence stems from our capabilities, and our experience is solidified by the trust our customers place in us. Our company values include:

  • Integrity in Service: Transparent and sincere engagement with clients.
  • Mutual Support: Fostering an environment of collective growth and innovation.
  • Technological Leadership: Continuous drive for technological innovation and improvement.

Our Customers

We have successfully collaborated with various industries, including agriculture, semiconductors, and manufacturing. Our portfolio showcases several significant projects, such as:

  • Greenhouse control systems for agricultural data collection.
  • Visual inspection systems for battery assembly anomalies.
  • Intelligent grading systems for agricultural products.

Careers at Winerva

Join a team that values innovation, collaboration, and continuous learning. With an average of six years of specialized experience among our members, we seek talented individuals who are passionate about technology and desire to grow with us. Positions are available across various domains, including:

  • Computer Vision Specialists
  • Software Developers
  • Automation Engineers

Contact Information

If you have any inquiries or wish to learn more about our technologies and services, please feel free to reach out to us:

Customer Service Hotline: 0927-377-741
Emailfluber@winerva.com


Enhance your automation and visual processing experience with Winerva – where technology meets service excellence!

Multi-Shot

I want to combine the above two requests into a multi-shot prompt and ask them in a single query.

def multi_shot_prompt(system1: str, system2: str, user1: str, user2: str, model: str = "gpt-4o-mini"):
    """
    Use multi-shot prompting to complete two-stage reasoning in a single call.
    :param system1: System prompt for the first stage
    :param system2: System prompt for the second stage
    :param user1: User input for the first stage
    :param user2: User input for the second stage
    :param model: The LLM model to use
    :return: The final response from the model
    """

    messages = [
        # First stage system prompt
        {"role": "system", "content": system1},
        {"role": "user", "content": user1},
        # Simulated short answer from the first stage assistant
        {"role": "assistant", "content": "(This is the short answer from stage one. The model will use this as context.)"},
        
        # Second stage system prompt
        {"role": "system", "content": system2},
        {"role": "user", "content": user2}
    ]

    stream = openai.chat.completions.create(
        model=model,
        messages=messages,
        stream=True
    )

    response = ""
    display_handle = display(Markdown(""), display_id=True)
    for chunk in stream:
        response += chunk.choices[0].delta.content or ''
        response = response.replace("```", "").replace("markdown", "")
        update_display(Markdown(response), display_id=display_handle.display_id)
multi_shot_prompt(system_prompt_1, system_prompt_2, user_prompt_1, user_prompt_2)

Winerva Brochure

About Us

Company Name: Winerva (鴻博資訊有限公司)
Established: 2014

Winerva specializes in vision detection and automation technology, boasting over 12 years of experience in image processing, object detection, and 3D reconstruction. Our team, with an average of 6 years of professional experience, understands the Taiwanese market and customer needs deeply. We are dedicated to supporting our clients in project development with innovative solutions and advanced technologies.

Our Strengths

  • Core Technology: We provide Automated Optical Inspection (AOI) systems suitable for small to medium enterprises and the semiconductor industry. This technology is expected to be one of the fastest-growing sectors in automation over the next few decades.
  • Full-Stack Development: Our services focus on building powerful and user-friendly websites and applications, ensuring seamless integration between front-end and back-end requirements.
  • Computer Vision: Proficiency in real-time object detection systems and high-performance defect detection solutions.
  • Industrial Automation: Design and implementation of high-precision automated systems for enhanced detection efficiency.

Company Culture

We pride ourselves on our commitment to integrity and mutual support. Our corporate philosophy includes:

  • Leading Technology: Continuous innovation to maintain industry leadership.
  • Integrity in Service: Providing transparent and sincere services to our clients.
  • Teamwork and Innovation: Embracing the power of teamwork to foster constant innovation.
  • Consensus Building: Collaborating with our customers to create long-term value.

Portfolio

Notable Projects

  • Capacitance Height Measurement: Installed systems in capacitance production lines to provide feedback on manufacturing results.
  • Battery Insulation Assembly Inspection: Detection of assembly anomalies in circular battery insulation caps.
  • Coating Process Leak Detection: Monitoring leak incidents through Modbus notifications for prompt alerts.

Careers

At Winerva, we are always looking for talented individuals who share our commitment to quality and innovation. If you are interested in joining our team and contributing to cutting-edge projects, please reach out for current job openings.

Contact Us

Customer Service Line: 0927-377-741
Email: fluber@winerva.com

For any inquiries or further information about our technologies and services, please don’t hesitate to contact us!


Winerva looks forward to being your partner in automation and innovation!

Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *