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.
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.
new ChatGoogleGenerativeAI({
model: env.GEMINI_MODEL ?? "gemini-flash-latest",
apiKey: env.GEMINI_API_KEY,
temperature,
maxRetries: 0, // we handle failures ourselves (module 9)
});Messages
SystemMessage
You write slide decks in SlideML…
HumanMessage
Write the deck for this outline: {…}
AIMessage
<deck><TitleSlide …/>…</deck>
SystemMessage: the standing rules, exactly like the system instruction you used withgemini.js.HumanMessage: this request.AIMessage: whatinvoke()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.