### Install Project Dependencies Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/examples/vanilla-js.md Install the necessary npm packages for the backend server and Monacopilot integration. ```bash npm init -y npm install express cors monacopilot dotenv ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/examples/remix.md Install all project dependencies using npm, yarn, pnpm, or bun after cloning the repository or setting up the project. ```bash npm install ``` ```bash yarn ``` ```bash pnpm install ``` ```bash bun install ``` -------------------------------- ### Clone and Install Dependencies Source: https://github.com/arshad-yaseen/monacopilot/blob/main/CONTRIBUTING.md Initial commands to set up the local development environment. ```bash git clone https://github.com/arshad-yaseen/monacopilot.git cd monacopilot pnpm install ``` -------------------------------- ### Start Development Server Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/examples/gatsby.md Launch the Gatsby development server. ```npm npm run develop ``` ```yarn yarn develop ``` ```pnpm pnpm develop ``` ```bun bun develop ``` -------------------------------- ### Install Monacopilot dependencies Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/examples/sveltekit.md Install the required packages for Monacopilot and Monaco Editor integration. ```bash npm install monacopilot @monaco-editor/loader monaco-editor ``` ```bash yarn add monacopilot @monaco-editor/loader monaco-editor ``` ```bash pnpm add monacopilot @monaco-editor/loader monaco-editor ``` ```bash bun add monacopilot @monaco-editor/loader monaco-editor ``` -------------------------------- ### Start the development server Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/examples/sveltekit.md Launch the development server to view the Monaco Editor with AI-powered completions. ```npm npm run dev ``` ```yarn yarn dev ``` ```pnpm pnpm run dev ``` ```bun bun dev ``` -------------------------------- ### Install Monacopilot and React Monaco Editor Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/examples/remix.md Use npm, yarn, pnpm, or bun to install the necessary dependencies for Monacopilot and the Monaco Editor React component. ```bash npm install monacopilot @monaco-editor/react ``` ```bash yarn add monacopilot @monaco-editor/react ``` ```bash pnpm add monacopilot @monaco-editor/react ``` ```bash bun add monacopilot @monaco-editor/react ``` -------------------------------- ### Install monacopilot package Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/index.md Use your preferred package manager or a CDN link to add monacopilot to your project. ```bash npm install monacopilot ``` ```bash yarn add monacopilot ``` ```bash pnpm add monacopilot ``` ```bash bun add monacopilot ``` ```html ``` -------------------------------- ### Development Workflow Commands Source: https://github.com/arshad-yaseen/monacopilot/blob/main/CONTRIBUTING.md Commands to start development modes for different packages and documentation. ```bash # For core package pnpm dev:core # For monacopilot package pnpm dev:monacopilot # For documentation pnpm dev:docs # For playground pnpm dev:playground ``` -------------------------------- ### Install Monacopilot dependency Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/guides/upgrade-to-v1.md Update the package to version 1.0.0 using npm. ```bash npm install monacopilot@1.0.0 ``` -------------------------------- ### Start Remix Development Server Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/examples/remix.md Run the development server for your Remix application using npm, yarn, pnpm, or bun. Access the application at http://localhost:3000. ```bash npm run dev ``` ```bash yarn dev ``` ```bash pnpm dev ``` ```bash bun dev ``` -------------------------------- ### Environment Variables for API Keys Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/examples/vanilla-js.md Configure your API keys by setting them in the .env file. This example uses MISTRAL_API_KEY. ```bash MISTRAL_API_KEY=your_api_key_here ``` -------------------------------- ### Use Editor Component in Page Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/examples/tanstack-start.md Incorporate the created Editor component into your TanStack Start application's page. This example shows its usage in the home page. ```typescript import { createFileRoute } from '@tanstack/react-router' import Editor from '~/components/Editor' export const Route = createFileRoute('/')({ component: Home, }) function Home() { return (

