Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 | 7x 7x 7x 7x 7x 7x 7x 7x 14x 14x 14x 14x 14x 12x 12x 2x 10x 1x 2x 2x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 3x 2x 2x 2x 1x 1x 2x 2x 2x 2x 3x 2x 2x 2x 1x 1x 2x 2x 2x 2x | import {
Injectable,
Logger,
NotFoundException,
ForbiddenException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, DataSource, FindOptionsWhere } from 'typeorm';
import { ContextTemplate, TemplateType } from '../core-entities';
import {
CreateContextTemplateDto,
PreviewContextTemplateDto,
PreviewContextTemplateResponseDto,
UpdateContextTemplateDto,
} from './dto/context-template.dto';
import { ContextGenerationService } from '../context-generation/context-generation.service';
import { countTokens } from 'gpt-tokenizer';
import { CustomVariablesService } from '../custom-variables/custom-variables.service';
@Injectable()
export class ContextTemplatesService {
private readonly logger = new Logger(ContextTemplatesService.name);
constructor(
@InjectRepository(ContextTemplate)
private contextTemplatesRepository: Repository<ContextTemplate>,
private dataSource: DataSource,
private readonly contextGenerationService: ContextGenerationService,
private readonly customVariablesService: CustomVariablesService,
) {}
async create(
createContextTemplateDto: CreateContextTemplateDto,
): Promise<ContextTemplate> {
const template = this.contextTemplatesRepository.create(
createContextTemplateDto,
);
return this.contextTemplatesRepository.save(template);
}
async findAll(type?: TemplateType): Promise<ContextTemplate[]> {
const where: FindOptionsWhere<ContextTemplate> = {};
Iif (type) {
where.template_type = type;
}
return this.contextTemplatesRepository.find({
where,
order: { template_name: 'ASC' },
});
}
async findOne(id: string): Promise<ContextTemplate> {
const template = await this.contextTemplatesRepository.findOneBy({ id });
if (!template) {
throw new NotFoundException(`ContextTemplate with ID "${id}" not found`);
}
return template;
}
async findByName(name: string): Promise<ContextTemplate | null> {
return this.contextTemplatesRepository.findOneBy({ template_name: name });
}
async findByBuiltinKey(builtinKey: string): Promise<ContextTemplate | null> {
return this.contextTemplatesRepository.findOneBy({
builtin_key: builtinKey,
});
}
async findDefaultInitial(): Promise<ContextTemplate | null> {
return this.contextTemplatesRepository.findOneBy({
is_default_initial: true,
});
}
async findDefaultFollowup(): Promise<ContextTemplate | null> {
return this.contextTemplatesRepository.findOneBy({
is_default_followup: true,
});
}
async update(
id: string,
updateContextTemplateDto: UpdateContextTemplateDto,
): Promise<ContextTemplate> {
const template = await this.findOne(id);
// Check if builtin - forbid modification
if (template.is_builtin) {
throw new ForbiddenException(
`Cannot modify built-in context template "${template.template_name}". Duplicate it to create your own version.`,
);
}
const {
template_name,
template_content,
context_definition,
template_type,
} = updateContextTemplateDto;
// is_default should be handled by specific methods to ensure only one default exists.
this.contextTemplatesRepository.merge(template, {
template_name,
template_content,
context_definition,
template_type,
});
return this.contextTemplatesRepository.save(template);
}
async remove(id: string): Promise<void> {
const template = await this.findOne(id);
await this.contextTemplatesRepository.remove(template);
}
async duplicate(id: string): Promise<ContextTemplate> {
const originalTemplate = await this.findOne(id);
// Generate unique name for the duplicate
let newName = `${originalTemplate.template_name} (Copy)`;
let suffix = 2;
while (
await this.contextTemplatesRepository.findOneBy({
template_name: newName,
})
) {
newName = `${originalTemplate.template_name} (Copy ${suffix})`;
suffix++;
}
// The `is_default` flags will be false by default in the new entity.
// Create duplicate with user ownership
const duplicate = this.contextTemplatesRepository.create({
template_name: newName,
template_content: originalTemplate.template_content,
context_definition: originalTemplate.context_definition,
template_type: originalTemplate.template_type,
is_builtin: false,
builtin_key: null,
});
return this.contextTemplatesRepository.save(duplicate);
}
/**
* Update content of a built-in template (for version upgrades).
* Only callable from seeding service.
*/
async updateBuiltinContent(
id: string,
templateContent: string,
): Promise<ContextTemplate> {
const template = await this.contextTemplatesRepository.findOneBy({ id });
Iif (!template) {
throw new NotFoundException(`ContextTemplate with ID "${id}" not found`);
}
template.template_content = templateContent;
return this.contextTemplatesRepository.save(template);
}
async preview(
dto: PreviewContextTemplateDto,
): Promise<PreviewContextTemplateResponseDto> {
const adHocData: {
adhoc_files_content: string;
adhoc_folders_content: string;
} = {
adhoc_files_content: '',
adhoc_folders_content: '',
};
Iif (dto.context_definition) {
Iif (
dto.context_definition.files &&
dto.context_definition.files.length > 0
) {
const fileContents = await Promise.all(
dto.context_definition.files.map((filePath: string) =>
this.contextGenerationService.secureReadFile(filePath),
),
);
adHocData.adhoc_files_content = fileContents.join('\n\n');
}
Iif (
dto.context_definition.folders &&
dto.context_definition.folders.length > 0
) {
const folderContexts = await Promise.all(
dto.context_definition.folders.map(async (folderPath: string) => {
const tree =
await this.contextGenerationService.secureTree(folderPath);
const header = `// Tree for: ${folderPath}\n\`\`\`\n${tree}\n\`\`\``;
const filesInFolder =
await this.contextGenerationService.secureGlob(
`${folderPath}/**/*`,
);
const fileContents = await Promise.all(
filesInFolder.map((filePath: string) =>
this.contextGenerationService.secureReadFile(filePath),
),
);
return [header, ...fileContents].join('\n\n');
}),
);
adHocData.adhoc_folders_content = folderContexts.join('\n\n---\n\n');
}
}
const enabledVariables = await this.customVariablesService.findAllEnabled();
const variableMap = enabledVariables.reduce((acc, curr) => {
acc[curr.key] = curr.value;
return acc;
}, {});
const data = {
...adHocData,
// Add other potential template variables here if needed, like user_input or system_prompt
// For now, these are not part of the preview DTO, so they'll be empty.
user_input: '',
system_prompt: '',
ad_hoc_context_definition: JSON.stringify(dto.context_definition || {}),
VAR: variableMap,
};
const rendered_context = await this.contextGenerationService.render(
dto.template_content,
data,
);
// Using character length as a proxy for token count for now.
// const token_count = rendered_context.length;
const token_count = countTokens(rendered_context);
return {
rendered_context,
token_count,
};
}
async setDefaultInitial(id: string): Promise<ContextTemplate> {
const newDefault = await this.findOne(id);
await this.dataSource.transaction(async (manager) => {
const currentDefault = await manager.findOneBy(ContextTemplate, {
is_default_initial: true,
});
if (currentDefault && currentDefault.id !== newDefault.id) {
currentDefault.is_default_initial = false;
await manager.save(currentDefault);
}
if (!newDefault.is_default_initial) {
newDefault.is_default_initial = true;
await manager.save(newDefault);
}
});
return newDefault;
}
async setDefaultFollowup(id: string): Promise<ContextTemplate> {
const newDefault = await this.findOne(id);
await this.dataSource.transaction(async (manager) => {
const currentDefault = await manager.findOneBy(ContextTemplate, {
is_default_followup: true,
});
if (currentDefault && currentDefault.id !== newDefault.id) {
currentDefault.is_default_followup = false;
await manager.save(currentDefault);
}
if (!newDefault.is_default_followup) {
newDefault.is_default_followup = true;
await manager.save(newDefault);
}
});
return newDefault;
}
async setDefaultCondensed(id: string): Promise<ContextTemplate> {
const newDefault = await this.findOne(id);
await this.dataSource.transaction(async (manager) => {
const currentDefault = await manager.findOneBy(ContextTemplate, {
is_default_condensed: true,
});
Iif (currentDefault && currentDefault.id !== newDefault.id) {
currentDefault.is_default_condensed = false;
await manager.save(currentDefault);
}
Iif (!newDefault.is_default_condensed) {
newDefault.is_default_condensed = true;
await manager.save(newDefault);
}
});
return newDefault;
}
}
|