Skip to content

Commit

Permalink
Formatted assistant-lib src
Browse files Browse the repository at this point in the history
  • Loading branch information
bdb-dd committed Mar 7, 2024
1 parent 3699d94 commit 3db6506
Show file tree
Hide file tree
Showing 12 changed files with 517 additions and 468 deletions.
44 changes: 24 additions & 20 deletions packages/assistant-lib/package.json
Original file line number Diff line number Diff line change
@@ -1,22 +1,26 @@
{
"name": "@digdir/assistant-lib",
"private": true,
"version": "1.0.0",
"description": "Core assistant library",
"main": "dist/src/index.js",
"license": "MIT",
"dependencies": {
"@azure/openai": "^1.0.0-beta.11",
"@instructor-ai/instructor": "^0.0.7",
"@supabase/supabase-js": "^2.39.7",
"axios": "^1.6.7",
"dataclass": "^2.1.1",
"js-yaml": "^4.1.0",
"lodash": "^4.17.21",
"openai": "^4.28.0",
"remeda": "^1.44.1",
"typesense": "^1.7.2",
"zod": "^3.22.4",
"zod-to-json-schema": "^3.22.4"
}
"name": "@digdir/assistant-lib",
"private": true,
"version": "1.0.0",
"description": "Core assistant library",
"main": "dist/src/index.js",
"license": "MIT",
"scripts": {
"codestyle:check": "prettier src/ --check",
"codestyle:fix": "prettier src/ --write"
},
"dependencies": {
"@azure/openai": "^1.0.0-beta.11",
"@instructor-ai/instructor": "^0.0.7",
"@supabase/supabase-js": "^2.39.7",
"axios": "^1.6.7",
"dataclass": "^2.1.1",
"js-yaml": "^4.1.0",
"lodash": "^4.17.21",
"openai": "^4.28.0",
"remeda": "^1.44.1",
"typesense": "^1.7.2",
"zod": "^3.22.4",
"zod-to-json-schema": "^3.22.4"
}
}
53 changes: 27 additions & 26 deletions packages/assistant-lib/src/config/typesense.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,35 @@
import { envVar } from '../general';

import { envVar } from "../general";

type TypesenseNodeConfig = {
host: string;
port: number;
protocol: string;
host: string;
port: number;
protocol: string;
};

type TypesenseServiceConfig = {
nodes: TypesenseNodeConfig[]
connectionTimeoutSec: number;
apiKey: string;
docsCollection: string;
docsSearchPhraseCollection: string;
nodes: TypesenseNodeConfig[];
connectionTimeoutSec: number;
apiKey: string;
docsCollection: string;
docsSearchPhraseCollection: string;
};


export function typesenseConfig(): TypesenseServiceConfig {


const cfg: TypesenseServiceConfig = {
nodes: [{
host: envVar("TYPESENSE_API_HOST"),
port: 443, protocol: "https"
}],
apiKey: envVar("TYPESENSE_API_KEY"),
docsCollection: envVar("TYPESENSE_DOCS_COLLECTION"),
docsSearchPhraseCollection: envVar("TYPESENSE_DOCS_SEARCH_PHRASE_COLLECTION"),
connectionTimeoutSec: 2
}

return cfg;
}
const cfg: TypesenseServiceConfig = {
nodes: [
{
host: envVar("TYPESENSE_API_HOST"),
port: 443,
protocol: "https",
},
],
apiKey: envVar("TYPESENSE_API_KEY"),
docsCollection: envVar("TYPESENSE_DOCS_COLLECTION"),
docsSearchPhraseCollection: envVar(
"TYPESENSE_DOCS_SEARCH_PHRASE_COLLECTION",
),
connectionTimeoutSec: 2,
};

