const session = await LanguageModel.create();
const answer = await session.prompt("What is 2 + 2?");
console.log(answer);LanguageModel: create() static method / notebook
LanguageModel: create() static method
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
const session = await LanguageModel.create({
initialPrompts: [
{
role: "system",
content: "You are a concise assistant. Respond in one sentence.",
},
],
});
const response = await session.prompt("What is photosynthesis?");
console.log(response);const session = await LanguageModel.create({
monitor(monitor) {
monitor.addEventListener("downloadprogress", ({ loaded, total }) => {
console.log(`Model download: ${Math.round((loaded / total) * 100)}%`);
});
},
});const session = await LanguageModel.create({
expectedInputs: [{ type: "text", languages: ["en"] }],
expectedOutputs: [{ type: "text", languages: ["en", "fr"] }],
initialPrompts: [
{
role: "system",
content:
"Translate the user's input to French. Use the output format 'English input: French output'",
},
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hello: Bonjour" },
{ role: "user", content: "Goodbye" },
{ role: "assistant", content: "Goodbye: Au revoir" },
{ role: "user", content: "The train is late" },
{
role: "assistant",
content: "The train is late: Le train est en retard",
},
{ role: "user", content: "My shoes are pink" },
{
role: "assistant",
content: "My shoes are pink: Mes chaussures sont roses",
},
],
});
const result = await session.prompt("Window");
console.log(result); // "Window: Fenêtre"async function getWeatherData(location) {
const response = await fetch(
`https://api.example.com/weather?city=${location}`,
);
const data = await response.json();
return `${data.temp}°C, ${data.description}`;
}
const session = await LanguageModel.create({
tools: [
{
name: "getWeather",
description: "Returns the current weather for a given city.",
inputSchema: {
type: "object",
properties: {
location: { type: "string", description: "The city name." },
},
required: ["location"],
},
async execute(...args) {
const location = args[0];
return await getWeatherData(location);
},
},
],
});
const response = await session.prompt("What's the weather like in Tokyo?");
console.log(response);const controller = new AbortController();
const cancelButton = document.getElementById("cancel-button");
cancelButton.addEventListener("click", () => controller.abort());
const session = await LanguageModel.create({
signal: controller.signal,
initialPrompts: [
{
role: "system",
content: "You are a helpful assistant.",
},
],
});