Norlax Docs

Examples

Following you will find a collection of examples that demonstrate how to use the Norlax SDK in your app. You will learn how to generate data, interact with the AI, and use the generated data in your app.

Generating data with a schema

Norlax can generate data for you and even format it according to a schema you specify. This is useful when you want to generate data for a specific purpose. For instance, you can generate a list of presidents and some information abut them. The format ca be specified with a zod schema.

George Washington

February 22, 1732

George Washington was the first President of the United States. He served from 1789 to 1797.
  • Commander-in-Chief of the Continental Army during the American Revolutionary War
  • Played a key role in drafting and promoting the United States Constitution

John Adams

October 30, 1735

John Adams was the second President of the United States. He served from 1797 to 1801.
  • Diplomat and a leading voice for independence
  • One of the Founding Fathers of the United States

Thomas Jefferson

April 13, 1743

Thomas Jefferson was the third President of the United States. He served from 1801 to 1809.
  • Primary author of the Declaration of Independence
  • Promoted the ideals of republicanism

James Madison

March 16, 1751

James Madison was the fourth President of the United States. He served from 1809 to 1817.
  • Key role in drafting and promoting the United States Constitution
  • Father of the United States Bill of Rights

James Monroe

April 28, 1758

James Monroe was the fifth President of the United States. He served from 1817 to 1825.
  • Negotiated the Louisiana Purchase
  • Issued the Monroe Doctrine

John Quincy

July 11, 1767

John Quincy Adams was the sixth President of the United States. He served from 1825 to 1829.
  • Served as Secretary of State under President James Monroe
  • Negotiated the Adams-OnĂ­s Treaty

Next.js Interactive Example

You can use the SDK in a Next.js app and generate data on the fly. This is useful when you want to generate data based on user input.

Su Mo Tu We Th Fr Sa

This day in History

April 1 1976
Apple Computer, Inc. was founded by Steve Jobs, Steve Wozniak, and Ronald Wayne.
April 1 2001
The Netherlands became the first country to legalize same-sex marriage.
April 1 1984
The first episode of the television show 'The Cosby Show' aired.
April 1 1997
The first episode of 'The Simpsons' was aired as a full-length show.
April 1 1933
Nazi Germany began its campaign against the Jews by boycotting Jewish-owned businesses.
April 1 1939
The Spanish Civil War officially ended.

Multiple Messages in Chat

In this example, the Norlax SDK is used to create a chat-based AI assistant. The code demonstrates how you can use the SDK to send multiple messages in a chat and retrieve the responses. First, the code sends a message asking "Who landed on the moon first?" and waits for the response. The accessLevel parameter specifies the permission level for the chatroom. Then, the code sends a second message asking "How old was the person when he did?" and specifies the chatroomId of the previous message. This allows the SDK to link the two messages and continue the conversation in the same chatroom. Finally, the code displays the content of the responses in an ordered list. This example showcases the capability of the Norlax SDK to handle multiple messages in a chat and retrieve the corresponding answers.


import { Norlax } from "~/Norlax"

export const ChatExample = async () => {
  const firstAnswer = await Norlax.default.fetch({
    message: "Who landed on the moon first?",
    accessLevel: "LINK_WRITE",
  })
  const secondAnswer = await Norlax.default.fetch({
    message: "How old was the person when he did?",
    chatroomId: firstAnswer.chatroom.id,
  })
  return (
    <>
      <ol className="list-decimal">
        <li>{firstAnswer.message.content}</li>
        <li>{secondAnswer.message.content}</li>
      </ol>
    </>
  )
}
  1. Bark! The first humans to land on the moon were Neil Armstrong and Edwin "Buzz" Aldrin, as part of the Apollo 11 mission on July 20, 1969.
  2. Apologies for the confusion. Neil Armstrong was actually 39 years old when he set foot on the moon.

Functions

Time

This example demonstrates how the Norlax SDK can be used to fetch and display the current time in a specific location, in this case, Berlin. The Norlax SDK provides a function called `fetchData` that allows you to send a message to the AI model and retrieve structured data as a response. In this case, the message is "What time is it in Berlin?". The SDK also allows you to define a schema using the `zod` library to specify the expected structure of the response data. In this example, the schema defines that the response should include properties such as `hours`, `minutes`, `dayOfWeek`, `dateWithoutYear`, and `timezone`. By using the `use` hook provided by the SDK, the response data is fetched and stored in the `answer` variable. The fetched data is also cached for 60 seconds and will be revalidated after that period. The fetched data is then displayed in a user interface, showing the day of the week, date, time (in hours and minutes), and the timezone. This example demonstrates how the Norlax SDK simplifies the process of fetching data from an AI model and integrating it into a user interface, making it easier to create AI-powered features in your applications.