return cfg;
}
2 changes: 1 addition & 1 deletion packages/assistant-lib/src/docs/analysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ const UserQueryAnalysisSchema = z.object({
export type UserQueryAnalysis = z.infer<typeof UserQueryAnalysisSchema> | null;

export async function userInputAnalysis(
userInput: string
userInput: string,
): Promise<UserQueryAnalysis> {
let queryResult: UserQueryAnalysis | null = null;

Expand Down
27 changes: 14 additions & 13 deletions packages/assistant-lib/src/docs/prompts.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@

export const stage1_analyze_query: string =
`You are a skilled customer service agent with many years experience evaluating incoming support requests related to Altinn, a data collection system for government agencies.
export const stage1_analyze_query: string = `You are a skilled customer service agent with many years experience evaluating incoming support requests related to Altinn, a data collection system for government agencies.
1. If the question is not in English, first translate to English.
Expand All @@ -19,28 +17,31 @@ Information about a Github pull request, also called a PR
Catch all category if none of the above categories matches well.
3. Finally, return the category, original language code and name.
`
`;

export function qaTemplate() {
const translate_hint = '\nOnly return the helpful answer below, along with relevant source code examples when possible.\n'
const translate_hint =
"\nOnly return the helpful answer below, along with relevant source code examples when possible.\n";

const prompt_text = `Use the following pieces of information to answer the user's question.
const prompt_text =
`Use the following pieces of information to answer the user's question.
If you don't know the answer, just say that you don't know, don't try to make up an answer.
Context: {context}
Question: {question}
` + translate_hint + "\nHelpful answer:\n"

console.log(`Prompt text:\n${prompt_text}`)
return prompt_text
` +
translate_hint +
"\nHelpful answer:\n";

console.log(`Prompt text:\n${prompt_text}`);
return prompt_text;
}

export const generate_search_phrases_template =
`Please analyze the contents of the following documentation article and generate a list of English phrases that you would expect to match the following document.
export const generate_search_phrases_template = `Please analyze the contents of the following documentation article and generate a list of English phrases that you would expect to match the following document.
DO NOT include the phrases "Altinn Studio", "Altinn 3" or "Altinn apps".
Document:
{document}
`
`;
113 changes: 61 additions & 52 deletions packages/assistant-lib/src/docs/query-relaxation.ts
Original file line number Diff line number Diff line change
@@ -1,75 +1,84 @@
import Instructor from '@instructor-ai/instructor';
import { z } from 'zod';
import Instructor from "@instructor-ai/instructor";
import { z } from "zod";
import {
// azure_client,
openaiClient
} from '../llm';
import { scopedEnvVar } from '../general';
// azure_client,
openaiClient,
} from "../llm";
import { scopedEnvVar } from "../general";

const stage_name = 'DOCS_QA_EXTRACT';
const stage_name = "DOCS_QA_EXTRACT";
const envVar = scopedEnvVar(stage_name);

// const azureClient = azure_client();
const openaiClientInstance = Instructor({
client: openaiClient() as any,
mode: "FUNCTIONS",
debug: envVar('DEBUG_INSTRUCTOR')
client: openaiClient() as any,
mode: "FUNCTIONS",
debug: envVar("DEBUG_INSTRUCTOR"),
});

const QueryRelaxationSchema = z.object({
searchQueries: z.array(z.string())
searchQueries: z.array(z.string()),
});

export type QueryRelaxation = z.infer<typeof QueryRelaxationSchema> | null;

export async function queryRelaxation(user_input: string): Promise<QueryRelaxation> {
let query_result: QueryRelaxation | null = null;
export async function queryRelaxation(
user_input: string,
): Promise<QueryRelaxation> {
let query_result: QueryRelaxation | null = null;

const prompt = `You have access to a search API that returns relevant documentation.
const prompt = `You have access to a search API that returns relevant documentation.
Your task is to generate an array of up to 7 search queries that are relevant to this question.
Use a variation of related keywords and synonyms for the queries, trying to be as general as possible.
Include as many queries as you can think of, including and excluding terms.
For example, include queries like ['keyword_1 keyword_2', 'keyword_1', 'keyword_2'].
Be creative. The more queries you include, the more likely you are to find relevant results.`
Be creative. The more queries you include, the more likely you are to find relevant results.`;

if (envVar('USE_AZURE_OPENAI_API', false) == true) {
// query_result = await azureClient.chat.completions.create({
// model: envVar('AZURE_OPENAI_DEPLOYMENT'),
// response_model: { schema: SearchQueriesSchema, name: "GeneratedSearchQueries" },
// temperature: 0.1,
// max_retries: 0,
// messages: [
// {
// role: "system",
// content: prompt },
// { role: "user", content: "[User query]\n" + user_input },
// ]
// });
} else {
console.log(`${stage_name} model name: ${envVar('OPENAI_API_MODEL_NAME', "")}`);
query_result = await openaiClientInstance.chat.completions.create({
model: envVar('OPENAI_API_MODEL_NAME'),
response_model: { schema: QueryRelaxationSchema, name: "QueryRelaxation" },
temperature: 0.1,
max_retries: 0,
messages: [
{
role: "system",
content: prompt
},
{ role: "user", content: "[User query]\n" + user_input },
]
});
}
if (envVar("USE_AZURE_OPENAI_API", false) == true) {
// query_result = await azureClient.chat.completions.create({
// model: envVar('AZURE_OPENAI_DEPLOYMENT'),
// response_model: { schema: SearchQueriesSchema, name: "GeneratedSearchQueries" },
// temperature: 0.1,
// max_retries: 0,
// messages: [
// {
// role: "system",
// content: prompt },
// { role: "user", content: "[User query]\n" + user_input },
// ]
// });
} else {
console.log(
`${stage_name} model name: ${envVar("OPENAI_API_MODEL_NAME", "")}`,
);
query_result = await openaiClientInstance.chat.completions.create({
model: envVar("OPENAI_API_MODEL_NAME"),
response_model: {
schema: QueryRelaxationSchema,
name: "QueryRelaxation",
},
temperature: 0.1,
max_retries: 0,
messages: [
{
role: "system",
content: prompt,
},
{ role: "user", content: "[User query]\n" + user_input },
],
});
}

if (!query_result) {
return null
}
if (!query_result) {
return null;
}

for (let i = 0; i < query_result.searchQueries.length; i++) {
query_result.searchQueries[i] = query_result.searchQueries[i].replace("GitHub", "").trim();
}
for (let i = 0; i < query_result.searchQueries.length; i++) {
query_result.searchQueries[i] = query_result.searchQueries[i]
.replace("GitHub", "")
.trim();
}

return query_result;
}
return query_result;
}
Loading

0 comments on commit 3db6506

Please sign in to comment.