from dotenv import load_dotenv
from langchain_community.retrievers import WikipediaRetriever
from typing import List
from langchain_core.documents import Document
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser
load_dotenv()
wikipediaRetriever = WikipediaRetriever(top_k_results = 6, doc_content_chars_max = 2000)
runnableSequence1 = (lambda x: x["input"]) | wikipediaRetriever
def getStringDocumentList(documentList: List[Document]):
return "\n\n".join(document.page_content for document in documentList)
chatPromptTemplate = ChatPromptTemplate.from_messages(
[
("system", "You're a helpful AI assistant. Given a user question and some Wikipedia article snippets, answer the user question. If none of the articles answer the question, just say you don't know.\n\nHere are the Wikipedia articles : {context}"),
("human", "{input}")
]
)
chatOpenAI = ChatOpenAI(model = "gpt-4o-mini")
runnableSequence2 = (
RunnablePassthrough.assign(context = (lambda x : getStringDocumentList(x["context"])))
| chatPromptTemplate
| chatOpenAI
| StrOutputParser()
)
runnableSequence3 = RunnablePassthrough.assign(context = runnableSequence1).assign(answer = runnableSequence2)
responseDictionary = runnableSequence3.invoke({"input" : "How fast are cheetahs?"})
print(responseDictionary)
"""
{
'input' : 'How fast are cheetahs?',
'context' : [
Document(
metadata = {
'title' : 'Cheetah',
'summary' : 'The cheetah (Acinonyx jubatus) is a large cat and the fastest land animal. It has a tawny to creamy white or pale buff fur that is marked with evenly spaced, solid black spots. The head is small and rounded, with a short snout and black tear-like facial streaks. It reaches 67–94 cm (26–37 in) at the shoulder, and the head-and-body length is between 1.1 and 1.5 m (3 ft 7 in and 4 ft 11 in). Adults weigh between 21 and 72 kg (46 and 159 lb). The cheetah is capable of running at 93 to 104 km/h (58 to 65 mph); it has evolved specialized adaptations for speed, including a light build, long thin legs and a long tail.\nThe cheetah was first described in the late 18th century. Four subspecies are recognised today that are native to Africa and central Iran. An African subspecies was introduced to India in 2022. It is now distributed mainly in small, fragmented populations in northwestern, eastern and southern Africa and central Iran. It lives in a variety of habitats such as savannahs in the Serengeti, arid mountain ranges in the Sahara, and hilly desert terrain.\nThe cheetah lives in three main social groups: females and their cubs, male "coalitions", and solitary males. While females lead a nomadic life searching for prey in large home ranges, males are more sedentary and instead establish much smaller territories in areas with plentiful prey and access to females. The cheetah is active during the day, with peaks during dawn and dusk. It feeds on small- to medium-sized prey, mostly weighing under 40 kg (88 lb), and prefers medium-sized ungulates such as impala, springbok and Thomson\'s gazelles. The cheetah typically stalks its prey within 60–100 m (200–330 ft) before charging towards it, trips it during the chase and bites its throat to suffocate it to death. It breeds throughout the year. After a gestation of nearly three months, females give birth to a litter of three or four cubs. Cheetah cubs are highly vulnerable to predation by other large carnivores. They are weaned at around four months and are independent by around 20 months of age.\nThe cheetah is threatened by habitat loss, conflict with humans, poaching and high susceptibility to diseases. The global cheetah population was estimated in 2021 at 6,517; it is listed as Vulnerable on the IUCN Red List. It has been widely depicted in art, literature, advertising, and animation. It was tamed in ancient Egypt and trained for hunting ungulates in the Arabian Peninsula and India. It has been kept in zoos since the early 19th century.',
'source' : 'https://en.wikipedia.org/wiki/Cheetah'
},
page_content = 'The cheetah (Acinonyx jubatus) is a large cat and the fastest land animal. It has a tawny to creamy white or pale buff fur that is marked with evenly spaced, solid black spots. The head is small and rounded, with a short snout and black tear-like facial streaks. It reaches 67–94 cm (26–37 in) at the shoulder, and the head-and-body length is between 1.1 and 1.5 m (3 ft 7 in and 4 ft 11 in). Adults weigh between 21 and 72 kg (46 and 159 lb). The cheetah is capable of running at 93 to 104 km/h (58 to 65 mph); it has evolved specialized adaptations for speed, including a light build, long thin legs and a long tail.\nThe cheetah was first described in the late 18th century. Four subspecies are recognised today that are native to Africa and central Iran. An African subspecies was introduced to India in 2022. It is now distributed mainly in small, fragmented populations in northwestern, eastern and southern Africa and central Iran. It lives in a variety of habitats such as savannahs in the Serengeti, arid mountain ranges in the Sahara, and hilly desert terrain.\nThe cheetah lives in three main social groups: females and their cubs, male "coalitions", and solitary males. While females lead a nomadic life searching for prey in large home ranges, males are more sedentary and instead establish much smaller territories in areas with plentiful prey and access to females. The cheetah is active during the day, with peaks during dawn and dusk. It feeds on small- to medium-sized prey, mostly weighing under 40 kg (88 lb), and prefers medium-sized ungulates such as impala, springbok and Thomson\'s gazelles. The cheetah typically stalks its prey within 60–100 m (200–330 ft) before charging towards it, trips it during the chase and bites its throat to suffocate it to death. It breeds throughout the year. After a gestation of nearly three months, females give birth to a litter of three or four cubs. Cheetah cubs are highly vulnerable to predation by other large carnivores. They are weaned a'
),
Document
(
metadata = {
'title' : 'Southeast African cheetah',
'summary' : 'The Southeast African cheetah (Acinonyx jubatus jubatus) is the nominate cheetah subspecies native to East and Southern Africa. The Southern African cheetah lives mainly in the lowland areas and deserts of the Kalahari, the savannahs of Okavango Delta, and the grasslands of the Transvaal region in South Africa. In Namibia, cheetahs are mostly found in farmlands. In India, four cheetahs of the subspecies are living in Kuno National Park in Madhya Pradesh after having been introduced there.',
'source' : 'https://en.wikipedia.org/wiki/Southeast_African_cheetah'
},
page_content = 'The Southeast African cheetah (Acinonyx jubatus jubatus) is the nominate cheetah subspecies native to East and Southern Africa. The Southern African cheetah lives mainly in the lowland areas and deserts of the Kalahari, the savannahs of Okavango Delta, and the grasslands of the Transvaal region in South Africa. In Namibia, cheetahs are mostly found in farmlands. In India, four cheetahs of the subspecies are living in Kuno National Park in Madhya Pradesh after having been introduced there.\n\n\n== Taxonomy ==\n\nThe Southern African cheetah was first described by German naturalist Johann Christian Daniel von Schreber in his book Die Säugethiere in Abbildungen nach der Natur mit Beschreibungen (The Mammals illustrated as in Nature with Descriptions), published in 1775. Schreber described the species on basis of a specimen from the Cape of Good Hope. It is therefore the nominate subspecies. Subpopulations have been called "South African cheetah" and "Namibian cheetah."\nFollowing Schreber\'s description, other naturalists and zoologists also described cheetah specimens from many parts of Southern and East Africa that today are all considered synonyms of A. j. jubatus:\n\nFelis guttata proposed in 1804 by Johann Hermann;\nFelis fearonii proposed in 1834 by Andrew Smith;\nFelis lanea proposed in 1877 by Philip Sclater;\nAcinonyx jubatus obergi proposed in 1913 by Max Hilzheimer;\nAcinonyx jubatus ngorongorensis proposed in 1913 by Hilzheimer on basis of a specimen from Ngorongoro, German East Africa;\nAcinonyx jubatus velox proposed in 1913 by Edmund Heller on basis of a cheetah that was shot by Kermit Roosevelt in June 1909 in the Kenyan highlands.\nAcinonyx rex proposed in 1927 by Reginald Innes Pocock on basis of a specimen from the Umvukwe Range in Rhodesia.\nIn 2005, the authors of Mammal Species of the World grouped A. j. guttata, A. j. lanea, A. j. obergi, and A. j. rex under A j. jubatus, whilst recognizing A. j. raineyi and A. j. velox as valid taxa and considering P. l. ngoron'
),
Document(
metadata = {
'title' : 'Fastest animals',
'summary' : 'This is a list of the fastest animals in the world, by types of animal.',
'source': 'https://en.wikipedia.org/wiki/Fastest_animals'
},
page_content = "This is a list of the fastest animals in the world, by types of animal.\n\n\n== Fastest organism ==\nThe peregrine falcon is the fastest bird, and the fastest member of the animal kingdom, with a diving speed of over 300 km/h (190 mph). The fastest land animal is the cheetah. Among the fastest animals in the sea is the black marlin, with uncertain and conflicting reports of recorded speeds.\nWhen drawing comparisons between different classes of animals, an alternative unit is sometimes used for organisms: body length per second. On this basis the 'fastest' organism on earth, relative to its body length, is the Southern Californian mite, Paratarsotomus macropalpis, which has a speed of 322 body lengths per second. The equivalent speed for a human, running as fast as this mite, would be 1,300 mph (2,092 km/h), or approximately Mach 1.7. The speed of the P. macropalpis is far in excess of the previous record holder, the Australian tiger beetle Rivacindela hudsoni, which is the fastest insect in the world relative to body size, with a recorded speed of 1.86 metres per second (6.7 km/h; 4.2 mph), or 171 body lengths per second. The cheetah, the fastest land mammal, scores at only 16 body lengths per second.\n\n\n== Invertebrates ==\n\n\n== Fish ==\nDue to physical constraints, fish may be incapable of exceeding swim speeds of 36 km/h (22 mph). The larger reported figures below are therefore highly questionable:\n\n\n== Amphibians ==\n\n\n== Reptiles ==\n\n\n== Birds ==\n\n\n== Mammals ==\n\n\n== See also ==\nSpeed record\n\n\n== Notes ==\n\n\n== References =="
),
Document(
metadata = {
'title' : 'Footspeed',
'summary' : 'Footspeed, or sprint speed, is the maximum speed at which a human can run. It is affected by many factors, varies greatly throughout the population, and is important in athletics and many sports, such as association football, Australian rules football, American football, track and field, field hockey, tennis, baseball, and basketball.',
'source' : 'https://en.wikipedia.org/wiki/Footspeed'
},
page_content = 'Footspeed, or sprint speed, is the maximum speed at which a human can run. It is affected by many factors, varies greatly throughout the population, and is important in athletics and many sports, such as association football, Australian rules football, American football, track and field, field hockey, tennis, baseball, and basketball.\n\n\n== Factors in speed ==\nThe key determinant of footspeed in sprinting is the predominance of one distinct type of muscle fibre over another, specifically the ratio of fast-twitch muscles to slow-twitch muscles in a sprinter\'s physical makeup. Though fast-twitch muscles produce no more energy than slow-twitch muscles when they contract, they do so more rapidly through a process of anaerobic metabolism, though at the cost of inferior efficiency over longer periods of firing. The average human has an almost-equal ratio of fast-twitch to slow-twitch fibers, but top sprinters may have as much as 80% fast-twitch fibers, while top long-distance runners may have only 20%. This ratio is believed to have genetic origins, though some assert that it can be adjusted by muscle training. "Speed camps" and "Speed Training Manuals", which purport to provide fractional increases in maximum footspeed, are popular among budding professional athletes, and some sources estimate that 17–19% of speed can be trained.\nThough good running form is useful in increasing speed, fast and slow runners have been shown to move their legs at nearly the same rate – it is the force exerted by the leg on the ground that separates fast sprinters from slow. Top short-distance runners exert as much as four times their body weight in pressure on the running surface. For this reason, muscle mass in the legs, relative to total body weight, is a key factor in maximizing footspeed.\n\n\n== Limits of speed ==\nThe record is 44.72 km/h (27.78 mph), measured between meter 60 and meter 80 of the 100 meters sprint at the 2009 World Championships in Athletics by Usain Bolt. (Bolt\'s ave'
),
Document(
metadata = {
'title' : 'Pursuit predation',
'summary' : "Pursuit predation is a form of predation in which predators actively give chase to their prey, either solitarily or as a group. It is an alternate predation strategy to ambush predation — pursuit predators rely on superior speed, endurance and/or teamwork to seize the prey, while ambush predators use concealment, luring, exploiting of surroundings and the element of surprise to capture the prey. While the two patterns of predation are not mutually exclusive, morphological differences in an organism's body plan can create an evolutionary bias favoring either type of predation.\nPursuit predation is typically observed in carnivorous species within the kingdom Animalia, such as cheetahs, lions, wolves and early Homo species. The chase can be initiated either by the predator, or by the prey if it is alerted to a predator's presence and attempt to flee before the predator gets close. The chase ends either when the predator successfully catches up and tackles the prey, or when the predator abandons the attempt after the prey outruns it and escapes.\nOne particular form of pursuit predation is persistence hunting, where the predator stalks the prey slowly but persistently to wear it down physically with fatigue or overheating; some animals are examples of both types of pursuit.\n\n",
'source' : 'https://en.wikipedia.org/wiki/Pursuit_predation'
},
page_content = "Pursuit predation is a form of predation in which predators actively give chase to their prey, either solitarily or as a group. It is an alternate predation strategy to ambush predation — pursuit predators rely on superior speed, endurance and/or teamwork to seize the prey, while ambush predators use concealment, luring, exploiting of surroundings and the element of surprise to capture the prey. While the two patterns of predation are not mutually exclusive, morphological differences in an organism's body plan can create an evolutionary bias favoring either type of predation.\nPursuit predation is typically observed in carnivorous species within the kingdom Animalia, such as cheetahs, lions, wolves and early Homo species. The chase can be initiated either by the predator, or by the prey if it is alerted to a predator's presence and attempt to flee before the predator gets close. The chase ends either when the predator successfully catches up and tackles the prey, or when the predator abandons the attempt after the prey outruns it and escapes.\nOne particular form of pursuit predation is persistence hunting, where the predator stalks the prey slowly but persistently to wear it down physically with fatigue or overheating; some animals are examples of both types of pursuit.\n\n\n== Strategy ==\nThere is still uncertainty as to whether predators behave with a general tactic or strategy while preying. However, among pursuit predators there are several common behaviors. Often, predators will scout potential prey, assessing prey quantity and density prior to engaging in a pursuit. Certain predators choose to pursue prey primarily in a group of conspecifics; these animals are known as pack hunters or group pursuers. Other species choose to hunt alone. These two behaviors are typically due to differences in hunting success, where some groups are very successful in groups and others are more successful alone. Pursuit predators may also choose to either exhaust their metabolic r"
),
Document(
metadata = {
'title' : 'Gepard-class fast attack craft',
'summary' : 'The Type 143A Gepard class was a class of missile bearing fast attack craft (German: Schnellboot) and the last one in service with the German Navy before the remaining four operational ships were decommissioned on 16 November 2016. The Ghana Navy operates two such ships. \nIt is an evolution of the Albatros class, the main difference being the replacement of the second 76 mm gun by the RAM system. The Gepard-class vessels were gradually supplemented by Braunschweig-class corvettes and later replaced completely by them.\nThe ships in class were named after small to medium-sized predatory animals; Gepard is German for "cheetah".',
'source' : 'https://en.wikipedia.org/wiki/Gepard-class_fast_attack_craft'
},
page_content = 'The Type 143A Gepard class was a class of missile bearing fast attack craft (German: Schnellboot) and the last one in service with the German Navy before the remaining four operational ships were decommissioned on 16 November 2016. The Ghana Navy operates two such ships. \nIt is an evolution of the Albatros class, the main difference being the replacement of the second 76 mm gun by the RAM system. The Gepard-class vessels were gradually supplemented by Braunschweig-class corvettes and later replaced completely by them.\nThe ships in class were named after small to medium-sized predatory animals; Gepard is German for "cheetah".\n\n\n== List of ships ==\n\nThe "S" and the number are part of the ship\'s full name. When the ships were first commissioned, their designation included only the number; however, the crews petitioned for full names, and the decision was made to combine the original names with the additional animal name.\nSince 1 July 2006, all ships had formed part of the 7. Schnellbootgeschwader (7th Fast Patrol Boat Squadron), whereas for the eight years prior the flotilla was split into (hulls S 76–S 80) 2. Schnellbootgeschwader (2nd Fast Patrol Boat Squadron), and (hulls S 71–S 75) 7. Schnellbootgeschwader. The squadron was stationed in Warnemünde, where both predecessor squadrons had been based.\n\n\n== Gallery ==\n\n\t\t\n\t\t\t\n\t\t\t\n\t\t\n\t\t\n\t\t\t\n\t\t\t\n\t\t\n\t\t\n\t\t\t\n\t\t\t\n\t\t\n\t\t\n\t\t\t\n\t\t\t\n\t\t\n\n\n== Notes ==\n\n\n== References ==\n\n"Schnellboot GEPARD-Klasse" (in German). German Navy. Retrieved 10 July 2013.'
)
],
'answer' : 'Cheetahs can run at speeds of 93 to 104 km/h (58 to 65 mph), making them the fastest land animals.'
}
"""