import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
apiKey: process.env.GEMINI_API_KEY,
});
async function main() {
const response = await ai.models.generateContent({
model: "gemini-3-flash-preview",
contents: "How does AI work?",
config: {
systemInstruction: "You are a cat. Your name is Neko.",
},
});
console.log(response.text);
}
await main();
import { GoogleGenAI } from "@google/genai";
async function main() {
const ai = new GoogleGenAI({
apiKey: process.env.GEMINI_API_KEY,
});
const config = {
thinkingConfig: {
thinkingBudget: 0,
},
};
const model = "gemini-3-flash-preview";
const contents = [
{
role: "user",
parts: [
{
text: `INSERT_INPUT_HERE`,
},
],
},
];
const response = await ai.models.generateContentStream({
model,
config,
contents,
});
let fileIndex = 0;
for await (const chunk of response) {
console.log(chunk.text);
}
}
main();
import { GoogleGenAI } from "@google/genai";
async function main() {
const ai = new GoogleGenAI({
apiKey: "YOUR_GEMINI_API_KEY", // In browser, get from user input or secure storage
});
const config = {
responseModalities: ["IMAGE", "TEXT"],
};
const model = "gemini-2.5-flash-image";
const contents = [
{
role: "user",
parts: [
{
text: `INSERT_INPUT_HERE`,
},
],
},
];
const response = await ai.models.generateContentStream({
model,
config,
contents,
});
let imageUrls: string[] = [];
let textContent = "";
for await (const chunk of response) {
if (!chunk.candidates || !chunk.candidates[0].content || !chunk.candidates[0].content.parts) {
continue;
}
const parts = chunk.candidates[0].content.parts;
for (const part of parts) {
if (part.inlineData) {
// Create a portable data URL for the image
const { mimeType, data } = part.inlineData;
const imageUrl = `data:${mimeType};base64,${data}`;
imageUrls.push(imageUrl);
console.log("Generated image URL:", imageUrl);
} else if (part.text) {
textContent += part.text;
console.log("Text response:", part.text);
}
}
}
// Return or use the image URLs and text
return { imageUrls, textContent };
}
main();
import { GoogleGenAI } from "@google/genai";
async function main() {
const ai = new GoogleGenAI({
apiKey: "YOUR_GEMINI_API_KEY", // In browser, get from user input or secure storage
});
const config = {
responseModalities: ["IMAGE"],
};
const model = "gemini-2.5-flash-image";
const contents = [
{
role: "user",
parts: [
{
inlineData: {
data: `...data url to image`, // Replace with actual base64 data without data: prefix
mimeType: `image/jpeg`,
},
},
{
inlineData: {
data: `...data url to image`, // Replace with actual base64 data without data: prefix
mimeType: `image/jpeg`,
},
},
{
text: `Blend the two images into one`,
},
],
},
];
const response = await ai.models.generateContentStream({
model,
config,
contents,
});
let imageUrls: string[] = [];
let textContent = "";
for await (const chunk of response) {
if (!chunk.candidates || !chunk.candidates[0].content || !chunk.candidates[0].content.parts) {
continue;
}
const parts = chunk.candidates[0].content.parts;
for (const part of parts) {
if (part.inlineData) {
// Create a portable data URL for the image
const { mimeType, data } = part.inlineData;
const imageUrl = `data:${mimeType};base64,${data}`;
imageUrls.push(imageUrl);
console.log("Generated image URL:", imageUrl);
} else if (part.text) {
textContent += part.text;
console.log("Text response:", part.text);
}
}
}
// Return or use the image URLs and text
return { imageUrls, textContent };
}
main();
import { GoogleGenAI } from "@google/genai";
function saveBinaryFile(fileName: string, content: Buffer) {
writeFile(fileName, content, "utf8", (err) => {
if (err) {
console.error(`Error writing file ${fileName}:`, err);
return;
}
console.log(`File ${fileName} saved to file system.`);
});
}
async function main() {
const ai = new GoogleGenAI({
apiKey: process.env.GEMINI_API_KEY,
});
const config = {
responseModalities: ["IMAGE"],
};
const model = "gemini-2.5-flash-image";
const contents = [
{
role: "user",
parts: [
{
text: `INSERT_INPUT_HERE`,
},
],
},
];
}
main();
// To run this code you need to install the following dependencies:
// npm install @google/genai mime
// npm install -D @types/node
import { GoogleGenAI } from "@google/genai";
import mime from "mime";
import { writeFile } from "fs";
function saveBinaryFile(fileName: string, content: Buffer) {
writeFile(fileName, content, "utf8", (err) => {
if (err) {
console.error(`Error writing file ${fileName}:`, err);
return;
}
console.log(`File ${fileName} saved to file system.`);
});
}
async function main() {
const ai = new GoogleGenAI({
apiKey: process.env.GEMINI_API_KEY,
});
const config = {
responseModalities: ["IMAGE", "TEXT"],
};
const model = "gemini-2.5-flash-image";
const contents = [
{
role: "user",
parts: [
{
text: `INSERT_INPUT_HERE`,
},
],
},
];
const response = await ai.models.generateContentStream({
model,
config,
contents,
});
let fileIndex = 0;
for await (const chunk of response) {
if (!chunk.candidates || !chunk.candidates[0].content || !chunk.candidates[0].content.parts) {
continue;
}
if (chunk.text) {
console.log("text chunk:", chunk.text);
}
}
}
main();
import { GoogleGenAI } from "@google/genai";
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
const spamDetailsSchema = z.object({
reason: z.string().describe("The reason why the content is considered spam."),
spam_type: z.enum(["phishing", "scam", "unsolicited promotion", "other"]).describe("The type of spam."),
});
const notSpamDetailsSchema = z.object({
summary: z.string().describe("A brief summary of the content."),
is_safe: z.boolean().describe("Whether the content is safe for all audiences."),
});
const moderationResultSchema = z.object({
decision: z.union([spamDetailsSchema, notSpamDetailsSchema]),
});
const ai = new GoogleGenAI({});
const prompt = `
Please moderate the following content and provide a decision.
Content: 'Congratulations! You''ve won a free cruise to the Bahamas. Click here to claim your prize: www.definitely-not-a-scam.com'
`;
const response = await ai.models.generateContent({
model: "gemini-3-flash-preview",
contents: prompt,
config: {
responseMimeType: "application/json",
responseJsonSchema: zodToJsonSchema(moderationResultSchema),
},
});
const result = moderationResultSchema.parse(JSON.parse(response.text));
console.log(result);
// OUTPUT
// {
// "decision": {
// "reason": "Content tricks the user into clicking suspicious link",
// "spam_type": "scam"
// }
// }
import { GoogleGenAI, SchemaType } from "@google/genai";
import { JSONParser } from "@streamparser/json";
import { Observable } from "rxjs";
// Define the shape of our data
interface Person {
name: string;
}
function generatePeopleStream(): Observable<Person> {
return new Observable((subscriber) => {
const ai = new GoogleGenAI({
apiKey: process.env.GEMINI_API_KEY,
});
const schema = {
type: SchemaType.ARRAY,
items: {
type: SchemaType.OBJECT,
properties: {
name: { type: SchemaType.STRING },
},
required: ["name"],
},
};
const parser = new JSONParser();
// Emit values to the subscriber as they are parsed
parser.onValue = ({ value, key }) => {
// Ensure we are parsing an item inside the array (key is an index)
if (typeof key === "number" && value && typeof value === "object") {
subscriber.next(value as Person);
}
};
// Start the async generation process
(async () => {
try {
const response = await ai.models.generateContentStream({
model: "gemini-3-flash-preview",
config: {
responseMimeType: "application/json",
responseSchema: schema,
},
contents: [
{
role: "user",
parts: [{ text: "Generate a list of 5 fictional people." }],
},
],
});
for await (const chunk of response) {
const textPart = chunk.candidates?.[0]?.content?.parts?.[0]?.text;
if (textPart) {
parser.write(textPart);
}
}
subscriber.complete();
} catch (error) {
subscriber.error(error);
}
})();
});
}
// Usage Example
async function main() {
const people$ = generatePeopleStream();
console.log("Subscribing to stream...");
people$.subscribe({
next: (person) => console.log("Received person:", person),
error: (err) => console.error("Stream error:", err),
complete: () => console.log("Stream completed."),
});
}
main();