Skip to content

Commit

Permalink
(lint/pretty): ran pretty-write
Browse files Browse the repository at this point in the history
  • Loading branch information
iislucas committed Oct 26, 2024
1 parent e896dfa commit aba9cbe
Show file tree
Hide file tree
Showing 11 changed files with 218 additions and 218 deletions.
96 changes: 48 additions & 48 deletions src/fewshot_template.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
* @license SPDX-License-Identifier: Apache-2.0
*/

import { Template, template, nv, matchTemplate } from "./template";
import { FewShotTemplate, matchFewShotTemplate } from "./fewshot_template";
import { Template, template, nv, matchTemplate } from './template';
import { FewShotTemplate, matchFewShotTemplate } from './fewshot_template';

// // ----------------------------------------------------------------------------
// const movieSuggestionPrompt: Template<never> = template``;
Expand All @@ -16,29 +16,29 @@ import { FewShotTemplate, matchFewShotTemplate } from "./fewshot_template";
// Idea: abstraction: generate a variable (have a stopping condition as first
// class entity.

describe("fewshot_template", () => {
describe('fewshot_template', () => {
beforeEach(() => {});

it("A mini walkthrough of why this is neat...", () => {
it('A mini walkthrough of why this is neat...', () => {
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
const criteriaPoints = [
{
name: "Concise",
description: "not waffley.",
name: 'Concise',
description: 'not waffley.',
},
{
name: "No synposes",
description: "do not give plot synopses.",
name: 'No synposes',
description: 'do not give plot synopses.',
},
{
name: "Specific",
name: 'Specific',
description: 'not vague (i.e. not "an amazing movie.", "a classic.").',
},
];
const nCriteriaTempl = new FewShotTemplate(
template`(${nv("number")}) ${nv("name")}: ${nv("description")}`,
"\n"
template`(${nv('number')}) ${nv('name')}: ${nv('description')}`,
'\n'
);
const numberedCriteriaPoints = criteriaPoints.map((e, i) => {
return { ...e, number: `${i + 1}` };
Expand Down Expand Up @@ -67,25 +67,25 @@ describe("fewshot_template", () => {
// joining, e.g. ": " always separates the property from the value, and
// "\n" always separates different property-vcalue pairs.
const nPropertyValuePerLineTempl = new FewShotTemplate(
template`${nv("property")}: "${nv("value")}"`,
"\n"
template`${nv('property')}: "${nv('value')}"`,
'\n'
);
const movieAndRecList = [
{
property: "Movie",
value: nv("movie"),
property: 'Movie',
value: nv('movie'),
},
{
property: "Recommendation",
value: nv("recommendation"),
property: 'Recommendation',
value: nv('recommendation'),
},
];
const movieRecTempl = nPropertyValuePerLineTempl.apply(movieAndRecList);
const movieRecEvalTempl = nPropertyValuePerLineTempl.apply([
...movieAndRecList,
{
property: "Evaluation",
value: nv("evaluation"),
property: 'Evaluation',
value: nv('evaluation'),
},
]);

Expand All @@ -98,29 +98,29 @@ Evaluation: "{{evaluation}}"`
// ----------------------------------------------------------------------------
const fewShotCriticExamples = [
{
movie: "The Godfather",
recommendation: "a dark and violent story of family and power",
evaluation: "ok",
movie: 'The Godfather',
recommendation: 'a dark and violent story of family and power',
evaluation: 'ok',
},
{
movie: "The Godfather",
recommendation: "a masterpiece of cinema",
movie: 'The Godfather',
recommendation: 'a masterpiece of cinema',
evaluation:
"Specific: the recommendation is vague, it should be more precise.",
'Specific: the recommendation is vague, it should be more precise.',
},
];

const nCriticExamplesTempl = new FewShotTemplate(movieRecEvalTempl, "\n\n");
const nCriticExamplesTempl = new FewShotTemplate(movieRecEvalTempl, '\n\n');

// ----------------------------------------------------------------------------
// Templates can contain other templates inline also.
const criticTempl = template`Given the following criteria for movie recommendations:
${nv("Constitution")}
${nv('Constitution')}
Evaluate the following movie recommendations.
If the review is ok, the evaluation should just be "ok".
${nv("fewShotCriticExamples")}
${nv('fewShotCriticExamples')}
${movieRecTempl as Template<string>}
Evaluation: "`;
Expand Down Expand Up @@ -154,37 +154,37 @@ Evaluation: "`
);
});

it("parts template matching with multi-line match-string", () => {
it('parts template matching with multi-line match-string', () => {
const itemExperienceTempl = template`Short experience description: "${nv(
"experience"
'experience'
)}"
About: ${nv("aboutEntity")} (${nv("aboutDetails")})
Liked or Disliked: ${nv("likedOrDisliked")}, because:
About: ${nv('aboutEntity')} (${nv('aboutDetails')})
Liked or Disliked: ${nv('likedOrDisliked')}, because:
[
${nv("characteristics")}
${nv('characteristics')}
]`;

const t = itemExperienceTempl.substs({
experience: "The Garden of Forking Paths: like it",
experience: 'The Garden of Forking Paths: like it',
});

const parts = t.parts();
const s1 =
'The Garden of Forking Paths (short story by Jorge Luis Borges)\nLiked or Disliked: Liked, because:\n[\n "Intriguing",\n "Philosophical",\n "Thought-provoking"\n]\n\nfoo foo\n]';
const m1 = matchTemplate(parts, s1, false);
expect(m1.substs).toEqual({
aboutEntity: "The Garden of Forking Paths",
aboutDetails: "short story by Jorge Luis Borges",
likedOrDisliked: "Liked",
aboutEntity: 'The Garden of Forking Paths',
aboutDetails: 'short story by Jorge Luis Borges',
likedOrDisliked: 'Liked',
characteristics:
'"Intriguing",\n "Philosophical",\n "Thought-provoking"',
});
});

it("match fewshot template", () => {
it('match fewshot template', () => {
const templ = new FewShotTemplate(
template`(${nv("id")}) ${nv("property")}: "${nv("value")}"`,
"\n"
template`(${nv('id')}) ${nv('property')}: "${nv('value')}"`,
'\n'
);

const str = `(1) Concise: "not waffley"
Expand All @@ -194,20 +194,20 @@ Liked or Disliked: ${nv("likedOrDisliked")}, because:
const m = matchFewShotTemplate(templ, str);
expect(m.length).toEqual(3);
expect(m[0].substs).toEqual({
id: "1",
property: "Concise",
value: "not waffley",
id: '1',
property: 'Concise',
value: 'not waffley',
});
expect(m[0].curPart).toEqual(undefined);
expect(m[1].substs).toEqual({
id: "2",
property: "No synposes",
value: "do not give plot synopses",
id: '2',
property: 'No synposes',
value: 'do not give plot synopses',
});
expect(m[1].curPart).toEqual(undefined);
expect(m[2].substs).toEqual({
id: "3",
property: "Specific",
id: '3',
property: 'Specific',
value: "not vague (i.e. not 'an amazing movie.', 'a classic.')",
});
expect(m[2].curPart).toEqual(undefined);
Expand Down
10 changes: 5 additions & 5 deletions src/fewshot_template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,14 @@ const nameDescriptionTempl = new FewShotTempl(template
See the test file (.spec) for more detailed examples.
*/

import { flatten } from "underscore";
import { flatten } from 'underscore';
import {
Template,
matchTemplate,
TemplateMatch,
escapeStringInMatch,
} from "./template";
import { NamedVar } from "./variable";
} from './template';
import { NamedVar } from './variable';

// For each example substitution, substitute it into the template, and join it
// all together with the joinStr, into one big new template.
Expand All @@ -37,7 +37,7 @@ export function fewShotSubst<N extends string, M extends N, N2s extends string>(
const vars = flatten(
examples.map((e) =>
Object.values<string | NamedVar<N2s>>(e).filter(
(r) => typeof r !== "string"
(r) => typeof r !== 'string'
)
)
) as NamedVar<N2s>[];
Expand Down Expand Up @@ -77,7 +77,7 @@ export function matchFewShotTemplate<Ns extends string>(
matches.push(match);
while (
match.matchedPartsCount === match.parts.variables.length &&
match.finalStr !== ""
match.finalStr !== ''
) {
let nextStr = match.finalStr;
const sepMatch = match.finalStr.match(
Expand Down
6 changes: 3 additions & 3 deletions src/llm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
An class to wrap, and provide a common interface for LLM behaviour.
*/

import { ErrorResponse, isErrorResponse } from "./simple_errors";
import { Template, matchTemplate } from "./template";
import { ErrorResponse, isErrorResponse } from './simple_errors';
import { Template, matchTemplate } from './template';

export interface PredictResponse {
completions: string[];
Expand Down Expand Up @@ -42,7 +42,7 @@ export abstract class LLM<Params extends object> {
//
// TODO: maybe good to provide a version that takes the same query and gives difference responses each time, e.g. using a random seed at constructor time.
export class LookupTableFakeLLM implements LLM<object> {
public name: string = "fake: in memory lookup table";
public name: string = 'fake: in memory lookup table';

constructor(public table: { [query: string]: ScoreResponse }) {}

Expand Down
18 changes: 9 additions & 9 deletions src/llm_api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
/*
An class to wrap, and provide a common interface for LLM behaviour.
*/
import { LLM, PredictResponse } from "./llm";
import { ErrorResponse } from "./simple_errors";
import { LLM, PredictResponse } from './llm';
import { ErrorResponse } from './simple_errors';

export interface LlmOptions {
modelId?: string; // e.g. text-bison
Expand All @@ -28,14 +28,14 @@ async function sendLlmRequest(
): Promise<PredictResponse | ErrorResponse> {
// Default options are marked with *
const response = await fetch(`/api/llm`, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, *cors, same-origin
credentials: "same-origin", // include, *same-origin, omit
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
credentials: 'same-origin', // include, *same-origin, omit
headers: {
"Content-Type": "application/json",
'Content-Type': 'application/json',
},
redirect: "follow", // manual, *follow, error
referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(request), // body data type must match "Content-Type" header
});
console.log(response);
Expand All @@ -48,7 +48,7 @@ async function sendLlmRequest(
try {
prediction = (await response.json()) as PredictResponse;
} catch (err) {
console.error("invalid json in response.body: ", response.body);
console.error('invalid json in response.body: ', response.body);
return {
error: `response is not valid JSON.`,
};
Expand Down
36 changes: 18 additions & 18 deletions src/llm_vertexapi_gemini_lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,29 +70,29 @@ export type GeminiApiSystemInstruction = Partial<{
}>;

export type GeminiApiRequestContent = {
role: "user" | "model";
role: 'user' | 'model';
parts: GeminiContentPart[];
};

export enum HarmCategory {
HARM_CATEGORY_SEXUALLY_EXPLICIT = "HARM_CATEGORY_SEXUALLY_EXPLICIT",
HARM_CATEGORY_HATE_SPEECH = "HARM_CATEGORY_HATE_SPEECH",
HARM_CATEGORY_HARASSMENT = "HARM_CATEGORY_HARASSMENT",
HARM_CATEGORY_DANGEROUS_CONTENT = "HARM_CATEGORY_DANGEROUS_CONTENT",
HARM_CATEGORY_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
HARM_CATEGORY_HATE_SPEECH = 'HARM_CATEGORY_HATE_SPEECH',
HARM_CATEGORY_HARASSMENT = 'HARM_CATEGORY_HARASSMENT',
HARM_CATEGORY_DANGEROUS_CONTENT = 'HARM_CATEGORY_DANGEROUS_CONTENT',
}

export enum HarmBlockThreshold {
OFF = "OFF",
BLOCK_NONE = "BLOCK_NONE",
BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE",
BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE",
BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH",
OFF = 'OFF',
BLOCK_NONE = 'BLOCK_NONE',
BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',
BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',
BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',
}

export enum HarmBlockMethod {
HARM_BLOCK_METHOD_UNSPECIFIED = "HARM_BLOCK_METHOD_UNSPECIFIED",
SEVERITY = "SEVERITY",
PROBABILITY = "PROBABILITY",
HARM_BLOCK_METHOD_UNSPECIFIED = 'HARM_BLOCK_METHOD_UNSPECIFIED',
SEVERITY = 'SEVERITY',
PROBABILITY = 'PROBABILITY',
}

export type GeminiApiRequestSafetySettings = {
Expand All @@ -119,10 +119,10 @@ export type GeminiApiRequest = {
export interface GeminiValidResponse {
candidates: {
content: {
role: "model";
role: 'model';
parts: GeminiContentPart[];
};
finishReason: "STOP";
finishReason: 'STOP';
avgLogprobs: number;
}[];
usageMetadata: {
Expand Down Expand Up @@ -155,8 +155,8 @@ export interface GeminiApiOptions {
}

export const DEFAULT_OPTIONS: GeminiApiOptions = {
modelId: "gemini-1.5-flash-002",
location: "us-central1",
modelId: 'gemini-1.5-flash-002',
location: 'us-central1',
};

// ----------------------------------------------------------------------------
Expand All @@ -171,7 +171,7 @@ export function prepareGeminiRequest(
...params,
contents: [
{
role: "user",
role: 'user',
parts: [{ text: query }],
},
],
Expand Down
Loading

0 comments on commit aba9cbe

Please sign in to comment.