### Docker Compose for Xpert AI Server Setup Source: https://github.com/xpert-ai/xpert/blob/main/README.md This snippet demonstrates the steps to start the Xpert server using Docker Compose. It requires Docker and Docker Compose to be installed. The commands involve navigating to the docker directory, copying an environment file, and starting the services in detached mode. ```bash cd xpert cd docker cp .env.example .env docker compose up -d ``` -------------------------------- ### Deploy Xpert AI with Docker Compose (Bash) Source: https://context7.com/xpert-ai/xpert/llms.txt Provides a step-by-step guide to deploy the Xpert AI platform using Docker Compose. It includes cloning the repository, configuring environment variables in a .env file, starting services, checking status, viewing logs, and managing the service lifecycle (up, down, down -v). ```bash # docker-compose.yml deployment # Start all services with docker compose # 1. Clone the repository git clone https://github.com/xpert-ai/xpert.git cd xpert # 2. Navigate to docker directory cd docker # 3. Copy environment template cp .env.example .env # 4. Edit environment variables nano .env # Set the following variables: # NODE_ENV=production # API_BASE_URL=http://localhost:3000 # CLIENT_BASE_URL=http://localhost # DB_HOST=db # DB_PORT=5432 # DB_NAME=xpert_db # DB_USER=postgres # DB_PASS=secure_password_here # REDIS_HOST=redis # REDIS_PORT=6379 # 5. Start services docker compose up -d # 6. Check service status docker compose ps # 7. View logs docker compose logs -f api # 8. Initialize the platform # Visit http://localhost/onboarding in your browser # 9. Stop services docker compose down # 10. Stop and remove volumes docker compose down -v ``` -------------------------------- ### Start XpertAI Docker Compose with BI Profile Source: https://github.com/xpert-ai/xpert/blob/main/docker/README.md This command starts the XpertAI Docker containers using the 'bi' profile, enabling multidimensional modeling capabilities. It is used when advanced data analysis features are required. The service runs in detached mode. ```bash docker compose --profile bi up -d ``` -------------------------------- ### Render Filtered Commands with Aliases and Examples Source: https://github.com/xpert-ai/xpert/blob/main/packages/copilot-angular/src/lib/chat/chat.component.html Lists available commands that match filters, including their names, aliases, examples, or descriptions. This helps users discover and use available commands. ```html @for (command of filteredCommands(); track command.prompt) {* /{{command.name}} @if (command.alias) { /{{command.alias}} } @if (command.example) { {{command.example}} } @else { {{command.description}} } } ``` -------------------------------- ### Start XpertAI Docker Compose Services Source: https://github.com/xpert-ai/xpert/blob/main/docker/README.md Standard command to bring up all XpertAI services defined in the docker-compose.yml file in detached mode. This is the primary method for launching the application environment. ```bash docker compose up -d ``` -------------------------------- ### Install Metad Copilot Core Package Source: https://github.com/xpert-ai/xpert/blob/main/packages/copilot/README.md Installs the general-purpose abstract core logic package for developing AI Copilot applications using npm. ```bash npm install @metad/copilot ``` -------------------------------- ### Show Current GitHub Installation Details Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/@shared/xp-project/github-installation/installation.component.html This code block displays the current GitHub user or organization's details, including their avatar and name. It conditionally renders the avatar image and account name if a current installation is detected and processed. ```nunjucks @if (currentInstallation(); as currentInstallation) { ![{{ currentInstallation.accountName + ' avatar'}}]({{currentInstallation.avatarUrl}}) #### {{currentInstallation.accountName}} @if (currentInstallation.accountType === "Organization") { Organization } @else { Personal } repositories accessible } ``` -------------------------------- ### Install Metad Copilot Angular UI Package Source: https://github.com/xpert-ai/xpert/blob/main/packages/copilot/README.md Installs the UI component library for Angular, which includes the Copilot chat UI component, via npm. ```bash npm install @metad/ocap-angular ``` -------------------------------- ### Navigation and Next Steps (Angular) Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/features/xpert/knowledge/knowledgebase/documents/step-3/step.component.html This snippet provides navigation links and descriptive text for guiding users on what to do after documents have been embedded. It includes links to 'Goto documents' and 'Goto workspace', along with a description explaining how the knowledgebase can be utilized by digital expert agents. ```html {{'PAC.Knowledgebase.GotoDocuments' | translate: {Default: 'Goto documents'}}}} {{ 'PAC.Knowledgebase.WhatDoNext' | translate: {Default: 'What to do next'} }} {{ 'PAC.Knowledgebase.DoNextDesc' | translate: {Default: 'Once the documents have been embedded, the knowledgebase can be added to the digital expert agents for use as context.'} }} {{ 'PAC.Knowledgebase.GotoWorkspace' | translate: {Default: 'Goto workspace'} }} ``` -------------------------------- ### GET /api/xpert-agent/middlewares Source: https://context7.com/xpert-ai/xpert/llms.txt Retrieves a list of available agent middleware strategies. ```APIDOC ## GET /api/xpert-agent/middlewares ### Description Retrieves a list of available agent middleware strategies for tool integration and execution control. ### Method GET ### Endpoint `/api/xpert-agent/middlewares` ### Parameters None ### Response #### Success Response (200) - **strategies** (array) - A list of available middleware strategies. #### Response Example ```json [ "github", "slack", "jira" ] ``` ``` -------------------------------- ### Restore Postgres Data into New Container Source: https://github.com/xpert-ai/xpert/blob/main/docker/README.md After starting a new Postgres service (e.g., pg15), this command restores data from a backup file into the 'ocap' database. It only imports data, disabling triggers during the process to optimize restoration. The backup file must be placed in the correct volume directory before execution. ```bash pg_restore -U postgres -d ocap --data-only --disable-triggers /var/lib/postgresql/data/pg12_backup.dump ``` -------------------------------- ### Customize Copilot Command for Suggestion Links (TypeScript) Source: https://github.com/xpert-ai/xpert/blob/main/packages/copilot/README.md This snippet shows how to customize a Copilot command, named 'help' in this example, to provide suggestion links. It defines the command's name, description, examples, and actions, including argument annotations for defining the structure of suggestion links (title and URL). The implementation sets these links. ```typescript const #askCommand = injectCopilotCommand({ name: 'help', description: 'Help', examples: [ 'Show helps for angular', 'Show helps for react', 'Show helps for vue', ], actions: [ injectMakeCopilotActionable({ name: 'show-help', description: 'Show helps', argumentAnnotations: [ { name: 'helps', description: 'Helps for the commands', type: 'array', items: { type: 'object', properties: { title: { type: 'string', description: 'The title of help link', }, link: { type: 'string', description: 'The url of help link', }, }, } as any, required: true, }, ], implementation: async (helps: Link[]) => { this.helps.set(helps) return `Command finish!` }, }), ], }); ``` -------------------------------- ### Conditional Rendering: Point Key Check Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/features/story/point/point.component.html A basic conditional rendering example that checks for the presence of a 'pointKey'. If 'pointKey()' returns a falsy value, an empty block is rendered. This is often used for initial state checks or feature flags. ```html @if (!pointKey()) { } ``` -------------------------------- ### Manage Agent Middleware Strategies (TypeScript) Source: https://context7.com/xpert-ai/xpert/llms.txt Manages agent middleware strategies by retrieving available strategies and fetching tools for a specific provider (e.g., GitHub). It makes GET and POST requests to the /api/xpert-agent/middlewares and /api/xpert-agent/middlewares/:provider/tools endpoints, respectively. Requires 'axios' and environment variables for authentication. ```typescript // GET /api/xpert-agent/middlewares // POST /api/xpert-agent/middlewares/:provider/tools const manageMiddlewares = async () => { try { // Get available middleware strategies const strategies = await axios.get( 'http://localhost:3000/api/xpert-agent/middlewares', { headers: { 'Authorization': 'Bearer YOUR_JWT_TOKEN' } } ); console.log('Available middleware strategies:', strategies.data); // Get tools for a specific middleware provider const tools = await axios.post( 'http://localhost:3000/api/xpert-agent/middlewares/github/tools', { config: { accessToken: process.env.GITHUB_TOKEN, repository: 'owner/repo' } }, { headers: { 'Authorization': 'Bearer YOUR_JWT_TOKEN' } } ); console.log('GitHub middleware tools:', tools.data); return { strategies: strategies.data, githubTools: tools.data }; } catch (error) { console.error('Middleware operation failed:', error.response?.data || error.message); throw error; } }; ``` -------------------------------- ### Control Run Start/Stop in Xpert AI Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/features/xpert/studio/panel/workflow/code-test/code.component.html Provides a button to start a run and conditionally displays a 'Stop' button if the system is currently loading. Assumes 'loading()' and 'error()' functions/observables control the UI state. ```html {{ 'PAC.Xpert.StartRun' | translate: {Default: 'Start run'} }} @if (loading()) { {{ 'PAC.Xpert.Stop' | translate: { Default: 'Stop' } }} } ``` -------------------------------- ### Expose Local Service with ngrok Source: https://github.com/xpert-ai/xpert/blob/main/packages/server/src/integration/README.md This command uses ngrok to forward external HTTP requests to a local service running on port 3000. ngrok creates a public HTTPS URL that can be used by integration providers to send webhooks or API callbacks to your local development environment. Ensure ngrok is installed and configured. ```bash ngrok http http://localhost:3000 ``` -------------------------------- ### Handling Empty State and Navigation Prompt Source: https://github.com/xpert-ai/xpert/blob/main/libs/apps/indicator-market/src/lib/indicator-market.component.html This snippet illustrates how to display a message and prompt for user action when a particular state is empty. It includes a shopping cart icon and translated text guiding the user to a specific market to apply permissions. ```html @if (isEmpty()) { 🛒 {{ 'IndicatorApp.Empty' | translate: {Default: 'Empty'} }}, {{ 'IndicatorApp.Goto' | translate: {Default: 'Please go to'} }} {{ 'IndicatorApp.IndicatorMarket' | translate: {Default: 'Indicator Market'} }} {{ 'IndicatorApp.ApplyIndicatorPermission' | translate: {Default: 'apply indicator permission'} }} } ``` -------------------------------- ### Retrieve Copilot Statistics (TypeScript) Source: https://context7.com/xpert-ai/xpert/llms.txt Fetches copilot analytics including token costs, daily messages, and user satisfaction rates within a specified date range. Uses `axios` to make multiple concurrent GET requests. Requires start and end dates. ```typescript // GET /api/copilot/statistics/token-costs?start=2024-01-01&end=2024-01-31 // Get token usage and cost statistics const getCopilotStatistics = async (startDate, endDate) => { try { const [ tokenCosts, dailyMessages, userSatisfaction ] = await Promise.all([ axios.get('http://localhost:3000/api/copilot/statistics/token-costs', { params: { start: startDate, end: endDate }, headers: { 'Authorization': 'Bearer YOUR_JWT_TOKEN' } }), axios.get('http://localhost:3000/api/copilot/statistics/daily-messages', { params: { start: startDate, end: endDate }, headers: { 'Authorization': 'Bearer YOUR_JWT_TOKEN' } }), axios.get('http://localhost:3000/api/copilot/statistics/user-satisfaction-rate', { params: { start: startDate, end: endDate }, headers: { 'Authorization': 'Bearer YOUR_JWT_TOKEN' } }) ]); console.log('Token Costs:', tokenCosts.data); console.log('Daily Messages:', dailyMessages.data); console.log('User Satisfaction:', userSatisfaction.data); return { costs: tokenCosts.data, messages: dailyMessages.data, satisfaction: userSatisfaction.data }; } catch (error) { console.error('Failed to fetch statistics:', error.message); throw error; } }; // Example usage const stats = await getCopilotStatistics('2024-01-01', '2024-01-31'); ``` -------------------------------- ### Deploy XpertAI Docker Compose with BI Profile for Chinese Users Source: https://github.com/xpert-ai/xpert/blob/main/docker/README.md Combines the network-optimized deployment for Chinese users with the 'bi' profile. This command allows users in China to enable multidimensional modeling capabilities while using the dedicated compose file. The service runs in detached mode. ```bash docker compose -f docker-compose.cn.yml --profile bi up -d ``` -------------------------------- ### Docker Deployment Source: https://context7.com/xpert-ai/xpert/llms.txt Instructions for deploying the Xpert AI platform using Docker Compose. ```APIDOC ## Docker Deployment ### Description Instructions for deploying the Xpert AI platform using Docker Compose, including PostgreSQL, Redis, and OLAP services. ### Steps 1. **Clone the repository**: ```bash git clone https://github.com/xpert-ai/xpert.git cd xpert ``` 2. **Navigate to the docker directory**: ```bash cd docker ``` 3. **Copy environment template**: ```bash cp .env.example .env ``` 4. **Edit environment variables**: Open the `.env` file using a text editor (e.g., `nano .env`) and configure the following variables: ```properties NODE_ENV=production API_BASE_URL=http://localhost:3000 CLIENT_BASE_URL=http://localhost DB_HOST=db DB_PORT=5432 DB_NAME=xpert_db DB_USER=postgres DB_PASS=secure_password_here REDIS_HOST=redis REDIS_PORT=6379 ``` 5. **Start services**: ```bash docker compose up -d ``` 6. **Check service status**: ```bash docker compose ps ``` 7. **View logs**: ```bash docker compose logs -f api ``` 8. **Initialize the platform**: Access `http://localhost/onboarding` in your web browser to complete the initial setup. 9. **Stop services**: ```bash docker compose down ``` 10. **Stop and remove volumes**: ```bash docker compose down -v ``` ``` -------------------------------- ### Generate New Plugin Library with Nx Source: https://github.com/xpert-ai/xpert/blob/main/packages/plugins/README.md Generates a new plugin library using the Nx CLI with specified configurations for import path, unit testing, publishability, bundling, and linting. Replace `my-plugin` with your desired plugin name and import path. ```bash npx nx g @nx/js:lib packages/plugins/my-plugin --importPath=@xpert-ai/plugin-my-plugin --unitTestRunner=jest --publishable --bundler=rollup --linter=eslint ``` -------------------------------- ### Display Empty State and Initial Prompt Source: https://github.com/xpert-ai/xpert/blob/main/packages/copilot-angular/src/lib/chat/chat.component.html Handles the UI when there are no conversations, displaying an introductory message and prompting the user to select a business role if available. This serves as the initial state for the Copilot. ```html @if (!conversations()?.length) { 💡{{ 'Copilot.AskAICopilot' | translate: {Default: 'Ask AI Copilot Questions'} }} @if (roles()) { {{'Copilot.PleaseSelectBusinessRole' | translate: {Default: 'Please select a business role'} }} @for (item of roles(); track $index) {* {{item.title || item.name}} } } } ``` -------------------------------- ### Backup Postgres Database within Container Source: https://github.com/xpert-ai/xpert/blob/main/docker/README.md This command is executed inside the 'pg12' Docker container to create a backup of the 'ocap' database. It excludes the 'demo' schema and saves the backup in a custom format to a specified file within the container's volume. The backup file needs to be manually exported afterwards. ```bash pg_dump -U postgres -d ocap --exclude-schema=demo -Fc -f /var/lib/postgresql/data/pg12_backup.dump ``` -------------------------------- ### Display Knowledge Base Creation Options (Angular) Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/features/xpert/knowledge/knowledgebase/documents/documents.component.html This code displays options for creating new content within the knowledge base, including new folders, creation from a pipeline, and new documents. ```html {{ 'PAC.Knowledgebase.NewFolder' | translate: {Default: 'New Folder'} }} {{ 'PAC.Knowledgebase.CreateFromPipeline' | translate: {Default: 'Create From Pipeline'} }} {{ 'PAC.Knowledgebase.NewDocuments' | translate: {Default: 'New Documents' } }} ``` -------------------------------- ### Translation Display Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/features/xpert/studio/panel/workflow/source-test/source.component.html Displays translated text for UI elements like 'Options', 'Run', 'Cancel', and 'Start'. It relies on a translation pipe, likely from an internationalization library. This snippet is purely for display purposes. ```html {{ 'PAC.KEY_WORDS.Options' | translate: {Default: 'Options'} }} ``` ```html {{ 'PAC.ACTIONS.Run' | translate: {Default: 'Run'} }} ``` ```html {{ 'PAC.ACTIONS.Cancel' | translate: {Default: 'Cancel'} }} ``` ```html {{ 'PAC.ACTIONS.Start' | translate: {Default: 'Start'} }} ``` -------------------------------- ### Display Translated and Internationalized Time Option Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/features/setting/copilot/overview/overview.component.html This snippet displays a selected time option that has been both translated and internationalized. It first calls `selectedTimeOption()` to get the option value, then applies an `i18n` pipe for internationalization. ```html {{ selectedTimeOption() | i18n }} ``` -------------------------------- ### Display Command and Context Information Source: https://github.com/xpert-ai/xpert/blob/main/packages/copilot-angular/src/lib/chat/chat.component.html Renders details about a selected command or context, including its name, caption, key, and description. This provides users with information about available actions. ```html @if (command() || context()) { @if (command()) { {{command().name}} } @if (context()) { {{context().caption || context().key}} } @if (command()) { {{command().description}} } } ``` -------------------------------- ### Display Document Details in Angular Template Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/@shared/knowledge/task/task.component.html Renders details for a document when no tasks are present, including its ID, category, status, process start time, duration, message, and progress. This is implemented using Angular's template syntax. ```html @empty { {{ 'PAC.Knowledgebase.DocumentId' | translate: {Default: 'Document Id'} }}: {{ document()?.id }} {{ 'PAC.Knowledgebase.Category' | translate: {Default: 'Category'} }}: {{ document()?.category }} {{ 'PAC.Knowledgebase.Status' | translate: {Default: 'Status'} }}: {{ document()?.status }} {{ 'PAC.Knowledgebase.ProcessBeginAt' | translate: {Default: 'Process Begin At'} }}: {{ document()?.processBeginAt | relative }} {{ 'PAC.Knowledgebase.ProcessDuration' | translate: {Default: 'Process Duration ms'} }}: {{ document()?.processDuation }} {{ 'PAC.KEY_WORDS.Message' | translate: {Default: 'Message'} }}: {{ document()?.processMsg }} {{ 'PAC.Knowledgebase.Progress' | translate: {Default: 'Progress'} }}: {{ document()?.progress }}% } ``` -------------------------------- ### Conditional Rendering and Switch Statement Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/features/xpert/studio/panel/workflow/source-test/source.component.html Demonstrates conditional rendering based on the presence of parameters and a switch statement to handle different provider categories. It includes empty blocks for 'LocalFile' and 'WebCrawl' cases, suggesting further logic is implemented elsewhere. ```html @if (parameters()?.length) { } @switch (providerCategory()) { @case (eDocumentSourceProviderCategoryEnum.LocalFile) { } } ``` ```html @switch (providerCategory()) { @case (eDocumentSourceProviderCategoryEnum.WebCrawl) { @if (testing()) { } @else if (documents()) { @for (doc of documents(); track doc.id) { {{ doc.metadata.title }} {{ doc.metadata.source }} } @empty { {{ 'PAC.Knowledgebase.NoPagesFetched' | translate: {Default: 'No pages fetched'} }} } } } @default { @for (doc of documents(); track doc.id) { {{ doc.metadata.title }} {{ doc.metadata.source }} } @if (busing()) { } } } ``` -------------------------------- ### New Page Creation Options with Translations Source: https://github.com/xpert-ai/xpert/blob/main/libs/story-angular/story/story-widget/story-widget.component.html Displays options for creating new pages, differentiating between responsive and canvas page types. Translations are handled using Angular's translate pipe. ```html {{ 'Story.Story.NewResponsivePage' | translate: {Default: "New Responsive Page"} }} {{ 'Story.Story.NewCanvasPage' | translate: {Default: "New Canvas Page"} }} ``` -------------------------------- ### Translate Chat Messages Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/xpert/canvas/computer/computer.component.html Uses a translation pipe to internationalize chat messages. It takes a translation key and an optional object for dynamic values, ensuring messages are displayed in the user'.s language. Examples include 'Xpert's Computer' and 'Terminal'. ```html {{'PAC.Chat.WhosComputer' | translate: {value: 'Xpert', Default: "Xpert's Computer"} }} {{ 'PAC.Chat.Terminal' | translate: {Default: 'Terminal'} }} {{ 'PAC.Chat.FileSystem' | translate: {Default: 'File System'} }} {{ 'PAC.Chat.Timeline' | translate: {Default: 'Timeline'} }} ``` -------------------------------- ### Data Export to Excel and CSV Source: https://github.com/xpert-ai/xpert/blob/main/libs/story-angular/widgets/table/igx-grid/smart-grid.component.html Provides functionality to export data to Excel and CSV files. These are typically implemented as button actions triggering file generation. No specific code examples are provided, but the UI elements suggest these features. ```html {{ title }} 导出到 Excel 文件 导出到 CSV 文件 ``` -------------------------------- ### Deploy XpertAI Docker Compose for Chinese Users Source: https://github.com/xpert-ai/xpert/blob/main/docker/README.md This command is specifically for users in China who might encounter network issues. It uses a dedicated compose file (docker-compose.cn.yml) to deploy XpertAI, ensuring smoother access. The service runs in detached mode. ```bash docker compose -f docker-compose.cn.yml up -d ``` -------------------------------- ### Display Tags using Angular's @for loop Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/@shared/tag/maintain/maintain.component.html This snippet shows how to iterate through a list of tags using Angular's '@for' directive. It's intended for displaying tag information, though the specific tag properties are not rendered in this example. ```html {{'PAC.ACTIONS.Add' | translate: {Default: 'Add'}}} @for (tag of tags(); track tag.id) { } ``` -------------------------------- ### Set Volume Permissions for API Public Directory Source: https://github.com/xpert-ai/xpert/blob/main/docker/README.md These commands ensure the correct directory structure and permissions are set for the API's public volume. This is crucial for the application to correctly serve static assets and handle file operations. It involves creating the directory if it doesn't exist, setting ownership to UID 1000:GID 1000, and granting read/write/execute permissions. ```bash mkdir -p ./volumes/api/public sudo chown -R 1000:1000 ./volumes/api/public sudo chmod -R 775 ./volumes/api/public ``` -------------------------------- ### UI Text Translations (Angular) Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/features/chat/home/home.component.html This code shows examples of using Angular's translate pipe to internationalize various UI text elements, including labels for search, chat, tasks, projects, history, and actions like rename and delete. ```html {{'PAC.KEY_WORDS.Search' | translate: {Default: 'Search'} }} ``` ```html {{'PAC.Chat.NewChat' | translate: {Default: 'New Chat'} }} ``` ```html {{'PAC.Chat.Tasks' | translate: {Default: 'Tasks'} }} ``` ```html {{'PAC.Chat.Projects' | translate: {Default: 'Projects'} }} ``` ```html {{'PAC.Chat.History' | translate: {Default: 'History'} }} ``` ```html {{'PAC.Chat.Histories' | translate: {Default: 'Histories'} }} ``` ```html {{ 'PAC.Chat.SeeAll' | translate: { Default: 'See All' } }} ``` ```html {{'PAC.Chat.Rename' | translate: {Default: 'Rename'} }} ``` ```html {{'PAC.Chat.Delete' | translate: {Default: 'Delete'} }} ``` -------------------------------- ### Creating New Project Items Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/features/project/project/project.component.html This snippet details the UI elements and translation keys for creating new project items such as collections and stories. It includes buttons for 'New Collection' and 'New Story', along with icons representing folders and file creation. This section helps users initiate the creation of new content within the project. ```html {{ 'PAC.Project.NewCollection' | translate: {Default: 'New Collection'} }} {{ 'PAC.Project.NewStory' | translate: {Default: 'New Story'} }} create_new_folder {{ 'PAC.Project.NewCollection' | translate: {Default: 'New Collection'} }} collections {{ 'PAC.Project.NewStory' | translate: {Default: 'New Story'} }} ``` -------------------------------- ### Angular Display: Provider, Model, and Currency Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/features/setting/copilot/users/users.component.html These snippets demonstrate the display of specific data points: 'provider', 'model', and 'currency' from an item. They directly output the values of these properties. No specific formatting or transformations are applied, assuming they are already in a display-ready format. Dependencies include the 'item' object having these properties. ```html {{ item.provider }} ``` ```html {{ item.model }} ``` ```html {{ item.currency }} ``` -------------------------------- ### Display Prompt Completion Suggestions Source: https://github.com/xpert-ai/xpert/blob/main/packages/copilot-angular/src/lib/chat/chat.component.html Shows a suggested completion for the user's current prompt. This feature assists users by suggesting the rest of their input. ```html @if (promptCompletion()) { {{prompt()}} {{promptCompletion()}} } ``` -------------------------------- ### Define Custom Copilot Command in Angular Source: https://github.com/xpert-ai/xpert/blob/main/packages/copilot/README.md Defines a custom command for the Metad Copilot using injectCopilotCommand. This involves specifying the command's name, description, and optional examples or actions. This function is used to inject custom commands into the Copilot dialog prompt. ```typescript injectCopilotCommand({ name: 'form', description: 'Descripe how to fill the form', examples: ['A', 'B'], actions: [] }) ``` -------------------------------- ### Conditional Rendering with @if/@else Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/xpert/conversations/conversations.component.html Demonstrates basic conditional rendering using @if and @else directives. This allows for showing or hiding content based on a boolean condition. No external dependencies are required for this basic structure. ```html @if (searchValue) { } @else { } ``` ```html @if (expand()) { } @else { } ``` -------------------------------- ### POST /api/xpert-agent/middlewares/:provider/tools Source: https://context7.com/xpert-ai/xpert/llms.txt Configures and retrieves tools for a specific agent middleware provider. ```APIDOC ## POST /api/xpert-agent/middlewares/:provider/tools ### Description Retrieves tools for a specific agent middleware provider based on the provided configuration. ### Method POST ### Endpoint `/api/xpert-agent/middlewares/:provider/tools` ### Parameters #### Path Parameters - **provider** (string) - Required - The identifier of the middleware provider (e.g., `github`). #### Request Body - **config** (object) - Required - Configuration object for the middleware. - **accessToken** (string) - Required - Authentication token for the provider. - **repository** (string) - Optional - Specific repository details if applicable (e.g., `owner/repo`). ### Request Example ```json { "config": { "accessToken": "YOUR_GITHUB_TOKEN", "repository": "xpert-ai/xpert" } } ``` ### Response #### Success Response (200) - **tools** (array) - A list of tools available for the specified middleware provider. #### Response Example ```json [ { "name": "get_issues", "description": "Get a list of issues from a repository." }, { "name": "create_pull_request", "description": "Create a new pull request." } ] ``` #### Error Response - **error** (string) - Details about the error during tool retrieval. ``` -------------------------------- ### Xpert AI Suggestions and Empty State Rendering Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/xpert/conversation/conversation.component.html This snippet handles the scenario where there are no messages, displaying AI-specific content like title, description, and starter statements. It also includes logic for enabling and displaying suggestions or prompts for the user to ask. ```html @empty { @if (!loadingConv() && xpert()) { {{xpert().title || xpert().name}} {{xpert().description}} @for (statement of xpert().starters; track statement) { @if (statement) { {{statement}} } } @if (parameters()?.length) { } } } @if (suggestion_enabled()) { @if (suggesting()) { {{ 'PAC.Xpert.Suggesting' | translate: {Default: 'Suggesting'} }}... } @else if (suggestionQuestions()?.length) { {{ 'PAC.Xpert.TryAsking' | translate: {Default: 'Try asking'} }} @for (question of suggestionQuestions(); track question) { {{question}} } } } ``` -------------------------------- ### Define Copilot Argument Annotations with Zod in Angular Source: https://github.com/xpert-ai/xpert/blob/main/packages/copilot/README.md Defines the input parameters for a Copilot action function using argumentAnnotations. This example demonstrates defining properties like name, type, description, and requirement, with an option to use Zod for complex object definitions and then converting them to JSON schema. ```typescript import { z, ZodType, ZodTypeDef } from 'zod' import zodToJsonSchema from 'zod-to-json-schema' { properties: (<{ properties: any }>zodToJsonSchema(z.object({ title: z.string().describe('The title of form'), desc: z.string().description('My Milestone Work Objectives'), standard: z.string().description('My Satisfaction Measurement Standard'), }))).properties } ``` -------------------------------- ### Conditional Help URL Display Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/features/xpert/studio/panel/workflow/source-test/source.component.html Conditionally displays a help URL if available. It uses the 'as' keyword for variable assignment and a pipe for translation. No external dependencies are immediately apparent for this snippet. ```html @if (selectedStrategy()?.meta.helpUrl; as url) { {{ 'PAC.KEY_WORDS.Help' | translate: {Default: 'Help'} }} } ``` -------------------------------- ### Workflow Node Type Switching Logic Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/features/xpert/studio/panel/workflow/workflow.component.html This snippet demonstrates the core logic for handling different workflow node types using a switch-case statement. It checks the 'type()' against various enum values from 'eWorkflowNodeTypeEnum' to determine the appropriate action or rendering. The example also includes a conditional check for a provider's icon. ```Nunjucks @switch(type()) { @case (eWorkflowNodeTypeEnum.TRIGGER) { @if (provider()?.icon; as icon) { } @else { } } @default { } } ``` -------------------------------- ### Conditional Rendering for Xpert AI Agent Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/features/xpert/studio/components/agent/agent.component.html This snippet shows how to conditionally render UI elements based on various Xpert AI agent states such as whether the agent is active, is the root agent, is the starting agent, is sensitive, is the ending agent, or if output is disabled. It utilizes Razor syntax for conditional logic. ```cshtml @if (xpertAgent()) { @if (isRoot()) { } @if (isStart()) { } @if(isSensitive()) { } @if(isEnd()) { } @if (isDisableOutput()) { } {{agentLabel()}} {{xpertAgent().description}} @if (retry()?.enabled && retry().stopAfterAttempt) { {{'PAC.Xpert.RetryTimes' | translate: { Default: 'Retry '+(retry().stopAfterAttempt - 1)+' times on failure', times: retry().stopAfterAttempt - 1 } }} } @if (fallback()?.enabled) { {{'PAC.Xpert.FallbackModel' | translate: {Default: 'Fallback Model'} }}: } @if (errorHandling()?.type) { } } ``` -------------------------------- ### Project Navigation and Translation Keys Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/features/project/project/project.component.html This snippet showcases the use of Angular's translate pipe for internationalization in a project context. It displays navigation links for 'Home', 'Bookmarks', 'Collections', 'Semantic Models', and 'Indicators'. The keys like 'PAC.Project.Home' are used to fetch translated strings, ensuring multi-language support. ```html home {{ 'PAC.Project.Home' | translate: {Default: 'Home'} }} {{ 'PAC.Project.Bookmarks' | translate: {Default: 'Bookmarks'} }} chevron_right expand_more drag_indicator 📖 {{bookmark.story.name}} bookmark {{ 'PAC.Project.Collections' | translate: {Default: 'Collections'} }} {{ 'PAC.Project.SemanticModels' | translate: {Default: 'Semantic Models'} }} add_link chevron_right expand_more trending_up {{ 'PAC.Project.Indicators' | translate: {Default: 'Indicators'} }} ``` -------------------------------- ### Iterating and Displaying Points with Key Tracking Source: https://github.com/xpert-ai/xpert/blob/main/libs/story-angular/story/story-widget/story-widget.component.html Demonstrates iterating over a list of points ('pointList') using Angular's '@for' directive. Each point's name is displayed, and the 'track by point.key' ensures efficient DOM updates. ```html @for (point of pointList(); track point.key) { {{ point.name }} } ``` -------------------------------- ### Basic Conditional Rendering for Side Menu Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/features/xpert/xpert/xpert.component.html This snippet shows a simple conditional rendering based on whether the side menu is opened. It includes an if block and an else block, suggesting alternative UI states or content can be displayed. The content within these blocks is not specified. ```C# @if (sideMenuOpened()) { } @else { } ``` -------------------------------- ### Execute SQL Queries on Data Sources (TypeScript) Source: https://context7.com/xpert-ai/xpert/llms.txt Executes SQL queries against configured data sources. Supports multiple database types and includes error handling for query execution. Requires a data source ID and the SQL query string as input. Returns the query results or throws an error. ```typescript // POST /api/data-source/:id/query // Execute SQL query on a data source const queryDataSource = async (dataSourceId, sqlQuery) => { try { const response = await axios.post( `http://localhost:3000/api/data-source/${dataSourceId}/query`, { query: sqlQuery }, { headers: { 'Authorization': 'Bearer YOUR_JWT_TOKEN', 'Accept-Language': 'en-US' } } ); console.log(`Rows returned: ${response.data.length}`); return response.data; } catch (error) { if (error.response?.status === 400) { console.error('Query error:', error.response.data); } else { console.error('Failed to execute query:', error.message); } throw error; } }; // Example usage const results = await queryDataSource( 'ds-uuid-here', 'SELECT product_name, SUM(revenue) as total_revenue FROM sales GROUP BY product_name' ); ``` -------------------------------- ### Retrieve and Display Knowledgebase Data Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/features/setting/copilot/overview/overview.component.html This snippet calls the `knowledgebases()` function, presumably to fetch data related to knowledge bases. The output of this function is directly displayed, which could be a count, a list, or other relevant information. ```html {{ knowledgebases() }} ``` -------------------------------- ### Action Buttons for Project Items Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/features/project/project/project.component.html This snippet presents a set of common action buttons applicable to project items, including 'Edit', 'Copy', 'Move to', and 'Remove'. It also includes specific actions like 'Rerelease', 'Archive', and 'Release' based on the item's status, managed via a switch statement. These actions allow users to manipulate and manage project content. ```html {{ 'PAC.KEY_WORDS.Edit' | translate: {Default: 'Edit'} }} {{ 'PAC.Project.Copy' | translate: {Default: 'Copy'} }} {{ 'PAC.Project.MoveTo' | translate: {Default: 'Move to'} }} {{ 'PAC.Project.Remove' | translate: {Default: 'Remove'} }} ``` -------------------------------- ### Iterate and Display Roles Source: https://github.com/xpert-ai/xpert/blob/main/packages/copilot-angular/src/lib/chat/chat.component.html Loops through a list of roles and displays their titles or names. This is used to present available business roles to the user. ```html @for (role of roles(); track role) {* {{role.title || role.name}} } ``` -------------------------------- ### Conditional Rendering based on Step Type and Toolset Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/@shared/chat/message-step-icon/icon.component.html This code snippet demonstrates conditional rendering logic based on the type of a chat message step and its associated toolset. It handles various cases for file uploads, programming tasks, knowledge retrieval, and specific toolset integrations, falling back to displaying an icon for unknown toolsets. ```csharp @if (step(); as step) { @switch (step.type) { @case (eChatMessageStepCategory.File) { } @case (eChatMessageStepCategory.Files) { } @case (eChatMessageStepCategory.Program) { } @case (eChatMessageStepCategory.Knowledges) { } @default { @if (step.toolset) { @switch (step.toolset) { @case ('project') { } @case ('transfer_to') { } @case ('knowledge') { } @case ('knowledgebase') { } @case ('project-tasks') { } @case ('memories') { } @case ('workflow_agent_tool') { } @case ('workflow_task') { } @case ('mcp') { } @case ('openapi') { } @default { ![{{step.toolset}}](/api/xpert-toolset/builtin-provider/{{step.toolset}}/icon) } } } } } } ``` -------------------------------- ### Looping through Tools and Execution Status Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/features/xpert/studio/components/workflow/middleware/middleware.component.html This snippet iterates through a list of tools and their executions, rendering tool names and handling different execution statuses ('running', 'fail', 'success'). It uses Angular's @for and @switch directives. It also displays a label for 'Input' and handles an empty state with an optional error display. Dependencies include 'tools()', 'executions', 'status', 'error()', and 'loading()' functions/properties, along with the 'translate' pipe. ```html @for (item of tools(); track item.name) { {{item.name}} @for (execution of item.executions; track execution) { @switch (execution.status) { @case ('running') { } @case ('fail') { } @case ('success') { } } {{ 'PAC.KEY_WORDS.Input' | translate: {Default: 'Input'} }}: } } @empty { @if (error()) { {{ error() }} } } @if (loading()) { } ``` -------------------------------- ### Conditional Actions and Loading State (Angular Template) Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/@shared/environment/manage/manage.component.html This snippet demonstrates conditional rendering for actions like 'Delete' based on whether an environment is selected. It also includes a placeholder for handling a loading state. ```html @if (environment()) { {{ 'PAC.ACTIONS.Delete' | translate: { Default: 'Delete' } }} } @if (loading()) { } ``` -------------------------------- ### Copilot Model Management API Source: https://context7.com/xpert-ai/xpert/llms.txt Retrieves a list of available AI models for specified types (e.g., 'llm', 'embedding'). Provides details about each model's provider, label, model name, type, and supported features. Requires an Authorization header. ```typescript const getAvailableModels = async (modelType = 'llm') => { try { const response = await axios.get( `http://localhost:3000/api/copilot/models`, { params: { type: modelType }, headers: { 'Authorization': 'Bearer YOUR_JWT_TOKEN' } } ); response.data.forEach(copilot => { console.log(`Copilot: ${copilot.role}`); copilot.providerWithModels.models.forEach(model => { console.log(` - ${model.label} (${model.model})`); console.log(` Type: ${model.model_type}`); console.log(` Features: ${model.features.join(', ')}`); }); }); return response.data; } catch (error) { console.error('Failed to fetch models:', error.message); throw error; } }; ``` -------------------------------- ### Conditional Rendering with Async Pipes Source: https://github.com/xpert-ai/xpert/blob/main/libs/story-angular/story/story-widget/story-widget.component.html Demonstrates conditional rendering in Angular using async pipes to subscribe to observable streams. This pattern is useful for displaying UI elements only when the associated observable emits a truthy value. ```html @if (placeholder$ | async) { } @if (showMenu$ | async) { } ``` -------------------------------- ### Displaying Selected Copilot Model Information Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/@shared/copilot/copilot-model-select/select.component.html This snippet shows how to display information about a selected copilot model, including its icon and model name. It also includes logic for handling different model types (LLM, RERANK, etc.) and features like tool calls and vision capabilities. ```html @if (selectedCopilotWithModels(); as copilot) { @if (copilot.providerWithModels.icon_small) { } {{_copilotModel()?.model}} @if (selectedAiModel(); as model) { @switch (model.model_type) { @case (eModelType.LLM) { {{'PAC.Copilot.Chat' | translate: {Default: 'Chat'}}} } @case (eModelType.RERANK) { } @case (eModelType.TEXT_EMBEDDING) { } @case (eModelType.SPEECH2TEXT) { } @case (eModelType.TTS) { } @default {} } @if (model.features?.includes(eModelFeature.TOOL_CALL) || model.features?.includes(eModelFeature.MULTI_TOOL_CALL)) { } @if (model.features?.includes(eModelFeature.VISION)) { } } } @else if (__copilotModel()) { {{'PAC.Copilot.ChooseRightCopilot' | translate: {Default: 'Please choose right copilot'}}} @if (__copilotModel().model) { {{__copilotModel().modelType + '/' + __copilotModel().model}} } } @else { {{'PAC.Copilot.SelectModel' | translate: {Default: 'Select model'}}} } ``` -------------------------------- ### Display Knowledge Base Root and Folder Structure (Angular) Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/features/xpert/knowledge/knowledgebase/documents/documents.component.html This snippet demonstrates how to conditionally display the root of the knowledge base or a parent folder's name based on the presence of a parent ID. It also handles the case where no parent ID is found, displaying a 'Files' title. ```html @if (parentId()) { 1. {{ 'PAC.Knowledgebase.Root' | translate: {Default: 'Root'} }} @if (grandParent(); as grand) {2. {{ grand.name }} } } @else { {{ 'PAC.Knowledgebase.Files' | translate: {Default: 'Files'} }} } {{ 'PAC.Knowledgebase.DocumentsDescription' | translate: {Default: 'All files in the knowledge base are displayed here, and the entire knowledge base can be applied to the digital expert agent or project space.' } }} {{ 'PAC.KEY_WORDS.LearnMore' | translate: {Default: 'Learn more'} }} @if (search()) { } {{ 'PAC.Knowledgebase.Metadata' | translate: {Default: 'Metadata'} }} {{ 'PAC.Knowledgebase.NewUpload' | translate: {Default: 'New / Upload'} }} ``` -------------------------------- ### Angular: Iterate and Display Tables Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/features/semantic-model/tables-join/tables-join.component.html This snippet demonstrates an Angular template loop iterating over a list of tables. It uses async pipe to handle observable data and provides index and position information for each item. The displayed content includes the item's name and translations for 'Remove' and 'Join config'. ```html @for (item of tables$ | async; let i = $index; let isFirst = $first; let isLast = $last; track item.__id__) { @if (!isFirst) { } {{ item.name }} } {{'PAC.KEY_WORDS.REMOVE' | translate: {Default: "Remove"} }} {{ 'PAC.MODEL.JoinConfig' | translate: {Default: 'Join config'} }} ``` -------------------------------- ### Iterating and Displaying Searched Copilot Models Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/@shared/copilot/copilot-model-select/select.component.html This section iterates through a list of searched copilot models, displaying their provider label, name, and role. It also details the specific models associated with each provider, including their types and features. ```html @for (copilot of searchedModels(); track copilot.id) { {{copilot.providerWithModels?.label | i18n }} @if (copilot.name) { {{copilot.name}} } @else { {{ ('PAC.Copilot.Role_' + copilot.role) | translate: {Default: copilot.role} }} } @for (item of copilot.providerWithModels?.models; track item.model) { @if (copilot.providerWithModels.icon_small) { } {{item.model}} @switch (item.model_type) { @case (eModelType.LLM) { {{'PAC.Copilot.Chat' | translate: {Default: 'Chat'}}} } @case (eModelType.RERANK) { } @case (eModelType.TEXT_EMBEDDING) { } @case (eModelType.SPEECH2TEXT) { } @case (eModelType.TTS) { } } @if (item.features?.includes(eModelFeature.TOOL_CALL) || item.features?.includes(eModelFeature.MULTI_TOOL_CALL)) { } @if (item.features?.includes(eModelFeature.VISION)) { } } } ``` -------------------------------- ### Workspace and Knowledgebase Iteration (Angular) Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/features/chat/project/knowledges/knowledges.component.html This Angular template code iterates through available workspaces and their associated knowledgebases. It displays the 'Available Knowledgebases' title and handles the loading state of workspace knowledgebases using conditional rendering. ```html @if (workspace()) { @for (toolset of knowledgebases(); track toolset.id) { } {{ 'PAC.XProject.AvailableKnowledgebases' | translate: { Default: 'Available Knowledgebases' } }} @if (wsKbLoading()) { } @else { @for (item of wsKnowledgebases(); track item.knowledgebase.id) { @if (item.added) { } @else { } } } } ``` -------------------------------- ### Displaying Projects with Conditional Rendering (Angular) Source: https://github.com/xpert-ai/xpert/blob/main/apps/cloud/src/app/features/chat/home/home.component.html This snippet demonstrates iterating over a list of projects and conditionally rendering their names. It also includes logic for an editing state and a 'See All' link. ```html @for (project of projects(); track project.id) { @if (editingProject() === project.id) { } @else { {{ project.name }} @if (sidebarState() === 'expanded') { } } } {{ 'PAC.Chat.SeeAll' | translate: { Default: 'See All' } }} ``` -------------------------------- ### Translate Display Behavior Options Source: https://github.com/xpert-ai/xpert/blob/main/packages/angular/controls/value-help/value-help.component.html This snippet illustrates the translation of various display behavior options within the ValueHelp control. It uses the translate pipe to display labels like 'Description', 'Description ID', 'ID Description', 'ID', and 'Auto', providing options for how data should be presented. ```html {{ 'Ngm.Controls.ValueHelp.DisplayBehaviour' | translate: {Default: "Display Behaviour"} }} {{ 'Ngm.Common.DisplayBehaviour_Description' | translate: {Default: "Description"} }} {{ 'Ngm.Common.DisplayBehaviour_DescriptionID' | translate: {Default: "Description ID"} }} {{ 'Ngm.Common.DisplayBehaviour_IDDescription' | translate: {Default: "ID Description"} }} {{ 'Ngm.Common.DisplayBehaviour_ID' | translate: {Default: "ID"} }} {{ 'Ngm.Common.DisplayBehaviour_Auto' | translate: {Default: "Auto"} }} ```