Skip to content

simplify questions asked #370

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Oct 14, 2024
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion helpers/providers/anthropic.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import ciInfo from "ci-info";
import prompts from "prompts";
import { ModelConfigParams } from ".";
import { questionHandlers, toChoice } from "../../questions";
import { questionHandlers, toChoice } from "../../questions/utils";

const MODELS = [
"claude-3-opus",
Expand Down
2 changes: 1 addition & 1 deletion helpers/providers/azure.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import ciInfo from "ci-info";
import prompts from "prompts";
import { ModelConfigParams, ModelConfigQuestionsParams } from ".";
import { questionHandlers } from "../../questions";
import { questionHandlers } from "../../questions/utils";

const ALL_AZURE_OPENAI_CHAT_MODELS: Record<string, { openAIModel: string }> = {
"gpt-35-turbo": { openAIModel: "gpt-3.5-turbo" },
Expand Down
2 changes: 1 addition & 1 deletion helpers/providers/gemini.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import ciInfo from "ci-info";
import prompts from "prompts";
import { ModelConfigParams } from ".";
import { questionHandlers, toChoice } from "../../questions";
import { questionHandlers, toChoice } from "../../questions/utils";
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Import Verification Failed

The toChoice function was not found in the specified path ../../questions/utils. Please ensure that the function is correctly exported from questions/utils.ts or update the import path accordingly.

🔗 Analysis chain

LGTM! Verify the new import path.

The import statement has been updated to a more specific path, which is a good practice for better code organization. This change should improve the modularity of the codebase.

Let's verify that the imported functions exist in the new location:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that questionHandlers and toChoice are correctly defined in the new location.

# Test: Check if the functions are defined in the new utils file
ast-grep --lang typescript --pattern 'export const questionHandlers = $_' questions/utils.ts
ast-grep --lang typescript --pattern 'export function toChoice($_) { $$$ }' questions/utils.ts

Length of output: 443


const MODELS = ["gemini-1.5-pro-latest", "gemini-pro", "gemini-pro-vision"];
type ModelData = {
Expand Down
2 changes: 1 addition & 1 deletion helpers/providers/groq.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import ciInfo from "ci-info";
import prompts from "prompts";
import { ModelConfigParams } from ".";
import { questionHandlers, toChoice } from "../../questions";
import { questionHandlers, toChoice } from "../../questions/utils";

import got from "got";
import ora from "ora";
Expand Down
5 changes: 2 additions & 3 deletions helpers/providers/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import ciInfo from "ci-info";
import prompts from "prompts";
import { questionHandlers } from "../../questions";
import { questionHandlers } from "../../questions/utils";
import { ModelConfig, ModelProvider, TemplateFramework } from "../types";
import { askAnthropicQuestions } from "./anthropic";
import { askAzureQuestions } from "./azure";
Expand All @@ -27,7 +26,7 @@ export async function askModelConfig({
framework,
}: ModelConfigQuestionsParams): Promise<ModelConfig> {
let modelProvider: ModelProvider = DEFAULT_MODEL_PROVIDER;
if (askModels && !ciInfo.isCI) {
if (askModels) {
let choices = [
{ title: "OpenAI", value: "openai" },
{ title: "Groq", value: "groq" },
Expand Down
2 changes: 1 addition & 1 deletion helpers/providers/llmhub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import ora from "ora";
import { red } from "picocolors";
import prompts from "prompts";
import { ModelConfigParams } from ".";
import { questionHandlers } from "../../questions";
import { questionHandlers } from "../../questions/utils";

export const TSYSTEMS_LLMHUB_API_URL =
"https://llm-server.llmhub.t-systems.net/v2";
Expand Down
2 changes: 1 addition & 1 deletion helpers/providers/mistral.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import ciInfo from "ci-info";
import prompts from "prompts";
import { ModelConfigParams } from ".";
import { questionHandlers, toChoice } from "../../questions";
import { questionHandlers, toChoice } from "../../questions/utils";

const MODELS = ["mistral-tiny", "mistral-small", "mistral-medium"];
type ModelData = {
Expand Down
2 changes: 1 addition & 1 deletion helpers/providers/ollama.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import ollama, { type ModelResponse } from "ollama";
import { red } from "picocolors";
import prompts from "prompts";
import { ModelConfigParams } from ".";
import { questionHandlers, toChoice } from "../../questions";
import { questionHandlers, toChoice } from "../../questions/utils";

type ModelData = {
dimensions: number;
Expand Down
2 changes: 1 addition & 1 deletion helpers/providers/openai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import ora from "ora";
import { red } from "picocolors";
import prompts from "prompts";
import { ModelConfigParams, ModelConfigQuestionsParams } from ".";
import { questionHandlers } from "../../questions";
import { questionHandlers } from "../../questions/utils";

const OPENAI_API_URL = "https://api.openai.com/v1";

Expand Down
137 changes: 56 additions & 81 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/* eslint-disable import/no-extraneous-dependencies */
import { execSync } from "child_process";
import Commander from "commander";
import Conf from "conf";
import { Command } from "commander";
import fs from "fs";
import path from "path";
import { bold, cyan, green, red, yellow } from "picocolors";
Expand All @@ -17,8 +16,9 @@ import { runApp } from "./helpers/run-app";
import { getTools } from "./helpers/tools";
import { validateNpmName } from "./helpers/validate-pkg";
import packageJson from "./package.json";
import { QuestionArgs, askQuestions, onPromptState } from "./questions";

import { askQuestions } from "./questions/index";
import { QuestionArgs } from "./questions/types";
import { onPromptState } from "./questions/utils";
// Run the initialization function
initializeGlobalAgent();

Expand All @@ -29,12 +29,14 @@ const handleSigTerm = () => process.exit(0);
process.on("SIGINT", handleSigTerm);
process.on("SIGTERM", handleSigTerm);

const program = new Commander.Command(packageJson.name)
const program = new Command(packageJson.name)
.version(packageJson.version)
.arguments("<project-directory>")
.usage(`${green("<project-directory>")} [options]`)
.arguments("[project-directory]")
.usage(`${green("[project-directory]")} [options]`)
.action((name) => {
projectPath = name;
if (name) {
projectPath = name;
}
})
.option(
"--use-npm",
Expand All @@ -55,13 +57,6 @@ const program = new Commander.Command(packageJson.name)
`

Explicitly tell the CLI to bootstrap the application using Yarn
`,
)
.option(
"--reset-preferences",
`

Explicitly tell the CLI to reset any stored preferences
`,
)
.option(
Expand Down Expand Up @@ -124,7 +119,14 @@ const program = new Commander.Command(packageJson.name)
"--frontend",
`

Whether to generate a frontend for your backend.
Generate a frontend for your backend.
`,
)
.option(
"--no-frontend",
`

Do not generate a frontend for your backend.
Comment on lines +122 to +129
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Approve new frontend options, but fix formatting.

The addition of --frontend and --no-frontend options provides users with more control over frontend generation, which is a good improvement. However, the formatting of these options is inconsistent with other options in the file.

Please apply the following diff to correct the formatting:

 .option(
     "--frontend",
-    `
-  Generate a frontend for your backend.
-`,
+    `
+
+  Generate a frontend for your backend.
+`
 )
 .option(
     "--no-frontend",
-    `
-
-  Do not generate a frontend for your backend.
-`,
+    `
+
+  Do not generate a frontend for your backend.
+`
 )

This adjustment ensures that the option descriptions are properly formatted and consistent with other options.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Generate a frontend for your backend.
`,
)
.option(
"--no-frontend",
`
Do not generate a frontend for your backend.
.option(
"--frontend",
`
Generate a frontend for your backend.
`
)
.option(
"--no-frontend",
`
Do not generate a frontend for your backend.
`
)

`,
)
.option(
Expand Down Expand Up @@ -161,6 +163,13 @@ const program = new Commander.Command(packageJson.name)

Specify the tools you want to use by providing a comma-separated list. For example, 'wikipedia.WikipediaToolSpec,google.GoogleSearchToolSpec'. Use 'none' to not using any tools.
`,
(tools, _) => {
if (tools === "none") {
return [];
} else {
return getTools(tools.split(","));
}
},
)
.option(
"--use-llama-parse",
Expand Down Expand Up @@ -189,86 +198,71 @@ const program = new Commander.Command(packageJson.name)

Allow interactive selection of LLM and embedding models of different model providers.
`,
false,
)
.option(
"--ask-examples",
"--pro",
`

Allow interactive selection of community templates and LlamaPacks.
Allow interactive selection of all features.
`,
false,
)
.allowUnknownOption()
.parse(process.argv);
if (process.argv.includes("--no-frontend")) {
program.frontend = false;
}
if (process.argv.includes("--tools")) {
if (program.tools === "none") {
program.tools = [];
} else {
program.tools = getTools(program.tools.split(","));
}
}

const options = program.opts();

if (
process.argv.includes("--no-llama-parse") ||
program.template === "extractor"
options.template === "extractor"
) {
program.useLlamaParse = false;
options.useLlamaParse = false;
}
program.askModels = process.argv.includes("--ask-models");
program.askExamples = process.argv.includes("--ask-examples");
if (process.argv.includes("--no-files")) {
program.dataSources = [];
options.dataSources = [];
} else if (process.argv.includes("--example-file")) {
program.dataSources = getDataSources(program.files, program.exampleFile);
options.dataSources = getDataSources(options.files, options.exampleFile);
} else if (process.argv.includes("--llamacloud")) {
program.dataSources = [
options.dataSources = [
{
type: "llamacloud",
config: {},
},
EXAMPLE_FILE,
];
} else if (process.argv.includes("--web-source")) {
program.dataSources = [
options.dataSources = [
{
type: "web",
config: {
baseUrl: program.webSource,
prefix: program.webSource,
baseUrl: options.webSource,
prefix: options.webSource,
depth: 1,
},
},
];
} else if (process.argv.includes("--db-source")) {
program.dataSources = [
options.dataSources = [
{
type: "db",
config: {
uri: program.dbSource,
queries: program.dbQuery || "SELECT * FROM mytable",
uri: options.dbSource,
queries: options.dbQuery || "SELECT * FROM mytable",
},
},
];
}

const packageManager = !!program.useNpm
const packageManager = !!options.useNpm
? "npm"
: !!program.usePnpm
: !!options.usePnpm
? "pnpm"
: !!program.useYarn
: !!options.useYarn
Comment on lines +252 to +256
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Simplify package manager detection logic.

The current implementation uses unnecessary double negation operators. These can be safely removed to improve code clarity without changing the functionality.

Apply the following diff to simplify the package manager detection:

-const packageManager = !!options.useNpm
+const packageManager = options.useNpm
   ? "npm"
-  : !!options.usePnpm
+  : options.usePnpm
     ? "pnpm"
-    : !!options.useYarn
+    : options.useYarn
       ? "yarn"
       : getPkgManager();

This change aligns with the static analysis suggestions and makes the code more straightforward.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const packageManager = !!options.useNpm
? "npm"
: !!program.usePnpm
: !!options.usePnpm
? "pnpm"
: !!program.useYarn
: !!options.useYarn
const packageManager = options.useNpm
? "npm"
: options.usePnpm
? "pnpm"
: options.useYarn
? "yarn"
: getPkgManager();
🧰 Tools
🪛 Biome

[error] 252-252: Avoid redundant double-negation.

It is not necessary to use double-negation when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant double-negation

(lint/complexity/noExtraBooleanCast)


[error] 254-254: Avoid redundant double-negation.

It is not necessary to use double-negation when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant double-negation

(lint/complexity/noExtraBooleanCast)


[error] 256-256: Avoid redundant double-negation.

It is not necessary to use double-negation when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant double-negation

(lint/complexity/noExtraBooleanCast)

? "yarn"
: getPkgManager();

async function run(): Promise<void> {
const conf = new Conf({ projectName: "create-llama" });

if (program.resetPreferences) {
conf.clear();
console.log(`Preferences reset successfully`);
return;
}

if (typeof projectPath === "string") {
projectPath = projectPath.trim();
}
Expand Down Expand Up @@ -331,35 +325,16 @@ async function run(): Promise<void> {
process.exit(1);
}

const preferences = (conf.get("preferences") || {}) as QuestionArgs;
await askQuestions(
program as unknown as QuestionArgs,
preferences,
program.openAiKey,
);
const answers = await askQuestions(options as unknown as QuestionArgs);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Improve type safety in askQuestions function call.

The current implementation uses type casting, which could potentially hide type mismatches and reduce type safety.

Consider refactoring this to avoid the use of type casting. Here are a couple of approaches:

  1. Ensure that options conforms to the QuestionArgs interface:
const questionArgs: QuestionArgs = {
  // Map relevant properties from options to QuestionArgs
};
const answers = await askQuestions(questionArgs);
  1. Update the askQuestions function to accept a more general type that includes all properties of options:
function askQuestions(options: Partial<QuestionArgs> & Record<string, unknown>): Promise<Answers> {
  // Implementation
}

const answers = await askQuestions(options);

These approaches would maintain type safety and make the code more robust.


await createApp({
template: program.template,
framework: program.framework,
ui: program.ui,
...answers,
appPath: resolvedProjectPath,
packageManager,
frontend: program.frontend,
modelConfig: program.modelConfig,
llamaCloudKey: program.llamaCloudKey,
communityProjectConfig: program.communityProjectConfig,
llamapack: program.llamapack,
vectorDb: program.vectorDb,
externalPort: program.externalPort,
postInstallAction: program.postInstallAction,
dataSources: program.dataSources,
tools: program.tools,
useLlamaParse: program.useLlamaParse,
observability: program.observability,
externalPort: options.externalPort,
});
conf.set("preferences", preferences);

if (program.postInstallAction === "VSCode") {
if (answers.postInstallAction === "VSCode") {
console.log(`Starting VSCode in ${root}...`);
try {
execSync(`code . --new-window --goto README.md`, {
Expand All @@ -383,15 +358,15 @@ Please check ${cyan(
)} for more information.`,
);
}
} else if (program.postInstallAction === "runApp") {
} else if (answers.postInstallAction === "runApp") {
console.log(`Running app in ${root}...`);
await runApp(
root,
program.template,
program.frontend,
program.framework,
program.port,
program.externalPort,
answers.template,
answers.frontend,
answers.framework,
options.port,
options.externalPort,
);
}
}
Expand Down
5 changes: 2 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,7 @@
"async-retry": "1.3.1",
"async-sema": "3.0.1",
"ci-info": "github:watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540",
"commander": "2.20.0",
"conf": "10.2.0",
"commander": "12.1.0",
"cross-spawn": "7.0.3",
"fast-glob": "3.3.1",
"fs-extra": "11.2.0",
Expand All @@ -59,7 +58,7 @@
"ollama": "^0.5.0",
"ora": "^8.0.1",
"picocolors": "1.0.0",
"prompts": "2.1.0",
"prompts": "2.4.2",
"smol-toml": "^1.1.4",
"tar": "6.1.15",
"terminal-link": "^3.0.0",
Expand Down
Loading
Loading