write-language 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,211 @@
1
+ # write-language
2
+
3
+ Multi-provider language generation toolkit using Vercel AI SDK. Generate AI responses with 10+ LLM providers including OpenAI, Anthropic, Google, AWS Bedrock, and more.
4
+
5
+ ## Features
6
+
7
+ - 🤖 **Multi-Provider Support**: Works with 10+ LLM providers
8
+ - OpenAI (GPT-4, GPT-3.5)
9
+ - Anthropic (Claude 3.5, Claude 3)
10
+ - Google (Gemini, PaLM)
11
+ - AWS Bedrock
12
+ - Groq
13
+ - xAI (Grok)
14
+ - Cloudflare Workers AI
15
+ - Ollama (local models)
16
+ - OpenRouter
17
+ - And more!
18
+
19
+ - 📝 **Flexible Response Generation**: Stream or non-stream responses
20
+ - 🔧 **Model Registry**: Complete catalog of available models by provider
21
+ - 🎯 **Provider Factory**: Easy provider initialization
22
+ - 📋 **Pre-built Prompts**: Ready-to-use agent prompt templates
23
+ - 🛠️ **Tool Support**: Function calling and tool use capabilities
24
+ - 🎨 **Markdown to HTML**: Built-in markdown rendering with syntax highlighting
25
+
26
+ ## Installation
27
+
28
+ ```bash
29
+ npm install write-language
30
+ ```
31
+
32
+ ## Usage
33
+
34
+ ### Basic Response Generation
35
+
36
+ ```typescript
37
+ import { generateLanguageResponse } from 'write-language';
38
+
39
+ const result = await generateLanguageResponse({
40
+ provider: 'openai',
41
+ model: 'gpt-4-turbo',
42
+ prompt: 'Explain quantum computing in simple terms',
43
+ apiKey: process.env.OPENAI_API_KEY
44
+ });
45
+
46
+ console.log(result.text);
47
+ ```
48
+
49
+ ### Streaming Responses
50
+
51
+ ```typescript
52
+ const result = await generateLanguageResponse({
53
+ provider: 'anthropic',
54
+ model: 'claude-3-5-sonnet-20241022',
55
+ prompt: 'Write a short story about AI',
56
+ apiKey: process.env.ANTHROPIC_API_KEY,
57
+ stream: true
58
+ });
59
+
60
+ for await (const chunk of result.textStream) {
61
+ process.stdout.write(chunk);
62
+ }
63
+ ```
64
+
65
+ ### Using the Model Registry
66
+
67
+ ```typescript
68
+ import {
69
+ LANGUAGE_MODELS,
70
+ getModelsByProvider,
71
+ getModelsByCapability
72
+ } from 'write-language';
73
+
74
+ // Get all OpenAI models
75
+ const openaiModels = getModelsByProvider('openai');
76
+
77
+ // Get all multimodal models
78
+ const multimodalModels = getModelsByCapability('multimodal');
79
+
80
+ // Check specific model info
81
+ const gpt4Info = LANGUAGE_MODELS['gpt-4-turbo'];
82
+ console.log(gpt4Info);
83
+ // {
84
+ // name: 'GPT-4 Turbo',
85
+ // provider: 'openai',
86
+ // contextWindow: 128000,
87
+ // capabilities: ['text', 'multimodal', 'function-calling'],
88
+ // ...
89
+ // }
90
+ ```
91
+
92
+ ### Custom Provider Setup
93
+
94
+ ```typescript
95
+ import { createLLMProvider } from 'write-language';
96
+
97
+ const provider = createLLMProvider(
98
+ 'groq',
99
+ process.env.GROQ_API_KEY
100
+ );
101
+
102
+ const model = provider('llama-3.3-70b-versatile');
103
+ ```
104
+
105
+ ### Using Agent Prompts
106
+
107
+ ```typescript
108
+ import { AGENT_PROMPTS } from 'write-language';
109
+
110
+ const result = await generateLanguageResponse({
111
+ provider: 'openai',
112
+ model: 'gpt-4',
113
+ prompt: AGENT_PROMPTS.researchAgent.systemPrompt,
114
+ messages: [
115
+ {
116
+ role: 'user',
117
+ content: 'Research the latest developments in fusion energy'
118
+ }
119
+ ],
120
+ apiKey: process.env.OPENAI_API_KEY
121
+ });
122
+ ```
123
+
124
+ ### Markdown to HTML Conversion
125
+
126
+ ```typescript
127
+ import { convertMarkdownToHTMLEscaped } from 'write-language';
128
+
129
+ const markdown = '# Hello\n\n```javascript\nconsole.log("world");\n```';
130
+ const html = convertMarkdownToHTMLEscaped(markdown);
131
+ ```
132
+
133
+ ## API Reference
134
+
135
+ ### `generateLanguageResponse(options)`
136
+
137
+ Generate an AI language response.
138
+
139
+ **Options:**
140
+ - `provider` (string): LLM provider name
141
+ - `model` (string): Model identifier
142
+ - `prompt` (string): System prompt or initial prompt
143
+ - `apiKey` (string): Provider API key
144
+ - `messages` (array, optional): Conversation history
145
+ - `stream` (boolean, optional): Enable streaming
146
+ - `maxTokens` (number, optional): Maximum tokens to generate
147
+ - `temperature` (number, optional): Sampling temperature
148
+ - `tools` (array, optional): Available tools for function calling
149
+
150
+ **Returns:** `GenerateLanguageResult` with `text`, `textStream`, `finishReason`, etc.
151
+
152
+ ### `createLLMProvider(provider, apiKey, options)`
153
+
154
+ Create a provider instance.
155
+
156
+ **Parameters:**
157
+ - `provider`: Provider name
158
+ - `apiKey`: API key
159
+ - `options`: Additional provider options
160
+
161
+ **Returns:** Provider function
162
+
163
+ ### Model Registry Functions
164
+
165
+ - `getModelsByProvider(provider)`: Get all models for a provider
166
+ - `getAllModels()`: Get all available models
167
+ - `getModelsByCapability(capability)`: Filter by capability
168
+ - `getTextOnlyModels()`: Get text-only models
169
+ - `getMultimodalModels()`: Get multimodal models
170
+
171
+ ## Supported Providers
172
+
173
+ | Provider | Models | Capabilities |
174
+ |----------|--------|--------------|
175
+ | OpenAI | GPT-4, GPT-3.5, o1, o3 | Text, Multimodal, Functions |
176
+ | Anthropic | Claude 3.5, Claude 3 | Text, Multimodal, Functions |
177
+ | Google | Gemini 2.0, Gemini 1.5 | Text, Multimodal |
178
+ | AWS Bedrock | Claude, Llama, Mistral | Text, Multimodal |
179
+ | Groq | Llama 3, Mixtral | Text, Fast Inference |
180
+ | xAI | Grok | Text |
181
+ | Cloudflare | Various | Text, Edge Deployment |
182
+ | Ollama | Local Models | Text, Privacy |
183
+ | OpenRouter | 100+ Models | Text, Aggregator |
184
+
185
+ ## Environment Variables
186
+
187
+ Set API keys for the providers you want to use:
188
+
189
+ ```bash
190
+ OPENAI_API_KEY=sk-...
191
+ ANTHROPIC_API_KEY=sk-ant-...
192
+ GOOGLE_API_KEY=...
193
+ GROQ_API_KEY=gsk_...
194
+ XAI_API_KEY=xai-...
195
+ AWS_ACCESS_KEY_ID=...
196
+ AWS_SECRET_ACCESS_KEY=...
197
+ CLOUDFLARE_ACCOUNT_ID=...
198
+ CLOUDFLARE_API_TOKEN=...
199
+ ```
200
+
201
+ ## License
202
+
203
+ AGPL-3.0
204
+
205
+ ## Author
206
+
207
+ vtempest <grokthiscontact@gmail.com>
208
+
209
+ ## Contributing
210
+
211
+ Issues and PRs welcome at [github.com/vtempest/ai-research-agent](https://github.com/vtempest/ai-research-agent)
package/package.json ADDED
@@ -0,0 +1,106 @@
1
+ {
2
+ "name": "write-language",
3
+ "version": "0.1.3",
4
+ "description": "Multi-provider language generation toolkit using Vercel AI SDK - generate responses with 10+ LLM providers including OpenAI, Anthropic, Google, and more.",
5
+ "author": "vtempest <grokthiscontact@gmail.com>",
6
+ "license": "rights.institute/PROSPER",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/vtempest/ai-research-agent",
10
+ "directory": "packages/write-language"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/vtempest/ai-research-agent/issues"
14
+ },
15
+ "main": "./dist/write-language.cjs.js",
16
+ "types": "./dist/types.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/types.d.ts",
20
+ "import": "./dist/write-language.es.js",
21
+ "require": "./dist/write-language.cjs.js"
22
+ },
23
+ "./*": {
24
+ "types": "./src/*.ts",
25
+ "react-server": "./src/*",
26
+ "import": "./src/*",
27
+ "require": "./src/*"
28
+ }
29
+ },
30
+ "typesVersions": {
31
+ "*": {
32
+ "*": [
33
+ "src/*"
34
+ ]
35
+ }
36
+ },
37
+ "files": [
38
+ "dist",
39
+ "src"
40
+ ],
41
+ "sideEffects": false,
42
+ "scripts": {
43
+ "build": "vite build",
44
+ "test": "vitest",
45
+ "test-ui": "vitest --ui --watch",
46
+ "make": "rm -rf dist/*; NODE_OPTIONS=--max-old-space-size=15192 vite build",
47
+ "ship": "npx standard-version --release-as patch && npm publish --access public"
48
+ },
49
+ "peerDependencies": {
50
+ "next": ">=15.0.0",
51
+ "vinext": ">=0.1.0 || >=1.0.0-0"
52
+ },
53
+ "peerDependenciesMeta": {
54
+ "next": {
55
+ "optional": true
56
+ },
57
+ "vinext": {
58
+ "optional": true
59
+ }
60
+ },
61
+ "devDependencies": {
62
+ "@vitest/ui": "^4.0.18",
63
+ "terser": "^5.46.0",
64
+ "typescript": "^5.9.3",
65
+ "vite": "^8.1.3",
66
+ "vite-plugin-dts": "^5.0.3",
67
+ "vite-plugin-node-polyfills": "^0.28.0",
68
+ "vitest": "^4.0.18"
69
+ },
70
+ "dependencies": {
71
+ "@ai-sdk/amazon-bedrock": "^3.0.0",
72
+ "@ai-sdk/anthropic": "^2.0.0",
73
+ "@ai-sdk/google": "^2.0.0",
74
+ "@ai-sdk/google-vertex": "^3.0.0",
75
+ "@ai-sdk/groq": "^2.0.0",
76
+ "@ai-sdk/mcp": "^1.0.0",
77
+ "@ai-sdk/openai": "^2.0.0",
78
+ "@ai-sdk/xai": "^2.0.0",
79
+ "@openrouter/ai-sdk-provider": "^1.2.0",
80
+ "ai": "^5.0.0",
81
+ "highlight.js": "^11.11.1",
82
+ "html-entities": "^2.6.0",
83
+ "marked": "^17.0.4",
84
+ "workers-ai-provider": "^3.1.14",
85
+ "zod": "^4.3.6"
86
+ },
87
+ "keywords": [
88
+ "ai",
89
+ "llm",
90
+ "language-generation",
91
+ "vercel-ai-sdk",
92
+ "nlp",
93
+ "multi-provider",
94
+ "groq",
95
+ "openai",
96
+ "anthropic",
97
+ "google",
98
+ "aws-bedrock",
99
+ "cloudflare-workers",
100
+ "ollama",
101
+ "hacktoberfest"
102
+ ],
103
+ "publishConfig": {
104
+ "access": "public"
105
+ }
106
+ }
@@ -0,0 +1,196 @@
1
+ /**
2
+ * @fileoverview Core logic for generating AI language responses using Vercel AI SDK and various LLM providers.
3
+ * Handles prompt interpolation, tool calling, and response formatting.
4
+ */
5
+ import { generateText, stepCountIs, tool } from "ai";
6
+ import { AGENT_PROMPTS } from "./prompt-templates";
7
+ import { AGENT_TOOLS } from "../tools/qwksearch-api-tools";
8
+ import { LANGUAGE_MODELS, LANGUAGE_PROVIDERS } from "./language-model-registry";
9
+ import { createLLMProvider } from "./provider-factory";
10
+ import { convertMarkdownToHTMLEscaped } from "../utils/markdown-to-html";
11
+ import type {
12
+ AgentPrompt,
13
+ AgentTool,
14
+ GenerateLanguageOptions,
15
+ GenerateLanguageResult,
16
+ } from "./generation-types";
17
+
18
+ export type {
19
+ LLMProviderName,
20
+ GenerateLanguageOptions,
21
+ GenerateLanguageResult,
22
+ } from "./generation-types";
23
+ export { convertMarkdownToHTMLEscaped } from "../utils/markdown-to-html";
24
+
25
+ /**
26
+ * ### Generate Language Response
27
+ * Writes a language response that shows human-like understanding of the
28
+ * question and context.
29
+ * - _Requires_: LLM provider, API key, agent name, and context variables.
30
+ * - _Providers_: groq, togetherai, openai, anthropic, xai, google,
31
+ * perplexity, cloudflare, nvidia
32
+ * - _Agent Templates_: custom local entries defined in AGENT_PROMPTS.
33
+ * - _How it Works_: Language models predict the most likely next token given
34
+ * a prompt. They represent words as high-dimensional vectors, use
35
+ * transformer attention across all prior tokens, and sample from the
36
+ * resulting probability distribution to produce human-like text.
37
+ *
38
+ * @see [Vercel AI SDK generateText docs](https://sdk.vercel.ai/docs/reference/ai-sdk-core/generate-text)
39
+ * @see [Hugging Face tutorials](https://huggingface.co/learn)
40
+ * @see [Illustrated Transformer](https://jalammar.github.io/illustrated-transformer/)
41
+ * @see [Building a Transformer with PyTorch](https://www.datacamp.com/tutorial/building-a-transformer-with-py-torch)
42
+ * @see [LLM training example](https://github.com/vtempest/ai-research-agent/blob/master/packages/neural-net/src/train/predict-next-word.js)
43
+ *
44
+ * @param options - Configuration for the language-model call
45
+ * @returns Resolved response object with `content`, optional `extract`, or `error`
46
+ * @author [Language Model Researchers](https://arc.net/folder/D0472A20-9C20-4D3F-B145-D2865C0A9FEE)
47
+ * @example
48
+ * const response = await generateLanguageResponse({
49
+ * query: "Explain neural networks",
50
+ * agent: "question",
51
+ * provider: "groq",
52
+ * apiKey: "your-api-key",
53
+ * });
54
+ */
55
+ export async function generateLanguageResponse(
56
+ options: GenerateLanguageOptions = {} as GenerateLanguageOptions,
57
+ ): Promise<GenerateLanguageResult> {
58
+ const {
59
+ apiKey,
60
+ agent = "question",
61
+ temperature = 1,
62
+ html = true,
63
+ applyContextLimit = true,
64
+ ...context
65
+ } = options;
66
+
67
+ // Normalise provider to lowercase for consistent switch matching
68
+ const provider = options.provider?.toLowerCase();
69
+
70
+ // Resolve model: explicit override \u2192 provider's registered default
71
+ const model =
72
+ options.model ??
73
+ (LANGUAGE_MODELS as Array<{ provider: string; default?: string }>).find(
74
+ (m) => m.provider.toLowerCase() === provider,
75
+ )?.default ??
76
+ "";
77
+
78
+ try {
79
+ // \u2500\u2500 1. Validate required inputs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
80
+ const validProviders = LANGUAGE_PROVIDERS as string[];
81
+ if (!apiKey || !provider || !validProviders.includes(provider)) {
82
+ return {
83
+ error:
84
+ "API key and provider are required. Valid providers: " +
85
+ validProviders.join(", "),
86
+ };
87
+ }
88
+
89
+ // \u2500\u2500 2. Load agent prompt from local registry \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
90
+ const agentObject = (AGENT_PROMPTS as AgentPrompt[]).find(
91
+ (p) => p?.name === agent,
92
+ );
93
+
94
+ if (!agentObject) return { error: `Agent "${agent}" not found` };
95
+
96
+ // \u2500\u2500 3. Pre-process the prompt template via optional `before` hook \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
97
+ if (agentObject.before) {
98
+ agentObject.prompt = agentObject.before(agentObject.prompt, options);
99
+ }
100
+
101
+ // \u2500\u2500 4. Build template variable map and interpolate placeholders \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
102
+ const templateVars: Record<string, unknown> = {
103
+ ...options,
104
+ input: `${context.query ?? ""} ${context.article ?? ""}`,
105
+ };
106
+ let prompt = interpolateTemplate(agentObject.template ?? "", templateVars);
107
+
108
+ // \u2500\u2500 5. Trim prompt to the model's context window \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
109
+ if (applyContextLimit) {
110
+ const modelConfig = (
111
+ LANGUAGE_MODELS as Array<{
112
+ provider: string;
113
+ models: Array<{ id: string; contextLength: number }>;
114
+ }>
115
+ )
116
+ .find((m) => m.provider.toLowerCase() === provider)
117
+ ?.models.find((m) => m.id === model);
118
+
119
+ if (modelConfig) {
120
+ prompt = prompt.slice(0, modelConfig.contextLength);
121
+ }
122
+ }
123
+
124
+ // \u2500\u2500 6. Instantiate the LLM provider \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
125
+ const llm = createLLMProvider(provider, apiKey, model, temperature);
126
+ if (!llm) return { error: "Invalid provider selected" };
127
+
128
+ // \u2500\u2500 7. Resolve tools declared by the agent \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
129
+ const agentToolDefs = (AGENT_TOOLS as AgentTool[]).filter((t) =>
130
+ agentObject.tools?.includes(t.name),
131
+ );
132
+ const tools =
133
+ agentToolDefs.length > 0
134
+ ? Object.fromEntries(
135
+ agentToolDefs.map((t) => [
136
+ t.name,
137
+ tool({
138
+ description: t.description as string,
139
+ inputSchema: t.schema as any,
140
+ execute: t.func as (args: any) => Promise<string>,
141
+ }),
142
+ ]),
143
+ )
144
+ : undefined;
145
+
146
+ // \u2500\u2500 8. Invoke LLM via Vercel AI SDK generateText \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
147
+ const { text: rawReply } = await generateText({
148
+ model: llm,
149
+ prompt,
150
+ temperature,
151
+ ...(tools && { tools, stopWhen: stepCountIs(10) }),
152
+ });
153
+
154
+ // \u2500\u2500 9. Format output (HTML or raw Markdown) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
155
+ const content: string = html
156
+ ? await convertMarkdownToHTMLEscaped(rawReply)
157
+ : rawReply;
158
+
159
+ // \u2500\u2500 10. Extract structured data via optional `after` hook \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
160
+ const extract = agentObject.after?.(rawReply, options);
161
+
162
+ return { content, ...(extract !== undefined && { extract }) };
163
+ } catch (err) {
164
+ const error = err as { response?: { status?: number }; message?: string };
165
+ return {
166
+ error:
167
+ error.response?.status === 429
168
+ ? "Rate limit exceeded. Please wait before trying again."
169
+ : (error.message ??
170
+ "Failed to generate response. Please try again later."),
171
+ };
172
+ }
173
+ }
174
+
175
+ /**
176
+ * Substitutes `{variableName}` placeholders in a template string with values
177
+ * from `vars`. Object/array values are pretty-printed without braces or
178
+ * commas. Unmatched keys fall back to `"[not provided]"`.
179
+ *
180
+ * @param template - Template string containing `{key}` placeholders
181
+ * @param vars - Map of variable names to their replacement values
182
+ * @returns The fully interpolated string
183
+ */
184
+ function interpolateTemplate(
185
+ template: string,
186
+ vars: Record<string, unknown>,
187
+ ): string {
188
+ return template.replace(/\{(.+?)\}/g, (_match, key: string) => {
189
+ if (!(key in vars)) return "[not provided]";
190
+ const value = vars[key];
191
+ if (typeof value === "string") return value;
192
+ return JSON.stringify(value, null, 2)
193
+ .replace(/[{}"]/g, "")
194
+ .replace(/,/g, "\n");
195
+ });
196
+ }
@@ -0,0 +1,90 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * @module research/agents/generate-language-types
4
+ * @description Shared types for the generate-language module.
5
+ */
6
+
7
+ /** Supported LLM provider identifiers */
8
+ export type LLMProviderName =
9
+ | "nvidia"
10
+ | "openrouter"
11
+ | "anthropic"
12
+ | "google"
13
+ | "openai"
14
+ | "xai"
15
+ | "groq"
16
+ | "cloudflare"
17
+ | "perplexity"
18
+ | "amazon"
19
+ | "bedrock"
20
+ | "togetherai"
21
+ | (string & {}); // preserve autocomplete while allowing arbitrary strings
22
+
23
+ /**
24
+ * Configuration options for {@link generateLanguageResponse}.
25
+ */
26
+ export interface GenerateLanguageOptions {
27
+ /** LLM provider to use */
28
+ provider: LLMProviderName;
29
+ /**
30
+ * API key for the provider.
31
+ * For `cloudflare`, use the `"apiToken:accountId"` format.
32
+ * For `amazon`/`bedrock`, use bearer token or `"region:accessKeyId:secretAccessKey"` format.
33
+ */
34
+ apiKey?: string;
35
+ /** Agent prompt template name (default: `"question"`) */
36
+ agent?: string;
37
+ /** Specific model ID. Falls back to the provider's registered default. */
38
+ model?: string;
39
+ /**
40
+ * Sampling temperature (0\u20132).
41
+ * Lower = more deterministic; higher = more creative. Default: `1`
42
+ */
43
+ temperature?: number;
44
+ /** User query text */
45
+ query?: string;
46
+ /** Article or document text to process */
47
+ article?: string;
48
+ /** Prior conversation history for context-aware agents */
49
+ chat_history?: string;
50
+ /** Return `HTML` (`true`) or raw Markdown (`false`). Default: `true` */
51
+ html?: boolean;
52
+ /** Truncate the prompt to the model's context window length. Default: `true` */
53
+ applyContextLimit?: boolean;
54
+ /** Additional template variables forwarded to the agent prompt */
55
+ [key: string]: unknown;
56
+ }
57
+
58
+ /** Return value of {@link generateLanguageResponse} */
59
+ export interface GenerateLanguageResult {
60
+ /** Generated response in HTML or Markdown format */
61
+ content?: string;
62
+ /** Structured data extracted by the agent's `after` callback */
63
+ extract?: unknown;
64
+ /** Human-readable error message when generation fails */
65
+ error?: string;
66
+ }
67
+
68
+ /** Agent prompt template definition */
69
+ export interface AgentPrompt {
70
+ name: string;
71
+ /** Mustache-style template string with `{variableName}` placeholders */
72
+ template?: string;
73
+ prompt?: string;
74
+ /** Called before template substitution to pre-process the prompt */
75
+ before?: (
76
+ prompt: string | undefined,
77
+ options: GenerateLanguageOptions,
78
+ ) => string;
79
+ /** Called after generation to extract structured data from the raw reply */
80
+ after?: (reply: string, options: GenerateLanguageOptions) => unknown;
81
+ /** Names of registered agent tools to attach to this agent */
82
+ tools?: string[];
83
+ }
84
+
85
+ /** A registered agent tool with a name, schema, and async handler */
86
+ export interface AgentTool {
87
+ name: string;
88
+ func: (...args: unknown[]) => unknown | Promise<unknown>;
89
+ [key: string]: unknown;
90
+ }
package/src/index.ts ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * @fileoverview Language Generation Module
3
+ *
4
+ * Centralized exports for AI language model response generation using Vercel AI SDK.
5
+ * Provides prompt templates, model registries, provider factories, and response
6
+ * generation functions for 10+ LLM providers.
7
+ *
8
+ * @module language-generation
9
+ * @author ai-research-agent contributors
10
+ */
11
+
12
+ export {
13
+ generateLanguageResponse,
14
+ convertMarkdownToHTMLEscaped,
15
+ } from "./generate-response";
16
+
17
+ export type {
18
+ LLMProviderName,
19
+ GenerateLanguageOptions,
20
+ GenerateLanguageResult,
21
+ } from "./generate-response";
22
+
23
+ export type {
24
+ AgentPrompt,
25
+ AgentTool,
26
+ } from "./generation-types";
27
+
28
+ export { AGENT_PROMPTS, extractJSONFromLanguageReply } from "./prompt-templates";
29
+ export {
30
+ LANGUAGE_MODELS,
31
+ LANGUAGE_PROVIDERS,
32
+ getModelsByProvider,
33
+ getAllModels,
34
+ getModelsByCapability,
35
+ getTextOnlyModels,
36
+ getMultimodalModels,
37
+ } from "./language-model-registry";
38
+ export type { ModelCapability, ModelInfo } from "./language-model-registry";
39
+ export { createLLMProvider } from "./provider-factory";
40
+ export * from "./prompts";