This library performs conditional branching using natural language, powered by Google's Gemini API.
Think of it as a natural language if/else or switch statement.
- Natural Language branching: Branch complex, nuanced, or subjective conditions that are difficult to express with traditional code.
- Dynamic Branching: Select the most appropriate option from a set of choices based on a natural language prompt.
- Simple & Typed API: Easy-to-use, typed interface for seamless integration into TypeScript projects.
- Error Handling: Built-in error handling for API failures and unexpected responses.
npm install gemini-branchFirst, obtain a Google Gemini API key. You can get one from the Google AI Studio.
import { GeminiBranch } from 'gemini-branch';
import type { GeminiBranchResult } from 'gemini-branch';
let globalBranchResult: GeminiBranchResult | null = null;
globalBranchResult = await GeminiBranch({
condition: "Which is the morning greeting?",
choices: ["good morning", "hello", "good evening"],
apiKey: "YOUR GEMINI API KEY",
model: "gemma-3-27b-it",
});
console.log(globalBranchResult)
// { response: true, result: 'good morning', message: 'Success' }You need to select a model from the Gemini or Gemma 3 model list.
GeminiBranch is the main function that performs the conditional branching.
| Parameter | Type | Description | Required |
|---|---|---|---|
| condition | string | The natural language condition used for branching. | Yes |
| choices | string[] | A list of candidate values. Gemini selects the single best-matching option. | Yes |
| apiKey | string | Your Google Gemini API Key. | Yes |
| model | string | The model to use for branching. | Yes |
| else | string | A fallback value returned when no choice sufficiently matches the condition. | No |
| consoleErrors | boolean | Log internal errors to the console. Default is false. | No |
| Parameter | Type | Description |
|---|---|---|
| response | boolean | true : The library executed correctly (including when the fallback else value is returned). false : An internal error occurred (API failure, schema violation, etc.). |
| result | string | On success, a Gemini-selected value from choices or the fallback (else) value; on failure, "" or the else value if provided. |
| message | string | Error message on failure, "Success" on success, "No matching choice" when else is selected |
else is not provided, the model is instructed to output "" when no choice matches.
This project is licensed under the MIT License. See the LICENSE file for details.