Public
Edited
Aug 30, 2023
Insert cell
Insert cell
Insert cell
langchain = import("https://esm.sh/langchain/llms/openai");
Insert cell
OpenAI = langchain.OpenAI;
Insert cell
chains = import("https://esm.sh/langchain/chains")
Insert cell
APIChain = chains.APIChain
Insert cell
viewof openaiApiKey = Inputs.text({label: "OpenAI API Key", placeholder: "Enter your OpenAI API Key"})
Insert cell
Insert cell
SequentialChain = chains.SequentialChain
Insert cell
LLMChain = chains.LLMChain
Insert cell
prompts = import("https://esm.sh/langchain/prompts")
Insert cell
PromptTemplate = prompts.PromptTemplate
Insert cell
Insert cell
template = `You are a playwright. Given the title of play and the era it is set in, it is your job to write a synopsis for that title.

Title: {title}
Era: {era}
Playwright: This is a synopsis for the above play:`;

Insert cell
promptTemplate = new PromptTemplate({
template,
inputVariables: ["title", "era"],
});

Insert cell
synopsisChain = new LLMChain({
llm,
prompt: promptTemplate,
outputKey: "synopsis",
});

Insert cell
Insert cell
// This is an LLMChain to write a review of a play given a synopsis.
reviewLLM = new OpenAI({ temperature: 0, openAIApiKey: openaiApiKey});

Insert cell
reviewTemplate = `You are a play critic from the New York Times. Given the synopsis of play, it is your job to write a review for that play.
Play Synopsis:
{synopsis}
Review from a New York Times play critic of the above play:`;

Insert cell
reviewPromptTemplate = new PromptTemplate({
template: reviewTemplate,
inputVariables: ["synopsis"],
});

Insert cell
reviewChain = new LLMChain({
llm: reviewLLM,
prompt: reviewPromptTemplate,
outputKey: "review",
openAIApiKey: openaiApiKey
});


Insert cell
Insert cell
overallChain = new SequentialChain({
chains: [synopsisChain, reviewChain],
inputVariables: ["era", "title"],
// Here we return multiple variables
outputVariables: ["synopsis", "review"],
verbose: true,
openAIApiKey: openaiApiKey
});

Insert cell
Insert cell
chainExecutionResult = await overallChain.call({
title: "Tragedy at sunset on the beach",
era: "Victorian England",
});

Insert cell
Insert cell
OPEN_METEO_DOCS = `BASE URL: https://api.open-meteo.com/

API Documentation
The API endpoint /v1/forecast accepts a geographical coordinate, a list of weather variables and responds with a JSON hourly weather forecast for 7 days. Time always starts at 0:00 today and contains 168 hours. All URL parameters are listed below:

Parameter Format Required Default Description
latitude, longitude Floating point Yes Geographical WGS84 coordinate of the location
hourly String array No A list of weather variables which should be returned. Values can be comma separated, or multiple &hourly= parameter in the URL can be used.
daily String array No A list of daily weather variable aggregations which should be returned. Values can be comma separated, or multiple &daily= parameter in the URL can be used. If daily weather variables are specified, parameter timezone is required.
current_weather Bool No false Include current weather conditions in the JSON output.
temperature_unit String No celsius If fahrenheit is set, all temperature values are converted to Fahrenheit.
windspeed_unit String No kmh Other wind speed speed units: ms, mph and kn
precipitation_unit String No mm Other precipitation amount units: inch
timeformat String No iso8601 If format unixtime is selected, all time values are returned in UNIX epoch time in seconds. Please note that all timestamp are in GMT+0! For daily values with unix timestamps, please apply utc_offset_seconds again to get the correct date.
timezone String No GMT If timezone is set, all timestamps are returned as local-time and data is returned starting at 00:00 local-time. Any time zone name from the time zone database is supported. If auto is set as a time zone, the coordinates will be automatically resolved to the local time zone.
past_days Integer (0-2) No 0 If past_days is set, yesterday or the day before yesterday data are also returned.
start_date
end_date String (yyyy-mm-dd) No The time interval to get weather data. A day must be specified as an ISO8601 date (e.g. 2022-06-30).
models String array No auto Manually select one or more weather models. Per default, the best suitable weather models will be combined.

Variable Valid time Unit Description
temperature_2m Instant °C (°F) Air temperature at 2 meters above ground
snowfall Preceding hour sum cm (inch) Snowfall amount of the preceding hour in centimeters. For the water equivalent in millimeter, divide by 7. E.g. 7 cm snow = 10 mm precipitation water equivalent
rain Preceding hour sum mm (inch) Rain from large scale weather systems of the preceding hour in millimeter
showers Preceding hour sum mm (inch) Showers from convective precipitation in millimeters from the preceding hour
weathercode Instant WMO code Weather condition as a numeric code. Follow WMO weather interpretation codes. See table below for details.
snow_depth Instant meters Snow depth on the ground
freezinglevel_height Instant meters Altitude above sea level of the 0°C level
visibility Instant meters Viewing distance in meters. Influenced by low clouds, humidity and aerosols. Maximum visibility is approximately 24 km.`;

