Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.
The create() static method of the LanguageModel interface constructs a new LanguageModel instance, automatically downloading the corresponding model data if it is not already available.
LanguageModel.create()
LanguageModel.create(options)options OptionalAn object representing the options for creating a LanguageModel session. Properties include:
expectedInputsAn array of objects representing the required input modalities and languages. Each object can include the following properties:
typeAn enumerated value indicating the content type. Must be one of:
textPlain text content.
imageImage content.
audioAudio content.
tool-callA tool invocation issued by the model.
tool-responseThe result of a tool invocation.
languages OptionalAn array of strings containing BCP 47 language tags (for example, en, fr, ja) that the session is expected to handle for this content type. The user agent uses this list to determine whether the model supports the specified languages and to select appropriate model components or fine-tunings.
expectedOutputsAn array of objects representing the required output modalities and languages. Each object can include the following properties:
typeAn enumerated value indicating the content type. Must be one of:
textPlain text content.
imageImage content.
audioAudio content.
tool-callA tool invocation issued by the model.
tool-responseThe result of a tool invocation.
languages OptionalAn array of strings containing BCP 47 language tags (for example, en, fr, ja) that the session is expected to handle for this content type. The user agent uses this list to determine whether the model supports the specified languages and to select appropriate model components or fine-tunings.
initialPromptsAn array of objects representing messages passed during the creation of a language model session. This allows the model to "remember" instructions or previous dialogue without resending them with every new query. Each object can include the following properties:
roleA string indicating the point of view the message is phrased from. Must be one of:
systemA system-level instruction that guides the model's overall behavior. This must be the first instruction passed to the model.
userA message from the user, which the API should respond to.
assistantAn input that provides context for the AI assistant, such as its persona or the format of its responses. Such messages mainly serve to provide context/history, and further shape how the model responds.
contentA string representing a textual prompt, or an array of objects. Each object includes the following properties:
typeAn enumerated value representing the type of content. This can be one of:
audioAudio content.
imageImage content.
textTextual content.
tool-callA tool invocation issued by the model.
tool-responseThe result of a tool invocation.
valueThe content of the message. If the type is text, this is always a string. If the type is audio or image, the value can be one of several different object types; see What data types are accepted?.
prefix OptionalA boolean, defaulting to false. When true, the message is treated as a prefix for the model's next generated response rather than a complete turn.
monitorA reference to a CreateMonitor callback function to receive download progress events.
signalAn AbortSignal to cancel session creation.
toolsAn array of objects representing tools available to the AI. Each object can include the following properties:
nameA string giving the tool a unique name the model uses to refer to it when issuing a tool call.
descriptionA string describing what the tool does. The model uses this description to decide if and when to invoke the tool.
inputSchemaA JSON Schema that describes the tool's input parameters. The model uses this schema to construct the arguments it passes to the tool's execute function.
executeA callback function that the user agent invokes when the model calls this tool. Its arguments are specific to the model being used. It must return a Promise that resolves with a String representing the tool's result.
A Promise that resolves with a new LanguageModel instance.
AbortError DOMExceptionThrown if the operation was aborted via the signal option.
InvalidStateError DOMExceptionThrown if the calling document is not fully active.
NotAllowedError DOMExceptionThrown if usage of the method is blocked by a language-model Permissions-Policy.
NotSupportedError DOMExceptionThrown if:
role is assistant and its type is anything other than text.type is text and its value is not a string.type is image or audio but the type was not listed in expectedInputs, or the value is not an accepted data type.OperationError DOMExceptionThrown if creation fails for any other reason not listed in the other exception types.
QuotaExceededError DOMExceptionThrown if the content provided in initialPrompts exceeds the model's LanguageModel.contextWindow.
SyntaxError DOMExceptionThrown if:
prefix property is set to true and:role is not assistant.TypeError DOMExceptionThrown if:
role is system but it was not the first message passed to the context.The create() method constructs a new language model session, automatically downloading the model if it is not already available. You can monitor progress of a model download using the monitor option.
Before calling create(), use LanguageModel.availability() to check whether the desired configuration is supported.
Once a session is created, use its instance methods — LanguageModel.prompt(), LanguageModel.promptStreaming(), LanguageModel.append(), and others — to interact with the model.
Transient user activation is required. The user has to interact with the page or a UI element for this feature to work.
This example creates a default session and then prompts it for the result of summing 2 and 2. Note that text is supported by default, so the downloaded model should be suitable for this case.
const session = await LanguageModel.create();
const answer = await session.prompt("What is 2 + 2?");
console.log(answer);See also Using the Prompt API > Creating a LanguageModel session.
The following example provides the AI with instructions on the persona to adopt before generating an answer.
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);This code shows how you can monitor the download progress of a model. Note that if the model is unavailable or already available, the event will never fire.
const session = await LanguageModel.create({
monitor(monitor) {
monitor.addEventListener("downloadprogress", ({ loaded, total }) => {
console.log(`Model download: ${Math.round((loaded / total) * 100)}%`);
});
},
});See also Using the Prompt API > Monitoring download progress.
The following example shows how to use a few-shot prompt to ask the API for a specific task (French translation) to be delivered in a specific format, before providing some examples to help it learn the correct output format.
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"See also Adding context with initial and ongoing prompt inputs > Few-shot prompts.
This example creates a session with a hypothetical "get weather" tool. When the model decides to call the tool, the user agent invokes execute() with the arguments the model provides.
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);The following example enables a user to cancel a prompt. It does this by first creating an AbortController and assigning its abort() method to a cancel button's click handler. Next, it calls create() and passes AbortController.signal as the signal property.
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.",
},
],
});See also Using the Prompt API > Cancelling operations and destroying instances.