bolt.new/app/lib/.server/llm/stream-text.ts
Vishwanath Martur fdefd717b0 Add groq support
Related to #4763

Add groq API support with groq SDK.

* **Initialize groq instance**: Import `createGroq` from `groq` SDK and add `createGroqInstance`, `getGroqModel`, and `getGroqLlamaModel` functions in `app/lib/.server/llm/model.ts`.
* **Stream text responses**: Import `getGroqModel` in `app/lib/.server/llm/stream-text.ts`, update `streamText` function to use `getGroqModel`, and set headers for the `groq` instance.
* **Add constants**: Add constants for maximum tokens and response segments limits for the `groq` model in `app/lib/.server/llm/constants.ts`.
* **Retrieve API key**: Update `getAPIKey` function in `app/lib/.server/llm/api-key.ts` to retrieve the API key for the `groq` model.
* **Update routes**: Import `createGroq` in `app/routes/api.chat.ts` and `app/routes/api.enhancer.ts`.
2024-12-28 13:58:12 +05:30

36 lines
1009 B
TypeScript

import { streamText as _streamText, convertToCoreMessages } from 'ai';
import { getAPIKey } from '~/lib/.server/llm/api-key';
import { getGroqModel } from '~/lib/.server/llm/model';
import { MAX_TOKENS } from './constants';
import { getSystemPrompt } from './prompts';
interface ToolResult<Name extends string, Args, Result> {
toolCallId: string;
toolName: Name;
args: Args;
result: Result;
}
interface Message {
role: 'user' | 'assistant';
content: string;
toolInvocations?: ToolResult<string, unknown, unknown>[];
}
export type Messages = Message[];
export type StreamingOptions = Omit<Parameters<typeof _streamText>[0], 'model'>;
export function streamText(messages: Messages, env: Env, options?: StreamingOptions) {
return _streamText({
model: getGroqModel(getAPIKey(env)),
system: getSystemPrompt(),
maxTokens: MAX_TOKENS,
headers: {
'groq-beta': 'max-tokens-3-5-sonnet-2024-07-15',
},
messages: convertToCoreMessages(messages),
...options,
});
}