A TypeScript client for interacting with Grok AI. This client provides automated login functionality, cookie management, and comprehensive interaction with Grok's API.
- Automated browser-based login to Grok via X.AI auth
- Cookie persistence to avoid repeated logins
- Automatic handling of expired cookies
- Send messages to Grok with customizable options
- Continue conversations with follow-up messages
- Support for image attachments
- Customizable search settings and image generation
- Support for custom instructions and reasoning mode
- Conversation management
# Using npm
npm install grok-api-ts
# Using pnpm
pnpm add grok-api-ts
# Using yarn
yarn add grok-api-tsimport GrokAPI from 'grok-api-ts';
// Or use named import
// import { GrokAPI } from 'grok-api-ts';
async function main() {
// Initialize the Grok API (will prompt for login if needed)
const grokApi = new GrokAPI();
// If not authenticated, you'll need to login
if (!grokApi.isAuthenticated()) {
await grokApi.login('[email protected]', 'your-password');
}
// Start a new conversation
const response = await grokApi.sendMessage({
message: "What are the three laws of robotics?",
});
console.log(response.fullMessage);
// Continue the conversation
const followUp = await grokApi.continueConversation(
"Who created these laws and in what book did they first appear?"
);
console.log(followUp.fullMessage);
}
main();The client handles authentication automatically:
- First, it checks for existing cookies stored in
grok-cookies.json - If valid cookies are found, they will be used for API requests
- If no cookies are found, you'll need to call
login(username, password)method - During login, a real browser will open to complete the authentication via X.AI's auth system
- After successful login, cookies are saved for future use
- If cookies expire during usage, the client will detect auth failures and prompt for re-login
import GrokAPI from 'grok-api-ts';
async function main() {
const grokApi = new GrokAPI();
// Ensure authenticated
await grokApi.ensureAuthenticated('[email protected]', 'your-password');
// Start a new conversation with custom options
const response = await grokApi.sendMessage({
message: "Explain the concept of quantum computing",
disableSearch: false, // Enable web search (default)
enableImageGeneration: true, // Allow Grok to generate images (default)
customInstructions: "Explain in simple terms with analogies",
forceConcise: true // Request a more concise response
});
console.log(response.fullMessage);
// Access response metadata
if (response.metadata?.followUpSuggestions) {
console.log("Follow-up suggestions:", response.metadata.followUpSuggestions);
}
// Access conversation information
const { conversationId, lastResponseId } = grokApi.getConversationInfo();
console.log(`Conversation ID: ${conversationId}`);
}
main();The client supports streaming responses, allowing you to process Grok's response as it's being generated:
import GrokAPI from 'grok-api-ts';
async function main() {
const grokApi = new GrokAPI();
await grokApi.ensureAuthenticated();
// Use streaming API with callbacks
await grokApi.sendMessageStream(
{
message: "Write a story about a space adventure",
},
{
// Called for each token of the response
onToken: (token: string) => {
process.stdout.write(token);
},
// Called when the response is complete with full response data
onComplete: (response: ParsedGrokResponse) => {
console.log("\nResponse completed!");
console.log("Follow-up suggestions:", response.metadata?.followUpSuggestions);
},
// Called if an error occurs during streaming
onError: (error: any) => {
console.error("Error during streaming:", error);
}
}
);
}
main();The client automatically handles authentication errors:
import GrokAPI from 'grok-api-ts';
async function main() {
const grokApi = new GrokAPI();
try {
// Try making a request
const response = await grokApi.sendMessage({
message: "Hello Grok!"
});
console.log(response.fullMessage);
} catch (error) {
// If authentication failed, login and retry
console.log("Authentication error, attempting login...");
const loginSuccess = await grokApi.login('[email protected]', 'your-password');
if (loginSuccess) {
// Retry the request after successful login
const response = await grokApi.sendMessage({
message: "Hello Grok!"
});
console.log(response.fullMessage);
}
}
}
main();You can specify a custom location for cookie storage:
const grokApi = new GrokAPI([], '/path/to/your/cookies.json');All types are exported for TypeScript users:
import GrokAPI, {
GrokSendMessageOptions,
ParsedGrokResponse,
GrokModelResponse
} from 'grok-api-ts';
// Use types in your code
const options: GrokSendMessageOptions = {
message: "Hello Grok!",
disableSearch: true
};
// Type safety for function returns
const handleResponse = (response: ParsedGrokResponse) => {
console.log(response.fullMessage);
};constructor(cookieStrings?: string[], cookiesPath?: string)cookieStrings: Optional array of cookie stringscookiesPath: Optional path to the cookies file (defaults togrok-cookies.json)
-
async login(username: string, password: string): Promise<boolean>Automates the login process using a real browser and returns success status. -
isAuthenticated(): booleanChecks if the client has valid authentication cookies. -
async ensureAuthenticated(username?: string, password?: string): Promise<boolean>Ensures the client is authenticated, triggering login if needed. -
async sendMessage(options: GrokSendMessageOptions): Promise<ParsedGrokResponse>Sends a message to Grok and returns the response.Options include:
message: The message text to senddisableSearch: Whether to disable web search capability (default: false)enableImageGeneration: Whether to allow Grok to generate images (default: true)customInstructions: Custom instructions to guide Grok's responseforceConcise: Request a more concise response (default: false)imageAttachments: Array of image attachmentsconversationId: ID of the conversation (defaults to 'new')parentResponseId: ID of the parent response for threadingisReasoning: Enable reasoning mode (default: false)
-
async continueConversation(message: string, options?: Omit<GrokSendMessageOptions, 'message'>): Promise<ParsedGrokResponse>Continues an existing conversation with a follow-up message. -
getConversationInfo(): { conversationId: string; lastResponseId: string }Returns information about the current conversation.
The ParsedGrokResponse includes:
fullMessage: The complete text response from GrokresponseId: Unique ID for the response (for continuing the conversation)title: Conversation title (for new conversations)metadata: Additional metadata including follow-up suggestionsmodelResponse: Detailed model response objectconversationId: ID of the conversation
- Node.js 14+
- Chrome browser installed (used by patchright for authentication)
MIT