Insert cell
model = new OpenAI({ modelName: "text-davinci-003", openAIApiKey: openaiApiKey});
Insert cell
chain = APIChain.fromLLMAndAPIDocs(model, OPEN_METEO_DOCS, {
headers: {
// These headers will be used for API requests made by the chain.
},
});
Insert cell
Insert cell
res = await chain.call({
question:
"What is the weather like right now in Rockville, Maryland in degrees Farenheit?",
});
Insert cell
Insert cell
z = await import ('https://cdn.jsdelivr.net/npm/zod@3.22.2/+esm')
Insert cell
chatModels = import("https://esm.sh/langchain/chat_models/openai");
Insert cell
ChatOpenAI = chatModels.ChatOpenAI
Insert cell
createExtractionChainFromZod = chains.createExtractionChainFromZod;
Insert cell
zodSchema = z.object({
"person-name": z.string().optional(),
"person-age": z.number().optional(),
"person-hair_color": z.string().optional(),
"dog-name": z.string().optional(),
"dog-breed": z.string().optional(),
});
Insert cell
chatModel = new ChatOpenAI({
modelName: "gpt-3.5-turbo-0613",
temperature: 0,
openAIApiKey: openaiApiKey
});

Insert cell
extractionChain = createExtractionChainFromZod(zodSchema, chatModel);

Insert cell
Description = `Alex is 5 feet tall. Claudia is 4 feet taller Alex and jumps higher than him. Claudia is a brunette and Alex is blonde.
Alex's dog Frosty is a labrador and likes to play hide and seek.`
Insert cell
extractedInfo = await extractionChain.run(Description)
Insert cell
Insert cell
MultiPromptChain = chains.MultiPromptChain;
Insert cell
OpenAIChat = langchain.OpenAIChat
Insert cell
llm = new OpenAIChat({openAIApiKey: openaiApiKey, temperature: 1.0});
Insert cell
promptNames = ["physics", "math", "history"];

Insert cell
promptDescriptions = [
"Good for answering questions about physics",
"Good for answering math questions",
"Good for answering questions about history",
];

Insert cell
physicsTemplate = `You are a very smart physics professor who talks like Harry Potter. You are great at answering questions about physics in a concise and easy to understand manner. When you don't know the answer to a question you admit that you don't know.

Here is a question:
{input}`;
Insert cell
mathTemplate = `You are a very good mathematician who talks like George Washington. You are great at answering math questions. You are so good because you are able to break down hard problems into their component parts, answer the component parts, and then put them together to answer the broader question.

Here is a question:
{input}`;
Insert cell

historyTemplate = `You are a very smart history professor who talks like a serial killer. You are great at answering questions about history in a concise and easy to understand manner. When you don't know the answer to a question you admit that you don't know.

Here is a question:
{input}`;
Insert cell
promptTemplates = [physicsTemplate, mathTemplate, historyTemplate];
Insert cell
multiPromptChain = MultiPromptChain.fromLLMAndPrompts(llm, {
promptNames,
promptDescriptions,
promptTemplates,
});
Insert cell
result1 = multiPromptChain.call({
input: "What is the speed of light?",
});
Insert cell
result2 = multiPromptChain.call({
input: "Introduce yourself and tell me: What is the derivative of x^2?",
});
Insert cell
result3 = multiPromptChain.call({
input: "Introduce yourself and tell me: Who was the first president of the United States?",
});
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more