Monacopilot TanStack Start Example

) } ``` -------------------------------- ### Implement Server-Side Endpoint Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/advanced/custom-request-handler.md Example of an Express-style endpoint receiving the custom headers and body sent by the requestHandler. ```javascript app.post('/code-completion', async (req, res) => { const authToken = req.headers.authorization; const customHeader = req.headers['x-custom-header']; const { additionalData } = req.body; const completion = await copilot.complete({ body: req.body, }); res.json(completion); }); ``` -------------------------------- ### Create API Route for Code Completion Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/examples/tanstack-start.md Set up an API route in TanStack Start to handle POST requests for code completion. This route initializes the CompletionCopilot with your API key and model configuration. ```typescript import { createServerFileRoute } from '@tanstack/react-start/server' import { json } from '@tanstack/react-start' import { CompletionCopilot, type CompletionRequestBody } from 'monacopilot' const copilot = new CompletionCopilot(process.env.MISTRAL_API_KEY, { provider: 'mistral', model: 'codestral', }); export const ServerRoute = createServerFileRoute('/api/code-completion') .methods({ POST: async ({ request }) => { const body: CompletionRequestBody = await request.json(); const completion = await copilot.complete({ body, }); return json(completion); }, }); ``` -------------------------------- ### Integrate Custom OpenAI Model with Monacopilot Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/advanced/custom-model.md Use a custom model by providing an async function to the 'model' option when creating a CompletionCopilot. This example shows integration with OpenAI's API. ```javascript const copilot = new CompletionCopilot(undefined, { // You don't need to set the provider if you are using a custom model. // provider: "openai", model: async prompt => { const response = await fetch( 'https://api.openai.com/v1/chat/completions', { method: 'POST', headers: { Authorization: `Bearer ${process.env.OPENAI_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'gpt-4o', messages: [ {role: 'system', content: prompt.context}, { role: 'user', content: `${prompt.instruction}\n\n${prompt.fileContent}`, }, ], temperature: 0.2, max_tokens: 256, }), }, ); const data = await response.json(); return { text: data.choices[0].message.content, }; }, }); ``` -------------------------------- ### Customize Instruction for Code Completion Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/advanced/custom-prompt.md Use this snippet to override only the instruction part of the prompt for code completion. This is useful for guiding the AI's behavior for a specific completion task. ```javascript // Only customize the instruction for code completion copilot.complete({ options: { customPrompt: metadata => ({ instruction: 'Complete this code with an efficient algorithm that handles edge cases.', }), }, }); ``` -------------------------------- ### Preview Documentation Source: https://github.com/arshad-yaseen/monacopilot/blob/main/CONTRIBUTING.md Command to run the VitePress documentation server locally. ```bash pnpm dev:docs ``` -------------------------------- ### Run Project Tests Source: https://github.com/arshad-yaseen/monacopilot/blob/main/CONTRIBUTING.md Command to execute the test suite. ```bash pnpm test ``` -------------------------------- ### Environment Variable Configuration Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/examples/remix.md Configure your Mistral API key by creating a .env file in your project root. Replace 'your_mistral_api_key_here' with your actual API key obtained from the Mistral AI Console. ```bash .env MISTRAL_API_KEY=your_mistral_api_key_here ``` -------------------------------- ### Initialize Monacopilot in the browser Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/guides/browser-only.md Configures the CompletionCopilot instance and registers it with the Monaco editor using a custom requestHandler. ```javascript import { registerCompletion, CompletionCopilot } from 'monacopilot'; // Create the copilot instance directly in the browser const copilot = new CompletionCopilot('YOUR_API_KEY', { provider: 'mistral', model: 'codestral', }); registerCompletion(monaco, editor, { language: 'javascript', // Use requestHandler instead of endpoint requestHandler: async ({ body }) => { const completion = await copilot.complete({ body }); return completion; }, }); ``` -------------------------------- ### Project Directory Structure Source: https://github.com/arshad-yaseen/monacopilot/blob/main/CONTRIBUTING.md Overview of the monorepo layout using PNPM workspaces. ```text packages/ ├── core/ # Core functionality and provider implementations └── monacopilot/ # Main Monaco Editor integration package docs/ # Documentation website playground/ # NextJS app for testing changes in real-time ``` -------------------------------- ### Implement Editor component Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/examples/sveltekit.md Create a Svelte component that initializes the Monaco Editor and registers the Monacopilot completion provider. ```html
``` -------------------------------- ### Configure CompletionCopilot Provider and Model Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/configuration/copilot-options.md Initializes the CompletionCopilot instance with a specific provider and model using an API key. ```javascript const copilot = new CompletionCopilot(process.env.MISTRAL_API_KEY, { provider: 'mistral', model: 'codestral', }); ``` -------------------------------- ### Register Completion with Multi-File Context Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/configuration/register-options.md Provide context from other files using the `relatedFiles` option to improve Copilot's suggestions. The `path` should match the import path. ```javascript registerCompletion(monaco, editor, { relatedFiles: [ { path: './utils.js', // The exact path you'd use when importing content: 'export const reverse = (str) => str.split("").reverse().join("")', }, ], }); ``` -------------------------------- ### Integrate Monacopilot via CDN Source: https://context7.com/arshad-yaseen/monacopilot/llms.txt Configures the Monaco Editor and registers the completion provider in a browser environment using CDN scripts. ```html Monacopilot Example
``` -------------------------------- ### Implement custom prompt for React components Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/advanced/custom-prompt.md A practical implementation of customPrompt that utilizes completionMetadata to inject file-specific context and instructions for React development. ```javascript const customPrompt = ({ textBeforeCursor, textAfterCursor, language, filename, technologies, }) => ({ context: `You're working with a ${language} file named ${filename || 'unnamed'} in a project using ${technologies?.join(', ') || 'React'}.`, instruction: 'Complete the code after the cursor position with appropriate React syntax. Ensure the code follows modern React best practices and matches the style of the existing code.', fileContent: `${textBeforeCursor}[CURSOR]${textAfterCursor}`, }); copilot.complete({ options: {customPrompt}, }); ``` -------------------------------- ### Configure Environment Variable for API Key Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/examples/tanstack-start.md Add your Mistral API key to the `.env.local` file in your project's root directory. This key is required for the Monacopilot service to authenticate with the Mistral API. ```bash MISTRAL_API_KEY=your_mistral_api_key_here ``` -------------------------------- ### Initialize Monaco Editor and Register Monacopilot Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/examples/vanilla-js.md Configure Monaco Editor and register Monacopilot for code completions using the specified API endpoint. Ensure to deregister on window unload. ```javascript require.config({ paths: { vs: 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.55.1/min/vs', }, }); require(['vs/editor/editor.main'], function () { const editor = monaco.editor.create(document.getElementById('editor'), { value: '// Start coding...\n', language: 'javascript', theme: 'vs-dark', }); const completion = monacopilot.registerCompletion(monaco, editor, { language: 'javascript', // URL to the API endpoint we'll create in server.js below endpoint: 'http://localhost:3000/code-completion', }); window.addEventListener('beforeunload', () => { completion.deregister(); }); }); ``` -------------------------------- ### Custom Prompt Configuration Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/advanced/custom-prompt.md This snippet demonstrates how to configure a custom prompt for code completions using the `customPrompt` function within the `copilot.complete` method options. ```APIDOC ## POST /api/copilot/complete (Conceptual) ### Description This endpoint (conceptually represented by the `copilot.complete` method) allows for code completion with customizable prompts. ### Method POST (Conceptual) ### Endpoint /api/copilot/complete (Conceptual) ### Parameters #### Request Body - **options** (object) - Required - Options for code completion. - **customPrompt** (function) - Optional - A function that returns a `PromptData` object to customize the AI's prompt. ### Request Example ```javascript copilot.complete({ options: { customPrompt: completionMetadata => ({ context: 'Your custom codebase context information here', instruction: 'Your custom instructions for code completion here', fileContent: 'Your representation of file with cursor position', }), }, }); ``` ### Response (Response details depend on the completion result, not explicitly defined in the provided text for this specific configuration.) ### Custom Prompt Function Details The `customPrompt` function receives a `completionMetadata` object and should return a `PromptData` object. #### Completion Metadata Parameters - **language** (string | undefined) - The programming language of the code. - **cursorPosition** ({ lineNumber: number; column: number }) - The current cursor position. - **filename** (string | undefined) - The name of the file being edited. - **technologies** (string[] | undefined) - An array of technologies used in the project. - **relatedFiles** (object[] | undefined) - An array of related file objects with `path` and `content`. - **textAfterCursor** (string) - The text that appears after the cursor position. - **textBeforeCursor** (string) - The text that appears before the cursor position. #### PromptData Return Value Structure - **context** (string | undefined) - Information about the codebase context. - **instruction** (string | undefined) - Instructions for code completion. - **fileContent** (string | undefined) - Representation of the file content with cursor position. ### Example Custom Prompt for React ```javascript const customPrompt = ({ textBeforeCursor, textAfterCursor, language, filename, technologies, }) => ({ context: `You're working with a ${language} file named ${filename || 'unnamed'} in a project using ${technologies?.join(', ') || 'React'}.`, instruction: 'Complete the code after the cursor position with appropriate React syntax. Ensure the code follows modern React best practices and matches the style of the existing code.', fileContent: `${textBeforeCursor}[CURSOR]${textAfterCursor}`, }); copilot.complete({ options: {customPrompt}, }); ``` ``` -------------------------------- ### Create Editor component Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/examples/nextjs.md Implement the Monaco Editor component with completion registration. ```tsx 'use client'; import {useEffect, useRef} from 'react'; import MonacoEditor from '@monaco-editor/react'; import { registerCompletion, type CompletionRegistration, type Monaco, type StandaloneCodeEditor, } from 'monacopilot'; export default function Editor() { const completionRef = useRef(null); const handleMount = (editor: StandaloneCodeEditor, monaco: Monaco) => { completionRef.current = registerCompletion(monaco, editor, { endpoint: '/api/code-completion', language: 'javascript', }); }; useEffect(() => { return () => { completionRef.current?.deregister(); }; }, []); return ( ); } ``` -------------------------------- ### Configure custom prompt in copilot.complete Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/advanced/custom-prompt.md Use the customPrompt function within the options parameter to override default completion context, instructions, or file content representation. ```javascript copilot.complete({ options: { customPrompt: completionMetadata => ({ context: 'Your custom codebase context information here', instruction: 'Your custom instructions for code completion here', fileContent: 'Your representation of file with cursor position', }), }, }); ``` -------------------------------- ### Code Quality Commands Source: https://github.com/arshad-yaseen/monacopilot/blob/main/CONTRIBUTING.md Commands for formatting, type checking, and linting the codebase. ```bash pnpm format ``` ```bash pnpm tsc ``` ```bash pnpm lint ``` -------------------------------- ### Create Editor Component Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/examples/gatsby.md Implement the Monaco Editor component with completion registration. ```typescript import { useEffect, useRef } from "react"; import MonacoEditor from "@monaco-editor/react"; import { registerCompletion, type CompletionRegistration, type Monaco, type StandaloneCodeEditor, } from "monacopilot"; export default function Editor() { const completionRef = useRef(null); const handleMount = (editor: StandaloneCodeEditor, monaco: Monaco) => { completionRef.current = registerCompletion(monaco, editor, { endpoint: "/api/code-completion", language: "javascript", }); }; useEffect(() => { return () => { completionRef.current?.deregister(); }; }, []); return ; } ``` -------------------------------- ### Implement completion API handler with Express.js Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/index.md Create a backend route to handle completion requests using the CompletionCopilot class. ```typescript import 'dotenv/config'; import cors from 'cors'; import express from 'express'; import {CompletionCopilot} from 'monacopilot'; const app = express(); app.use(cors()); app.use(express.json()); const copilot = new CompletionCopilot(process.env.MISTRAL_API_KEY, { provider: 'mistral', model: 'codestral', }); app.post('/code-completion', async (req, res) => { const completion = await copilot.complete({body: req.body}); res.json(completion); }); app.listen(process.env.PORT || 3000); ``` -------------------------------- ### Register completions for specific technologies Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/configuration/register-options.md Use the technologies option to tailor completion suggestions to specific frameworks or languages. ```javascript registerCompletion(monaco, editor, { technologies: ['react', 'next.js', 'tailwindcss'], }); ``` -------------------------------- ### Use Editor component in page Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/examples/sveltekit.md Integrate the Editor component into a SvelteKit page. ```html

Monacopilot SvelteKit Example

``` -------------------------------- ### Backend Server for Code Completion API Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/examples/vanilla-js.md Set up an Express.js server to handle code completion requests using Monacopilot's CompletionCopilot. Requires dotenv, cors, and express. Ensure your API key is set in the .env file. ```typescript require('dotenv').config(); const cors = require('cors'); const express = require('express'); const {CompletionCopilot} = require('monacopilot'); const app = express(); app.use(cors()); app.use(express.json()); const copilot = new CompletionCopilot(process.env.MISTRAL_API_KEY, { provider: 'mistral', model: 'codestral', }); app.post('/code-completion', async (req, res) => { const completion = await copilot.complete({body: req.body}); res.json(completion); }); app.listen(process.env.PORT || 3000, () => { console.log(`Server is running on port ${process.env.PORT || 3000}`); }); ``` -------------------------------- ### Create API route for code completion Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/examples/sveltekit.md Define a SvelteKit server endpoint to handle completion requests using the Mistral provider. ```typescript import {json} from '@sveltejs/kit'; import type {RequestHandler} from '@sveltejs/kit'; import {MISTRAL_API_KEY} from '$env/static/private'; import {CompletionCopilot, type CompletionRequestBody} from 'monacopilot'; const copilot = new CompletionCopilot(MISTRAL_API_KEY, { provider: 'mistral', model: 'codestral', }); export const POST: RequestHandler = async ({request}) => { const body: CompletionRequestBody = await request.json(); const completion = await copilot.complete({body}); return json(completion); }; ``` -------------------------------- ### Configure CompletionCopilot provider Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/guides/upgrade-to-v1.md Update the server-side configuration to use the Mistral provider and Codestral model. ```javascript // Before const copilot = new CompletionCopilot(process.env.OPENAI_API_KEY, { provider: 'openai', model: 'gpt-4o', }); // After const copilot = new CompletionCopilot(process.env.MISTRAL_API_KEY, { provider: 'mistral', model: 'codestral', }); ``` -------------------------------- ### Dynamically Updating Completion Options Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/configuration/register-options.md Learn how to update completion options at runtime without re-registering the completion service. ```APIDOC ## Dynamically Updating Options ### Description Dynamically update completion options after registration using the `updateOptions` method at runtime without needing to deregister and register again. ### Method `completion.updateOptions(callback)` ### Parameters #### Request Body - **callback** (function) - Required - A function that receives the current options and returns a partial options object with the properties to update. ### Request Example ```javascript const completion = registerCompletion(monaco, editor, { language: 'javascript', endpoint: '/api/code-completion', }); // Later, update options when needed: completion.updateOptions((currentOptions) => ({ relatedFiles: [ ...currentOptions.relatedFiles, { path: './newFile.js', content: 'export function newFunction() { return "hello world"; }', }, ], })); ``` ### Response N/A (This method updates existing options) ``` -------------------------------- ### Update environment variables Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/guides/upgrade-to-v1.md Replace the OpenAI API key with the Mistral API key. ```text # Before OPENAI_API_KEY=your_openai_api_key_here # After MISTRAL_API_KEY=your_mistral_api_key_here ``` -------------------------------- ### Configuring Follow-Up Completions Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/configuration/register-options.md Manage whether Monacopilot automatically generates new completions after one is accepted. ```APIDOC ## Follow-Up Completions ### Description Control whether Monacopilot automatically generates a new completion immediately after the user accepts a completion using the `allowFollowUpCompletions` option. ### Method `registerCompletion(monaco, editor, options)` ### Parameters #### Request Body - **allowFollowUpCompletions** (boolean) - Optional - Set to `true` to allow follow-up completions (default), or `false` to disable them. ### Request Example ```javascript registerCompletion(monaco, editor, { allowFollowUpCompletions: false, }); ``` ### Response N/A (This is a configuration step) ``` -------------------------------- ### Register AI completion in Monaco Editor Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/index.md Initialize the editor and register the completion provider with your API endpoint. ```typescript import * as monaco from 'monaco-editor'; import {registerCompletion} from 'monacopilot'; const editor = monaco.editor.create(document.getElementById('container'), { language: 'javascript', }); registerCompletion(monaco, editor, { language: 'javascript', // Your API endpoint for handling completion requests endpoint: 'https://your-api-url.com/code-completion', }); ``` -------------------------------- ### Update custom prompt implementation Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/guides/upgrade-to-v1.md Adjust the custom prompt interface to use the new context, instruction, and fileContent structure. ```javascript // Before copilot.complete({ options: { customPrompt: metadata => ({ system: 'Your custom system prompt here', user: 'Your custom user prompt here', }), }, }); // After copilot.complete({ options: { customPrompt: metadata => ({ context: 'Information about the codebase context', instruction: 'Instructions for code completion', fileContent: 'File content with cursor position', }), }, }); ``` -------------------------------- ### Implement server-side completion handler Source: https://context7.com/arshad-yaseen/monacopilot/llms.txt The CompletionCopilot class processes requests from the client and interfaces with LLM providers. Ensure the MISTRAL_API_KEY is configured in your environment variables. ```typescript import express from 'express'; import cors from 'cors'; import { CompletionCopilot } from 'monacopilot'; const app = express(); app.use(cors()); app.use(express.json()); // Initialize with Mistral Codestral (built-in provider) const copilot = new CompletionCopilot(process.env.MISTRAL_API_KEY, { provider: 'mistral', model: 'codestral' }); app.post('/code-completion', async (req, res) => { const completion = await copilot.complete({ body: req.body }); // Response: { completion: "generated code", error?: "error message" } res.json(completion); }); app.listen(3000, () => { console.log('Completion server running on port 3000'); }); ``` -------------------------------- ### Format Prompts for Completion-based Models Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/advanced/custom-model.md Use this single-string format for completion-based models that require a concatenated prompt structure. ```javascript // Single prompt format prompt: `Context: ${prompt.context}\nFile: ${prompt.fileContent}\nTask: ${prompt.instruction}`; ``` -------------------------------- ### Handle completion lifecycle events Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/configuration/register-options.md Use event handlers to respond to completion suggestions being shown, accepted, or rejected by the user. ```javascript registerCompletion(monaco, editor, { // ... other options onCompletionShown: (completion, range) => { console.log('Completion suggestion:', {completion, range}); }, }); ``` ```javascript registerCompletion(monaco, editor, { // ... other options onCompletionAccepted: () => { console.log('Completion accepted'); }, }); ``` ```javascript registerCompletion(monaco, editor, { // ... other options onCompletionRejected: () => { console.log('Completion rejected'); }, }); ``` -------------------------------- ### Implement FastAPI completion endpoint Source: https://context7.com/arshad-yaseen/monacopilot/llms.txt Sets up a POST endpoint to receive completion requests and forward them to the Mistral Codestral API. ```python from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware import httpx app = FastAPI() app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"]) @app.post('/code-completion') async def handle_completion(request: Request): try: body = await request.json() metadata = body['completionMetadata'] prompt = f"""Complete the following {metadata['language']} code: {metadata['textBeforeCursor']} {metadata['textAfterCursor']} Provide only the completion code without explanations.""" # Call your LLM provider here async with httpx.AsyncClient() as client: response = await client.post( 'https://api.mistral.ai/v1/fim/completions', headers={'Authorization': f'Bearer {MISTRAL_API_KEY}'}, json={ 'model': 'codestral-latest', 'prompt': metadata['textBeforeCursor'], 'suffix': metadata['textAfterCursor'] } ) result = response.json() return { 'completion': result['choices'][0]['message']['content'], 'error': None } except Exception as e: return {'completion': None, 'error': str(e)} ``` -------------------------------- ### Registering Completions with Technologies Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/configuration/register-options.md Configure Monacopilot to provide completions tailored to specific technologies like React, Next.js, and Tailwind CSS. ```APIDOC ## Register Completion with Technologies ### Description Enable completions tailored to specific technologies by using the `technologies` option. ### Method `registerCompletion(monaco, editor, options)` ### Parameters #### Request Body - **technologies** (string[]) - Required - An array of strings specifying the technologies for which to provide completions. ### Request Example ```javascript registerCompletion(monaco, editor, { technologies: ['react', 'next.js', 'tailwindcss'], }); ``` ### Response N/A (This is a configuration step) ``` -------------------------------- ### Manually Trigger Completions with Keyboard Shortcut Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/configuration/register-options.md Set up a keyboard shortcut (Ctrl+Shift+Space) to manually trigger code completions when the 'onDemand' trigger is used. ```javascript const completion = registerCompletion(monaco, editor, { trigger: 'onDemand', }); editor.addCommand( monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.Space, () => { completion.trigger(); }, ); ``` -------------------------------- ### Customize Context for Code Completion Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/advanced/custom-prompt.md This snippet demonstrates how to customize only the context provided to the AI for code completion, based on project information like language, technologies, and filename. Ensure the `technologies` array is correctly populated if used. ```javascript // Only customize the context based on project information copilot.complete({ options: { customPrompt: ({language, technologies, filename}) => ({ context: `This is a ${language} file named ${filename} in a project using ${technologies?.join(', ')}. The code follows a functional programming paradigm with strict typing.`, }), }, }); ``` -------------------------------- ### Create API route for code completion Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/examples/nextjs.md Set up an API endpoint to handle completion requests from the editor. ```typescript // app/api/code-completion/route.ts import {NextRequest, NextResponse} from 'next/server'; import {CompletionCopilot, type CompletionRequestBody} from 'monacopilot'; const copilot = new CompletionCopilot(process.env.MISTRAL_API_KEY, { provider: 'mistral', model: 'codestral', }); export async function POST(req: NextRequest) { const body: CompletionRequestBody = await req.json(); const completion = await copilot.complete({ body, }); return NextResponse.json(completion, {status: 200}); } ``` ```typescript // pages/api/code-completion.ts import {NextApiRequest, NextApiResponse} from 'next'; import {CompletionCopilot} from 'monacopilot'; const copilot = new CompletionCopilot(process.env.MISTRAL_API_KEY, { provider: 'mistral', model: 'codestral', }); export default async function handler( req: NextApiRequest, res: NextApiResponse, ) { const completion = await copilot.complete({ body: req.body, }); res.status(200).json(completion); } ``` -------------------------------- ### Register Completion with Filename Context Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/configuration/register-options.md Specify the `filename` option to provide context about the current file, leading to more relevant code completions. ```javascript registerCompletion(monaco, editor, { filename: 'utils.js', // e.g., "index.js", "utils/objects.js" }); ``` -------------------------------- ### Python FastAPI Completion Handler Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/advanced/cross-language.md A basic implementation of a POST endpoint for code completion using FastAPI. ```python from fastapi import FastAPI, Request app = FastAPI() @app.post('/code-completion') async def handle_completion(request: Request): try: body = await request.json() metadata = body['completionMetadata'] prompt = f"""Please complete the following {metadata['language']} code: {metadata['textBeforeCursor']} {metadata['textAfterCursor']} Use modern {metadata['language']} practices and hooks where appropriate. Please provide only the completed part of the code without additional comments or explanations.""" # Simulate a response from a model response = "Your model's response here" return { 'completion': response, 'error': None } except Exception as e: return { 'completion': None, 'error': str(e) } ``` -------------------------------- ### Format Prompts for Chat-based Models Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/advanced/custom-model.md Use these structures when interacting with chat-based APIs like OpenAI or Anthropic. Ensure the prompt object contains context, instruction, and file content fields. ```javascript // OpenAI format messages: [ {role: 'system', content: prompt.context}, { role: 'user', content: `${prompt.instruction}\n\n${prompt.fileContent}`, }, ]; // Anthropic format system: prompt.context, messages: [ { role: 'user', content: `${prompt.instruction}\n\n${prompt.fileContent}`, }, ]; ``` -------------------------------- ### Configure completion caching Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/configuration/register-options.md Toggle the enableCaching option to control whether completions are reused based on context and cursor position. ```javascript registerCompletion(monaco, editor, { enableCaching: false, }); ``` -------------------------------- ### Configure Manual Completion Triggers Source: https://context7.com/arshad-yaseen/monacopilot/llms.txt Use keyboard shortcuts or editor actions to trigger completions on demand instead of automatically. ```typescript import { registerCompletion } from 'monacopilot'; const completion = registerCompletion(monaco, editor, { language: 'javascript', endpoint: '/api/code-completion', trigger: 'onDemand' // Disable automatic completions }); // Trigger with Ctrl+Shift+Space editor.addCommand( monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.Space, () => completion.trigger() ); // Or add as an editor action (appears in context menu) monaco.editor.addEditorAction({ id: 'monacopilot.triggerCompletion', label: 'Complete Code', contextMenuGroupId: 'navigation', keybindings: [ monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.Space ], run: () => completion.trigger() }); ``` -------------------------------- ### Configuring Max Context Lines Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/configuration/register-options.md Manage the number of lines included in completion requests to control costs and accuracy. ```APIDOC ## Max Context Lines ### Description Limit the number of lines included in the completion request using the `maxContextLines` option to manage potentially lengthy code in your editor. ### Method `registerCompletion(monaco, editor, options)` ### Parameters #### Request Body - **maxContextLines** (number) - Optional - The maximum number of lines to include in the completion request. Defaults to 100. ### Request Example ```javascript registerCompletion(monaco, editor, { maxContextLines: 60, }); ``` ### Response N/A (This is a configuration step) ``` -------------------------------- ### Update custom model integration Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/guides/upgrade-to-v1.md Update the custom model configuration to handle the new prompt structure containing context, instruction, and fileContent. ```javascript // Before const copilot = new CompletionCopilot(API_KEY, { model: { config: (apiKey, prompt) => ({ endpoint: 'https://your-api-endpoint.com', body: { inputs: prompt.user, // other parameters }, // headers }), transformResponse: response => ({text: response.generated_text}), }, }); // After const copilot = new CompletionCopilot(API_KEY, { model: { config: (apiKey, prompt) => ({ endpoint: 'https://your-api-endpoint.com', body: { // The prompt now has context, instruction, and fileContent inputs: `${prompt.context}\n\n${prompt.instruction}\n\n${prompt.fileContent}`, // other parameters }, // headers }), transformResponse: response => ({text: response.generated_text}), }, }); ``` -------------------------------- ### Register Completion with 'onTyping' Trigger Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/configuration/register-options.md Use the 'onTyping' trigger for real-time code completions as the user types. This is recommended for Mistral models to avoid rate limit errors. ```javascript registerCompletion(monaco, editor, { trigger: 'onTyping', }); ``` -------------------------------- ### Implement Editor Component with Monacopilot Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/examples/tanstack-start.md Create a React component that integrates the Monaco Editor and registers Monacopilot for code completions. Ensure the completion registration is deregistered on component unmount. ```typescript import { useEffect, useRef } from 'react' import MonacoEditor from '@monaco-editor/react' import { registerCompletion, type CompletionRegistration, type Monaco, type StandaloneCodeEditor, } from 'monacopilot' export default function Editor() { const completionRef = useRef(null) const handleMount = (editor: StandaloneCodeEditor, monaco: Monaco) => { completionRef.current = registerCompletion(monaco, editor, { endpoint: '/api/code-completion', language: 'javascript', }) } useEffect(() => { return () => { completionRef.current?.deregister() } }, []) return ( ) } ``` -------------------------------- ### Implement Browser-Only Completions Source: https://context7.com/arshad-yaseen/monacopilot/llms.txt Handle completion requests directly in the browser. Note that this exposes API keys and is intended for testing or internal tools. ```javascript import { registerCompletion, CompletionCopilot } from 'monacopilot'; // WARNING: Exposes API key in client-side code - use only for testing const copilot = new CompletionCopilot('your-mistral-api-key', { provider: 'mistral', model: 'codestral' }); const completion = registerCompletion(monaco, editor, { language: 'javascript', requestHandler: async ({ body }) => { return await copilot.complete({ body }); } }); ``` -------------------------------- ### Prompt Data Structure for Custom Models Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/advanced/custom-model.md The 'prompt' parameter passed to the custom model function includes context, instruction, and file content for the AI model. ```typescript interface PromptData { /** * Contextual information about the code environment * @example filename, technologies, etc. */ context: string; /** * Instructions for the AI model on how to generate the completion */ instruction: string; /** * The content of the file being edited */ fileContent: string; } ``` -------------------------------- ### Control follow-up completions Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/configuration/register-options.md Use allowFollowUpCompletions to enable or disable automatic generation of new suggestions after a user accepts one. ```javascript registerCompletion(monaco, editor, { allowFollowUpCompletions: false, }); ``` -------------------------------- ### Completion Event Handlers Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/configuration/register-options.md Utilize event handlers to respond to various stages of the completion process. ```APIDOC ## Completion Event Handlers ### Description The editor provides several events to handle completion suggestions. These events allow you to respond to different stages of the completion process. ### `onCompletionShown` Event #### Description This event is triggered when a completion suggestion is shown to the user. #### Method `registerCompletion(monaco, editor, options)` #### Parameters ##### Request Body - **onCompletionShown** (function) - Optional - A callback function that is executed when a completion is shown. It receives `completion` and `range` as arguments. - `completion` (string): The completion text being shown. - `range` (monaco.Range): The editor range object where the completion will be inserted. #### Request Example ```javascript registerCompletion(monaco, editor, { onCompletionShown: (completion, range) => { console.log('Completion suggestion:', {completion, range}); }, }); ``` ### `onCompletionAccepted` Event #### Description Event triggered when a completion suggestion is accepted by the user. #### Method `registerCompletion(monaco, editor, options)` #### Parameters ##### Request Body - **onCompletionAccepted** (function) - Optional - A callback function that is executed when a completion is accepted. #### Request Example ```javascript registerCompletion(monaco, editor, { onCompletionAccepted: () => { console.log('Completion accepted'); }, }); ``` ### `onCompletionRejected` Event #### Description Event triggered when a completion suggestion is rejected by the user. #### Method `registerCompletion(monaco, editor, options)` #### Parameters ##### Request Body - **onCompletionRejected** (function) - Optional - A callback function that is executed when a completion is rejected. #### Request Example ```javascript registerCompletion(monaco, editor, { onCompletionRejected: () => { console.log('Completion rejected'); }, }); ``` ### Response N/A (These are event handlers) ``` -------------------------------- ### Integrate with Next.js App Router Source: https://context7.com/arshad-yaseen/monacopilot/llms.txt Set up a server-side API route and a client-side React component to handle code completions. ```typescript // app/api/code-completion/route.ts import { NextRequest, NextResponse } from 'next/server'; import { CompletionCopilot, type CompletionRequestBody } from 'monacopilot'; const copilot = new CompletionCopilot(process.env.MISTRAL_API_KEY, { provider: 'mistral', model: 'codestral' }); export async function POST(req: NextRequest) { const body: CompletionRequestBody = await req.json(); const completion = await copilot.complete({ body }); return NextResponse.json(completion, { status: 200 }); } ``` ```tsx // components/Editor.tsx 'use client'; import { useEffect, useRef } from 'react'; import MonacoEditor from '@monaco-editor/react'; import { registerCompletion, type CompletionRegistration, type Monaco, type StandaloneCodeEditor } from 'monacopilot'; export default function Editor() { const completionRef = useRef(null); const handleMount = (editor: StandaloneCodeEditor, monaco: Monaco) => { completionRef.current = registerCompletion(monaco, editor, { endpoint: '/api/code-completion', language: 'javascript', technologies: ['react', 'nextjs'], filename: 'App.tsx' }); }; useEffect(() => { return () => completionRef.current?.deregister(); }, []); return ( ); } ``` -------------------------------- ### Pull Request Verification Checks Source: https://github.com/arshad-yaseen/monacopilot/blob/main/CONTRIBUTING.md Commands to run before submitting a pull request. ```bash pnpm tsc pnpm lint pnpm format pnpm test ``` -------------------------------- ### Register Completion with onCompletionRequested Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/configuration/register-options.md Use this event to track when a completion request is initiated. Access request parameters like endpoint and metadata. ```javascript registerCompletion(monaco, editor, { // ... other options onCompletionRequested: params => { console.log('Completion requested:', { endpoint: params.endpoint, metadata: params.body.completionMetadata, }); }, }); ``` -------------------------------- ### Register Completion Endpoint Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/advanced/cross-language.md Configuration to register the custom API endpoint with the Monacopilot editor instance. ```javascript registerCompletion(monaco, editor, { endpoint: 'https://my-python-api.com/code-completion', // ... other options }); ``` -------------------------------- ### Update completion options dynamically Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/configuration/register-options.md Use the updateOptions method at runtime to modify configuration without re-registering the completion instance. ```javascript const completion = registerCompletion(monaco, editor, { language: 'javascript', endpoint: '/api/code-completion', }); // Later, update options when needed: completion.updateOptions((currentOptions) => ({ relatedFiles: [ ...currentOptions.relatedFiles, { path: './newFile.js', content: 'export function newFunction() { return "hello world"; }', }, ], })); ``` -------------------------------- ### Custom Error Handling Source: https://github.com/arshad-yaseen/monacopilot/blob/main/docs/configuration/register-options.md Implement custom error handling logic instead of relying on default console logging. ```APIDOC ## Handling Errors ### Description Provide a callback function to handle errors that occur during the completion process. This will disable the default console logging. ### Method `registerCompletion(monaco, editor, options)` ### Parameters #### Request Body - **onError** (function) - Optional - A callback function that receives the error object. It is called when an error occurs. ### Request Example ```javascript registerCompletion(monaco, editor, { onError: error => { console.error(error); }, }); ``` ### Response N/A (This is a configuration step) ```