8. Take the Institution name as input.
Use Pydantic to define the schema
for the desired output and create a custom output parser. Invoke the Chain
and Fetch Results. Extract the below Institution related details from
Wikipedia: The founder of the Institution. When it was founded. The
current branches in the institution. How many employees are working in it.
A brief 4-line summary of the institution.
#install library files
pip install wikipedia
pip install pydantic
pip install openai
# Import necessary modules
import wikipedia
from pydantic import BaseModel
from typing import List, Optional
# Define a Pydantic model for the Institution details
class InstitutionInfo(BaseModel):
founder: Optional[str]
founded_year: Optional[str]
branches: Optional[List[str]]
number_of_employees: Optional[int]
summary: str
# Function to fetch and parse institution info
def get_institution_info(name: str) -> InstitutionInfo:
try:
# Fetch Wikipedia page summary and page content
summary = [Link](name, sentences=4)
page = [Link](name)
content = [Link]
# Very simple parsing (for real-world better parsing, use LLMs)
founder = None
founded_year = None
branches = []
employees = None
lines = [Link]('\n')
for line in lines:
line = [Link]()
if 'founded' in line and founded_year is None:
# try to extract year
import re
years = [Link](r'\b(19|20)\d{2}\b', line)
if years:
founded_year = years[0]
if 'founder' in line and founder is None:
founder = [Link]('founder')[-1].split('.')[0].strip(' :')
if 'branches' in line or 'campuses' in line:
[Link]([Link]())
if 'employees' in line and employees is None:
import re
match = [Link](r'\d{3,}', line)
if match:
employees = int([Link](0))
# Return the InstitutionInfo instance
return InstitutionInfo(
founder=founder,
founded_year=founded_year,
branches=branches if branches else None,
number_of_employees=employees,
summary=summary
)
except [Link] as e:
print(f"Error: The name '{name}' is ambiguous. Suggestions: {[Link]}")
except [Link]:
print(f"Error: The page for '{name}' does not exist.")
except Exception as e:
print(f"Unexpected error: {e}")
# Main function to run the program
if __name__ == "__main__":
# Take institution name as input
institution_name = input("Enter the Institution Name: ")
# Fetch details
institution_details = get_institution_info(institution_name)
# Display the structured output
if institution_details:
print("\nFetched Institution Information:")
print(institution_details.json(indent=4))
Explanation:
import wikipedia
from pydantic import BaseModel
from typing import List, Optional
wikipedia: To search and fetch content from Wikipedia.
pydantic: To define a schema (structured format) for output using a Python class.
typing: For type hinting (List, Optional).
2. Define the output structure with Pydantic
class InstitutionInfo(BaseModel):
founder: Optional[str]
founded_year: Optional[str]
branches: Optional[List[str]]
number_of_employees: Optional[int]
summary: str
We create a Pydantic model named InstitutionInfo.
This tells the program what information we want.
Optional means that field can be None if the data isn't found.
Fields:
founder: Name of the founder.
founded_year: Year the institution was started.
branches: List of branch names/locations.
number_of_employees: How many employees are there.
summary: A short 4-line description.
3. Define a function to fetch and extract info
def get_institution_info(name: str) -> InstitutionInfo:
Takes institution name as input (str type).
Returns the structured InstitutionInfo.
a) Fetch Summary and Page Content
summary = [Link](name, sentences=4)
page = [Link](name)
content = [Link]
b) Initialize Empty Variables
founder = None
founded_year = None
branches = []
employees = None
c) Parse the Content Line by Line
lines = [Link]('\n')
for line in lines:
line = [Link]()
Breaks Wikipedia content into lines for easier searching.
Converts everything to lowercase to make matching words easier.
d) Search for Specific Information
Look for keywords like:
"founded" → try to find the year using regex.
"founder" → try to find founder name.
"branches" or "campuses" → try to collect branch info.
"employees" → try to find number of employees.