Purrx

Chat models and messages

Create a Gemini chat model with LangChain, send system and human messages with invoke(), and read the reply's text, including replies made of several parts.

10 min+25 XPHands-on

The first LangChain file is small and important: it's where the project creates models. Every other file receives a model and never needs to know which one it is, or where the API key comes from.

src/llm.js (createModel)
new ChatGoogleGenerativeAI({
  model: env.GEMINI_MODEL ?? "gemini-flash-latest",
  apiKey: env.GEMINI_API_KEY,
  temperature,
  maxRetries: 0,   // we handle failures ourselves (module 9)
});

Messages

  1. SystemMessage

    You write slide decks in SlideML…

  2. HumanMessage

    Write the deck for this outline: {…}

  3. AIMessage

    <deck><TitleSlide …/>…</deck>

A chat model takes an array of messages and returns one more. The system message sets the rules; the human message is this request; the AI message is the reply.
  • SystemMessage: the standing rules, exactly like the system instruction you used with gemini.js.
  • HumanMessage: this request.
  • AIMessage: what invoke() returns. You can also put earlier AI messages in the array to continue a conversation.

Reading the reply

reply.content is usually a string. With some features (like tools) it can be an array of parts instead. contentText() (written for you) handles both, so the rest of the project never has to think about it.

Under the hood — Where does the API key come from in the playground?

On your machine, process.env.GEMINI_API_KEY reads an environment variable. The playground sandbox provides the same process.env with the key from your Purrx settings, so the file runs unchanged in both places.

Key takeaways

  • createModel() is the one place that chooses the model, key and settings.
  • A request is an array of messages: SystemMessage for rules, HumanMessage for this request.
  • invoke() returns an AIMessage; its content is usually a string, but can be a list of parts.

Sign in to run the exercise

Reading is free. Writing code here needs an account so we have somewhere to keep your Gemini key and the +25 XP you are about to earn.