-
Notifications
You must be signed in to change notification settings - Fork 35
feat: add grok provider #51
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,9 +1,11 @@ | ||
import { GeminiModelProvider } from './providers/gemini.js'; | ||
import { ClaudeModelProvider } from './providers/claude.js'; | ||
import { OpenAiModelProvider } from './providers/open-ai.js'; | ||
import { GrokModelProvider } from './providers/grok.js'; | ||
|
||
export const MODEL_PROVIDERS = [ | ||
new GeminiModelProvider(), | ||
new ClaudeModelProvider(), | ||
new OpenAiModelProvider(), | ||
new GrokModelProvider(), | ||
]; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,113 @@ | ||
import { xAI } from '@genkit-ai/compat-oai/xai'; | ||
import { GenkitPlugin, GenkitPluginV2 } from 'genkit/plugin'; | ||
import { RateLimiter } from 'limiter'; | ||
import fetch from 'node-fetch'; | ||
import { | ||
GenkitModelProvider, | ||
PromptDataForCounting, | ||
RateLimitConfig, | ||
} from '../model-provider.js'; | ||
|
||
export class GrokModelProvider extends GenkitModelProvider { | ||
readonly apiKeyVariableName = 'XAI_API_KEY'; | ||
|
||
protected readonly models = { | ||
'grok-4': () => xAI.model('grok-4'), | ||
'grok-code-fast-1': () => xAI.model('grok-code-fast-1'), | ||
}; | ||
|
||
private async countTokensWithXaiApi( | ||
prompt: PromptDataForCounting | ||
): Promise<number | null> { | ||
const apiKey = this.getApiKey(); | ||
if (!apiKey) { | ||
return null; | ||
} | ||
|
||
try { | ||
// Use xAI's tokenize API for accurate token counting | ||
const messages = this.genkitPromptToXaiFormat(prompt); | ||
const text = messages.map((m) => `${m.role}: ${m.content}`).join('\n'); | ||
|
||
const response = await fetch('https://api.x.ai/v1/tokenize', { | ||
method: 'POST', | ||
headers: { | ||
'Content-Type': 'application/json', | ||
Authorization: `Bearer ${apiKey}`, | ||
}, | ||
body: JSON.stringify({ text }), | ||
}); | ||
|
||
if (response.ok) { | ||
const data = (await response.json()) as { tokens: unknown[] }; | ||
return data.tokens?.length || 0; | ||
} | ||
return null; | ||
} catch (error) { | ||
console.warn('Failed to count tokens using xAI API', error); | ||
return null; | ||
} | ||
} | ||
|
||
private async countTokensForModel( | ||
_modelName: string, | ||
prompt: PromptDataForCounting | ||
): Promise<number> { | ||
const xaiTokenCount = await this.countTokensWithXaiApi(prompt); | ||
if (xaiTokenCount !== null) { | ||
return xaiTokenCount; | ||
} | ||
return 0; | ||
} | ||
|
||
protected rateLimitConfig: Record<string, RateLimitConfig> = { | ||
// XAI Grok rate limits https://docs.x.ai/docs/models | ||
'xai/grok-4': { | ||
requestPerMinute: new RateLimiter({ | ||
tokensPerInterval: 480, | ||
interval: 1000 * 60 * 1.5, // Refresh tokens after 1.5 minutes to be on the safe side | ||
}), | ||
tokensPerMinute: new RateLimiter({ | ||
tokensPerInterval: 2_000_000 * 0.75, | ||
interval: 1000 * 60 * 1.5, // Refresh tokens after 1.5 minutes to be on the safe side | ||
}), | ||
countTokens: (prompt) => this.countTokensForModel('grok-4', prompt), | ||
}, | ||
'xai/grok-code-fast-1': { | ||
requestPerMinute: new RateLimiter({ | ||
tokensPerInterval: 480, | ||
interval: 1000 * 60 * 1.5, // Refresh tokens after 1.5 minutes to be on the safe side | ||
}), | ||
tokensPerMinute: new RateLimiter({ | ||
tokensPerInterval: 2_000_000 * 0.75, | ||
interval: 1000 * 60 * 1.5, // Refresh tokens after 1.5 minutes to be on the safe side | ||
}), | ||
countTokens: (prompt) => | ||
this.countTokensForModel('grok-code-fast-1', prompt), | ||
}, | ||
}; | ||
|
||
protected pluginFactory(apiKey: string): GenkitPlugin | GenkitPluginV2 { | ||
return xAI({ apiKey }); | ||
} | ||
|
||
getModelSpecificConfig(): object { | ||
// Grok doesn't require special configuration at this time | ||
return {}; | ||
} | ||
|
||
private genkitPromptToXaiFormat( | ||
prompt: PromptDataForCounting | ||
): Array<{ role: string; content: string }> { | ||
const xaiPrompt: Array<{ role: string; content: string }> = []; | ||
for (const part of prompt.messages) { | ||
for (const c of part.content) { | ||
xaiPrompt.push({ | ||
role: part.role, | ||
content: 'media' in c ? c.media.url : c.text, | ||
}); | ||
} | ||
} | ||
return [...xaiPrompt, { role: 'user', content: prompt.prompt }]; | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.