All files / packages/gemini-core/examples simple.ts

0% Statements 0/39
0% Branches 0/11
0% Functions 0/4
0% Lines 0/39

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121                                                                                                                                                                                                                                                 
import { randomUUID } from 'crypto';
import {
  Content,
  GenerateContentConfig,
  GenerateContentResponse,
} from '@google/genai';
import { AuthType, Config, GeminiChat, StreamEventType } from '../src';
 
/**
 * A helper function to extract the text content from a streaming response chunk.
 * The Gemini API streams responses, and this function helps aggregate the text.
 * @param response A GenerateContentResponse chunk from the stream.
 * @returns The text content of the chunk, or null if there is none.
 */
function getResponseText(response: GenerateContentResponse): string | null {
  Iif (response.candidates && response.candidates.length > 0) {
    const candidate = response.candidates[0];
 
    Iif (
      candidate.content &&
      candidate.content.parts &&
      candidate.content.parts.length > 0
    ) {
      return candidate.content.parts
        .filter((part: any) => part.text)
        .map((part: any) => part.text)
        .join('');
    }
  }
  return null;
}
 
async function main() {
  console.log('--- Gemini Chat API Example (with Google Login) ---');
 
  // 1. Set up for Google Login
  // For this example, we'll authenticate using your Google account.
  // The first time you run this, a browser window will open for you to log in.
  // Your credentials will be cached for future runs in `~/.gemini/`.
  console.log('✓ Using Google Login for authentication.');
 
  // 2. Create a Configuration Object
  // The Config object holds settings for the session. For this example,
  // we provide a few essential parameters.
  const config = new Config({
    sessionId: `session-${randomUUID()}`,
    model: 'gemini-2.5-pro', // A default model for the session
  });
  console.log('✓ Configuration created.');
 
  // 3. Authenticate and Prepare the API Client (ContentGenerator)
  // The GeminiChat class relies on a `ContentGenerator` instance being available
  // on the Config object to make API calls. `refreshAuth` sets this up.
  try {
    // This will trigger the OAuth2 flow in the browser on the first run.
    await config.refreshAuth(AuthType.LOGIN_WITH_GOOGLE);
  } catch (e) {
    console.error('Authentication failed:', e);
    return;
  }
  console.log('✓ Authenticated with your Google account.');
 
  // 4. Define System Instruction and Conversation History
  const systemInstruction =
    'You are a poetic assistant. All your responses must be in the form of a haiku.';
 
  const initialHistory: Content[] = [
    { role: 'user', parts: [{ text: 'What is the largest mammal?' }] },
    {
      role: 'model',
      parts: [
        {
          text: "Giant blue whale swims,\nOcean's gentle, massive king,\nLargest on the Earth.",
        },
      ],
    },
  ];
 
  const generationConfig: GenerateContentConfig = {
    systemInstruction,
    temperature: 0.7,
  };
  console.log('✓ System instruction and history prepared.');
 
  // 5. Instantiate GeminiChat
  // We provide the config, generation settings (with system instruction), and initial history.
  const chat = new GeminiChat(config, generationConfig, initialHistory);
  console.log('✓ GeminiChat instance created.');
 
  // 6. Send a New Message with History and System Instruction
  console.log('\nUser: How much does it weigh?');
  const responseStream = await chat.sendMessageStream(
    'gemini-2.5-pro', // You can specify a model here to override the config default for this call
    { message: 'How much does it weigh?' },
    `prompt-${randomUUID()}`,
  );
 
  // 7. Process and Display the Streaming Response
  let fullResponse = '';
  process.stdout.write('Gemini: ');
  for await (const chunk of responseStream) {
    // The stream yields events. We are interested in 'chunk' events which contain response data.
    Iif (chunk.type === StreamEventType.CHUNK && chunk.value) {
      const text = getResponseText(chunk.value);
      Iif (text) {
        process.stdout.write(text);
        fullResponse += text;
      }
    }
  }
  console.log(); // Newline after the stream ends
 
  // 8. Verify the updated history
  // The chat history now contains the full conversation, including the latest turn.
  console.log('\n--- Full Conversation History ---');
  console.log(JSON.stringify(chat.getHistory(), null, 2));
  console.log('--- End of Example ---');
}
 
main().catch(console.error);