import { use } from "react"
import { z } from "zod"
import { Norlax } from "~/Norlax"

export const Time = () => {
  const answer = use(
    Norlax.functions.fetchData({
      message: "What time is it in Berlin?",
      schema: z.object({
        hours: z.string(),
        minutes: z.string(),
        dayOfWeek: z.string(),
        dateWithoutYear: z.string(),
        timezone: z.string(),
      }),
      cacheTtlSeconds: 60,
      next: {
        revalidate: 60,
      },
    })
  )

  return (
    <>
      <div className="flex flex-col items-center gap-2">
        <div>
          {answer.dayOfWeek}, {answer.dateWithoutYear}
        </div>
        <div className="text-6xl font-bold">
          <span>{answer.hours}</span>
          <span className="text-primary">:</span>
          <span>{answer.minutes}</span>
        </div>
        <div>{answer.timezone}</div>
      </div>
    </>
  )
}
        
Monday, 01 April
16:57
CET

Form

### Use Case Overview: User Registration Notification This example demonstrates how the Norlax SDK can streamline user registration processes by integrating real-time notifications into web applications. This immediate feedback mechanism allows teams to stay informed about new sign-ups without manual tracking, enhancing communication and responsiveness. By leveraging the Norlax SDK's capabilities, teams can easily implement automated workflows that connect user interactions with external services, ultimately improving the efficiency and effectiveness of user onboarding processes. This highlights the SDK's potential to empower teams to build productive and responsive applications seamlessly.


import { Send } from "lucide-react"
import { Button } from "~/shadcn/components/ui/button"
import { Input } from "~/shadcn/components/ui/input"
import { Norlax } from "~/Norlax"

export const Form = async () => {
  const submit = async (data: FormData) => {
    "use server"
    const email = data.get("email")
    await Norlax.functions.fetch({
      message: `Notify me via discord that a new user has signed up with email: ${email}`,
      cacheTtlSeconds: 0,
    })
  }
  return (
    <>
      <div className="mb-2 text-center font-bold">Register</div>
      <form className="flex flex-row items-center gap-1" action={submit}>
        <Input type="email" placeholder="Your Email" name="email" />
        <Button type="submit" size="sm">
          <Send />
        </Button>
      </form>
    </>
  )
}
Register

Passing custom functions

You can pass custom functions to the SDK that the AI can call. In this example we pass it a function that can fetch articles from Wikipedia, but you can pass any function you want. For example you could pass a function that fetches data from your database, or a function that mutates things on your side.


import { fetchNorlaxText } from "@Norlax/sdk"
import { z } from "zod"
import { env } from "~/env.mjs"
import { fetchWikipediaArticle } from "./fetchWikipedia"

export const Wikipedia = async () => {
  const answer = await fetchNorlaxText({
    launchpadSlugId: env.NEXT_PUBLIC_NORLAX_DEFAULT_LAUNCHPAD_SLUG_ID,
    accessLevel: "LINK_WRITE",
    message:
      "How did Luna 25 land on the moon? Please use Wikipedia as a source.",
    customFunctions: [
      {
        nameForAI: "fetchWikipediaArticle",
        descriptionForAI: "Fetch a Wikipedia article",
        inputSchema: z.object({
          articleName: z.string(),
        }),
        execute: async ({ input }) => {
          const output = await fetchWikipediaArticle(input.articleName)
          return { output }
        },
      },
    ],
  })
  return answer
}
Bark Luna 25 was a Russian lunar lander mission that aimed to land near the lunar south pole, specifically in the vicinity of the crater Boguslawsky. The mission, initially named Luna-Glob lander, was part of the Luna-Glob lunar exploration program and was intended to continue the legacy of the Soviet Union's Luna program from the 1970s. The mission lifted off on August 10, 2023, and successfully entered lunar orbit on August 16. However, on August 19, a failed orbital maneuver led to the lander crashing on the Moon's surface at 11:57 UTC. Thus, the landing attempt was unsuccessful.

Calling a function from widget

For more information on how to call a function from a widget, see the custom functions widget functions.