### Install Dependencies Source: https://monacopilot.dev/examples/vanilla-js.html Command to initialize the project and install required packages. ```bash npm init -y npm install express cors monacopilot dotenv ``` -------------------------------- ### Install Monacopilot with bun Source: https://monacopilot.dev/ Install the Monacopilot package using bun. ```bash bun add monacopilot ``` -------------------------------- ### Install Monacopilot with yarn Source: https://monacopilot.dev/ Install the Monacopilot package using yarn. ```bash yarn add monacopilot ``` -------------------------------- ### Install Project Dependencies Source: https://monacopilot.dev/examples/remix.html Install all project dependencies before running the development server. ```bash npm install ``` ```bash yarn ``` ```bash pnpm install ``` ```bash bun install ``` -------------------------------- ### Start Development Server with npm Source: https://monacopilot.dev/examples/sveltekit.html Use this command to start the development server using npm. ```bash npm run dev ``` -------------------------------- ### Install Monacopilot with pnpm Source: https://monacopilot.dev/ Install the Monacopilot package using pnpm. ```bash pnpm add monacopilot ``` -------------------------------- ### Install Monacopilot with npm Source: https://monacopilot.dev/ Install the Monacopilot package using npm. ```bash npm install monacopilot ``` -------------------------------- ### Start Development Server Source: https://monacopilot.dev/examples/remix.html Launch the Remix development server. ```bash npm run dev ``` ```bash yarn dev ``` ```bash pnpm dev ``` ```bash bun dev ``` -------------------------------- ### Start Development Server with bun Source: https://monacopilot.dev/examples/sveltekit.html Use this command to start the development server using bun. ```bash bun dev ``` -------------------------------- ### Run Application Source: https://monacopilot.dev/examples/vanilla-js.html Commands to start the backend server and serve the frontend. ```bash node server.js ``` ```bash npx serve ``` -------------------------------- ### Start Development Server Source: https://monacopilot.dev/examples/gatsby.html Launch the Gatsby development server. ```bash npm run develop ``` ```bash yarn develop ``` ```bash pnpm develop ``` ```bash bun develop ``` -------------------------------- ### Install Monacopilot Dependencies Source: https://monacopilot.dev/examples/remix.html Install the required packages for Monacopilot and the Monaco editor integration. ```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 ``` -------------------------------- ### Start Development Server with pnpm Source: https://monacopilot.dev/examples/sveltekit.html Use this command to start the development server using pnpm. ```bash pnpm run dev ``` -------------------------------- ### Start Development Server with yarn Source: https://monacopilot.dev/examples/sveltekit.html Use this command to start the development server using yarn. ```bash yarn dev ``` -------------------------------- ### Install Dependencies with bun Source: https://monacopilot.dev/examples/sveltekit.html Use this command to install project dependencies using bun. ```bash bun install ``` -------------------------------- ### Install Dependencies with npm Source: https://monacopilot.dev/examples/sveltekit.html Use this command to install project dependencies using npm. ```bash npm install ``` -------------------------------- ### Install Dependencies with pnpm Source: https://monacopilot.dev/examples/sveltekit.html Use this command to install project dependencies using pnpm. ```bash pnpm install ``` -------------------------------- ### Install Dependencies with yarn Source: https://monacopilot.dev/examples/sveltekit.html Use this command to install project dependencies using yarn. ```bash yarn ``` -------------------------------- ### Implement custom prompt for React components Source: https://monacopilot.dev/advanced/custom-prompt.html Example of using completion metadata to dynamically generate 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}, }); ``` -------------------------------- ### Monacopilot Browser-Only Setup Source: https://monacopilot.dev/guides/browser-only.html Instantiates `CompletionCopilot` and registers a completion handler using `requestHandler` for direct browser-based requests. This approach is not secure for production environments. ```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; }, }); ``` -------------------------------- ### Express.js API Handler for Completions Source: https://monacopilot.dev/ Example Express.js server to handle completion requests from Monacopilot. Requires MISTRAL_API_KEY and PORT environment variables. ```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); ``` -------------------------------- ### Update Monacopilot dependency Source: https://monacopilot.dev/guides/upgrade-to-v1.html Install the v1.0.0 version of the package via npm. ```bash npm install monacopilot@1.0.0 ``` -------------------------------- ### Python FastAPI Example for Code Completion API Source: https://monacopilot.dev/advanced/cross-language.html A basic implementation of a code completion endpoint using Python and FastAPI. It constructs a prompt based on provided metadata and simulates a model response. ```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) } ``` -------------------------------- ### Prompt Data Return Structure Source: https://monacopilot.dev/advanced/custom-prompt.html The `customPrompt` function should return a `PromptData` object (or a partial one) to guide the code completion. ```APIDOC ## Prompt Data Return Structure ### Description An object returned by the `customPrompt` function, specifying how the AI should generate code completions. ### Properties - **context** (string | undefined) - Information about the codebase context, including technologies, filename, language, etc. - **instruction** (string | undefined) - Instructions for how the AI should complete the code after the cursor position. - **fileContent** (string | undefined) - The representation of the file content showing where the cursor is positioned for completion. ``` -------------------------------- ### Register Custom Completion Endpoint in Monacopilot Source: https://monacopilot.dev/advanced/cross-language.html Example of how to register a custom code completion endpoint with Monacopilot using JavaScript. ```javascript registerCompletion(monaco, editor, { endpoint: 'https://my-python-api.com/code-completion', // ... other options }); ``` -------------------------------- ### Integrate Custom Model with Anthropic SDK Source: https://monacopilot.dev/advanced/custom-model.html Example of using the Anthropic client SDK to connect Claude models to Monacopilot. Ensure your Anthropic API key is set in environment variables. The model function processes the prompt and returns the completion text. ```javascript import Anthropic from '@anthropic-ai/sdk'; const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY, }); const copilot = new CompletionCopilot(undefined, { model: async prompt => { const completion = await anthropic.messages.create({ model: 'claude-3-5-haiku-latest', max_tokens: 1024, messages: [ {role: 'system', content: prompt.context}, { role: 'user', content: `${prompt.instruction}\n\n${prompt.fileContent}`, }, ], temperature: 0.1, }); return { text: completion.content[0].text, }; }, }); ``` -------------------------------- ### Register Completion with Custom Request Handler Source: https://monacopilot.dev/advanced/custom-request-handler.html Use the `requestHandler` option when registering a completion to intercept and modify outgoing requests. This example shows how to add custom headers and additional data to the request body before sending it to the completion API. ```javascript registerCompletion(monaco, editor, { language: 'javascript', requestHandler: async ({ body }) => { const response = await fetch('https://your-api-url.com/code-completion', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Custom-Header': 'custom-value' }, body: JSON.stringify({ ...body, additionalData: { userId: 'user-123', projectId: 'project-456' } }) }); return await response.json(); } }); ``` -------------------------------- ### Apply partial custom prompt configurations Source: https://monacopilot.dev/advanced/custom-prompt.html Demonstrates how to override only specific parts of the prompt, such as instructions or context, while leaving others to default. ```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.', }), }, }); // 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.`, }), }, }); ``` -------------------------------- ### Configure Environment Variables Source: https://monacopilot.dev/examples/remix.html Set the API key in the project root .env file. ```bash MISTRAL_API_KEY=your_mistral_api_key_here ``` -------------------------------- ### Configure Environment Variables Source: https://monacopilot.dev/examples/vanilla-js.html Environment configuration file for API keys. ```bash MISTRAL_API_KEY=your_api_key_here ``` -------------------------------- ### Initialize Frontend Editor Source: https://monacopilot.dev/examples/vanilla-js.html Frontend script to initialize the Monaco Editor and register the Monacopilot completion service. ```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(); }); }); ``` -------------------------------- ### Configure custom prompt in copilot.complete Source: https://monacopilot.dev/advanced/custom-prompt.html Basic implementation of the customPrompt function to override context, instructions, and file content. ```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', }), }, }); ``` -------------------------------- ### Format Prompts for Completion Models Source: https://monacopilot.dev/advanced/custom-model.html Use this format for completion-based models. It combines context, file content, and instructions into a single prompt string. ```javascript // Single prompt format prompt: `Context: ${prompt.context}\nFile: ${prompt.fileContent}\nTask: ${prompt.instruction}`; ``` -------------------------------- ### Initialize CompletionCopilot with Mistral Provider Source: https://monacopilot.dev/configuration/copilot-options.html Instantiate `CompletionCopilot` specifying the Mistral provider and the `codestral` model. Ensure the Mistral API key is set in the environment variables. ```javascript const copilot = new CompletionCopilot(process.env.MISTRAL_API_KEY, { provider: 'mistral', model: 'codestral', }); ``` -------------------------------- ### Implement Editor component Source: https://monacopilot.dev/examples/sveltekit.html Create a Svelte component that initializes the Monaco Editor and registers the Monacopilot completion provider. ```html
``` -------------------------------- ### Create HTML Structure Source: https://monacopilot.dev/examples/vanilla-js.html The main HTML file loading the Monaco Editor and Monacopilot scripts. ```html Monacopilot Example
``` -------------------------------- ### Handle Completion Shown Event Source: https://monacopilot.dev/configuration/register-options.html Use the `onCompletionShown` event to respond when a completion suggestion is displayed to the user. Logs the completion text and insertion range. ```javascript registerCompletion(monaco, editor, { // ... other options onCompletionShown: (completion, range) => { console.log('Completion suggestion:', {completion, range}); }, }); ``` -------------------------------- ### Define Project Structure Source: https://monacopilot.dev/examples/vanilla-js.html The required file layout for a vanilla JavaScript Monacopilot implementation. ```text project/ ├── index.html # Main HTML file with the Monaco Editor ├── app.js # Frontend JavaScript to initialize editor and Monacopilot ├── server.js # Backend server to handle code completion requests ├── .env # Environment variables for API keys └── package.json # Project dependencies ``` -------------------------------- ### Create Editor Component Source: https://monacopilot.dev/examples/nextjs.html 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 ( ); } ``` -------------------------------- ### Register Completion with 'onTyping' Trigger Source: https://monacopilot.dev/configuration/register-options.html Use 'onTyping' to provide code completions in real-time as the user types. This requires the Monaco Editor instance and the completion registration. ```javascript registerCompletion(monaco, editor, { trigger: 'onTyping', }); ``` -------------------------------- ### Initialize CompletionCopilot with a Custom OpenAI Model Source: https://monacopilot.dev/advanced/custom-model.html Use this when connecting to a custom LLM endpoint, such as OpenAI's API. Ensure your API key is securely stored in environment variables. The model function should return an object with a 'text' property. ```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, }; }, }); ``` -------------------------------- ### Follow-Up Completions Source: https://monacopilot.dev/configuration/register-options.html Explains the `allowFollowUpCompletions` option for controlling automatic generation of new completions. ```APIDOC ## Follow-Up Completions By default, Monacopilot will automatically generate a new completion immediately after the user accepts a completion. This feature, controlled by the `allowFollowUpCompletions` option, enhances productivity by providing a continuous flow of suggestions (default: `true`). To disable follow-up completions: ```javascript registerCompletion(monaco, editor, { allowFollowUpCompletions: false, }); ``` When disabled, the system will not automatically generate new completions after accepting one, giving you more control over when completions appear. ``` -------------------------------- ### Include Monacopilot via CDN Source: https://monacopilot.dev/ Include the Monacopilot library in your HTML using a CDN link. ```html ``` -------------------------------- ### Create API route for code completion Source: https://monacopilot.dev/examples/sveltekit.html Define a SvelteKit server route 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); }; ``` -------------------------------- ### Dynamically Updating Options Source: https://monacopilot.dev/configuration/register-options.html Demonstrates how to update completion options at runtime without re-registering. ```APIDOC ## Dynamically Updating Options You can dynamically update completion options after registration using the `updateOptions` method at runtime without needing deregister and register again. ```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"; }', }, ], })); ``` The `updateOptions` method accepts a callback function that receives the current options and returns a partial options object containing only the properties you want to update. ``` -------------------------------- ### Create API Route for Completions Source: https://monacopilot.dev/examples/nextjs.html 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); } ``` -------------------------------- ### Update custom model integration Source: https://monacopilot.dev/guides/upgrade-to-v1.html Adjust 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}), }, }); ``` -------------------------------- ### Provide Multi-File Context for Completions Source: https://monacopilot.dev/configuration/register-options.html Enhance completion relevance by providing context from other files in your project using the `relatedFiles` option. Specify the file path and its content to help Copilot understand the broader codebase. ```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("")', }, ], }); ``` -------------------------------- ### Update environment variables Source: https://monacopilot.dev/guides/upgrade-to-v1.html Replace the OpenAI API key with the Mistral API key. ```bash # Before OPENAI_API_KEY=your_openai_api_key_here # After MISTRAL_API_KEY=your_mistral_api_key_here ``` -------------------------------- ### Implement Editor Component Source: https://monacopilot.dev/examples/remix.html Create a React component that registers the completion service with the Monaco editor instance. ```tsx 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: '/code-completion', language: 'javascript', }); }; useEffect(() => { return () => { completionRef.current?.deregister(); }; }, []); return ; } ``` -------------------------------- ### Handle Completion Accepted Event Source: https://monacopilot.dev/configuration/register-options.html The `onCompletionAccepted` event is triggered when a user accepts a completion suggestion. Logs a confirmation message. ```javascript registerCompletion(monaco, editor, { // ... other options onCompletionAccepted: () => { console.log('Completion accepted'); }, }); ``` -------------------------------- ### Create API Route for Completions Source: https://monacopilot.dev/examples/tanstack-start.html Define a server-side route to handle completion requests using the CompletionCopilot instance. ```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); }, }); ``` -------------------------------- ### Completion Event Handlers Source: https://monacopilot.dev/configuration/register-options.html Details the various event handlers available for responding to completion suggestions. ```APIDOC ## Completion Event Handlers The editor provides several events to handle completion suggestions. These events allow you to respond to different stages of the completion process, such as when a suggestion is shown or accepted by the user. ### `onCompletionShown` This event is triggered when a completion suggestion is shown to the user. You can use this event to log or perform actions when a suggestion is displayed. ```javascript registerCompletion(monaco, editor, { // ... other options onCompletionShown: (completion, range) => { console.log('Completion suggestion:', {completion, range}); }, }); ``` **Parameters:** * `completion` : The completion text that is being shown * `range`: The editor range object where the completion will be inserted ### `onCompletionAccepted` Event triggered when a completion suggestion is accepted by the user. ```javascript registerCompletion(monaco, editor, { // ... other options onCompletionAccepted: () => { console.log('Completion accepted'); }, }); ``` ### `onCompletionRejected` Event triggered when a completion suggestion is rejected by the user. ```javascript registerCompletion(monaco, editor, { // ... other options onCompletionRejected: () => { console.log('Completion rejected'); }, }); ``` ### `onCompletionRequested` Event triggered when a completion is requested, before it is fetched. This allows you to track when completion requests are initiated and access the request parameters. ```javascript registerCompletion(monaco, editor, { // ... other options onCompletionRequested: params => { console.log('Completion requested:', { endpoint: params.endpoint, metadata: params.body.completionMetadata, }); }, }); ``` **Parameters:** * `params` : An object containing: * `endpoint`: The endpoint where the completion request will be sent * `body`: The request body containing completion metadata ``` -------------------------------- ### Update custom prompt implementation Source: https://monacopilot.dev/guides/upgrade-to-v1.html Update the custom prompt interface to use context, instruction, and fileContent fields. ```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', }), }, }); ``` -------------------------------- ### Custom Prompt API Source: https://monacopilot.dev/advanced/custom-prompt.html This section details how to use the `customPrompt` function within the `copilot.complete` method to influence code completions. ```APIDOC ## POST /api/copilot/complete ### Description Allows customization of the prompt used for code completions by providing a `customPrompt` function in the options parameter. ### Method POST ### Endpoint /api/copilot/complete ### Parameters #### Request Body - **options** (object) - Required - Options for the completion request. - **customPrompt** (function) - Optional - A function that returns prompt data. ### 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 (Implicitly returns code completion suggestions based on the provided prompt) ### Error Handling (Details not provided in the source text) ``` -------------------------------- ### Implement API Function Source: https://monacopilot.dev/examples/gatsby.html Create a serverless function in src/api/code-completion.ts to handle completion requests via the Mistral provider. ```typescript import type {GatsbyFunctionRequest, GatsbyFunctionResponse} from 'gatsby'; import {CompletionCopilot, type CompletionRequestBody} from 'monacopilot'; const copilot = new CompletionCopilot(process.env.MISTRAL_API_KEY!, { provider: 'mistral', model: 'codestral', }); export async function handler( req: GatsbyFunctionRequest, res: GatsbyFunctionResponse, ) { if (req.method !== 'POST') { res.status(405).json({error: 'Method not allowed'}); return; } try { const body: CompletionRequestBody = JSON.parse(req.body); const completion = await copilot.complete({body}); res.status(200).json(completion); } catch (error) { res.status(500).json({error: 'Internal Server Error', details: error}); } } ``` -------------------------------- ### Use Editor component in page Source: https://monacopilot.dev/examples/sveltekit.html Integrate the custom Editor component into a SvelteKit page. ```html

Monacopilot SvelteKit Example

``` -------------------------------- ### Format Prompts for Chat Models Source: https://monacopilot.dev/advanced/custom-model.html Use this format for chat-based models like OpenAI and Anthropic. It structures the prompt into system and user messages. ```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}`, }, ]; ``` -------------------------------- ### Create Editor Component Source: https://monacopilot.dev/examples/gatsby.html Define a React component that initializes the Monaco Editor and registers the completion service. ```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 ; } ``` -------------------------------- ### Trigger Completions with Keyboard Shortcut Source: https://monacopilot.dev/configuration/register-options.html Configure completions to trigger manually using a keyboard shortcut (Ctrl+Shift+Space) when the trigger mode is set to 'onDemand'. This requires the editor instance and the `completion.trigger()` method. ```javascript const completion = registerCompletion(monaco, editor, { trigger: 'onDemand', }); editor.addCommand( monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyMod.KeyCode.Space, () => { completion.trigger(); }, ); ``` -------------------------------- ### Implement Backend API Handler Source: https://monacopilot.dev/examples/vanilla-js.html Express server implementation to process code completion requests. ```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}`); }); ``` -------------------------------- ### Specify Filename for Contextual Completions Source: https://monacopilot.dev/configuration/register-options.html Improve completion accuracy by specifying the current filename using the `filename` option. This helps tailor suggestions to the specific file's context. ```javascript registerCompletion(monaco, editor, { filename: 'utils.js', // e.g., "index.js", "utils/objects.js" }); ``` -------------------------------- ### Dynamically Update Completion Options Source: https://monacopilot.dev/configuration/register-options.html Update completion options after registration using the `updateOptions` method. It accepts a callback that returns partial options to update. ```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"; }', }, ], })); ``` -------------------------------- ### Caching Completions Source: https://monacopilot.dev/configuration/register-options.html Details how to enable or disable the caching of completions to improve performance. ```APIDOC ## Caching Completions Monacopilot caches completions by default, reusing cached completions when the context and cursor position match while editing (default: `true`). To disable caching: ```javascript registerCompletion(monaco, editor, { enableCaching: false, }); ``` ``` -------------------------------- ### Completion Metadata Object Source: https://monacopilot.dev/advanced/custom-prompt.html The `completionMetadata` object passed to the `customPrompt` function provides context about the current editor state. ```APIDOC ## Completion Metadata Structure ### Description An object containing information about the current editor state, used to tailor the custom prompt. ### Properties - **language** (string | undefined) - The programming language of the code being completed. - **cursorPosition** ({ lineNumber: number; column: number }) - The current cursor position where the completion should begin. - **filename** (string | undefined) - The name of the file being edited. Only available if provided in `registerCompletion`. - **technologies** (string[] | undefined) - An array of technologies used in the project. Only available if provided in `registerCompletion`. - **relatedFiles** (object[] | undefined) - An array of objects containing the `path` and `content` of related files. Only available if provided in `registerCompletion`. - **textAfterCursor** (string) - The text that appears after the cursor position. - **textBeforeCursor** (string) - The text that appears before the cursor position. ``` -------------------------------- ### Update server-side CompletionCopilot configuration Source: https://monacopilot.dev/guides/upgrade-to-v1.html Migrate the provider and model configuration from OpenAI to Mistral's 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', }); ``` -------------------------------- ### Register Monacopilot Completion Source: https://monacopilot.dev/ Register the AI completion service with your Monaco Editor instance. Ensure the endpoint URL points to your API handler. ```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', }); ``` -------------------------------- ### Server-Side Endpoint Implementation Source: https://monacopilot.dev/advanced/custom-request-handler.html This server-side code demonstrates how to receive a modified request from the `requestHandler`. It accesses custom headers and additional data from the request body, then uses `copilot.complete()` to generate a completion. ```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); }); ``` -------------------------------- ### Manually Trigger Completions with 'onDemand' Source: https://monacopilot.dev/configuration/register-options.html Set the trigger to 'onDemand' to disable automatic completions and enable manual triggering via the `completion.trigger()` method. This provides precise control over when suggestions appear. ```javascript const completion = registerCompletion(monaco, editor, { trigger: 'onDemand', }); completion.trigger(); ``` -------------------------------- ### Create Page Component Source: https://monacopilot.dev/examples/remix.html Integrate the Editor component into a Remix route. ```tsx import Editor from '~/components/Editor'; export default function Index() { return (

Monacopilot Remix Example

); } ``` -------------------------------- ### Handle Completion Rejected Event Source: https://monacopilot.dev/configuration/register-options.html Use the `onCompletionRejected` event to detect when a user rejects a completion suggestion. Logs a rejection message. ```javascript registerCompletion(monaco, editor, { // ... other options onCompletionRejected: () => { console.log('Completion rejected'); }, }); ``` -------------------------------- ### Max Context Lines Source: https://monacopilot.dev/configuration/register-options.html Explains how to limit the number of lines included in the completion request to manage editor code length and costs. ```APIDOC ## Max Context Lines To manage potentially lengthy code in your editor, you can limit the number of lines included in the completion request using the `maxContextLines` option. By default, this is set to `100` lines. For example, if there's a chance that the code in your editor may exceed `500` lines, you don't need to provide all those lines to the model. This would increase costs due to the huge number of input tokens. You can adjust `maxContextLines` based on how accurate you want the completions to be and how much you're willing to pay for the model. ```javascript registerCompletion(monaco, editor, { maxContextLines: 60, }); ``` ``` -------------------------------- ### Return Formats for Request Handler Source: https://monacopilot.dev/advanced/custom-request-handler.html The `requestHandler` must return a response object. If using `CompletionCopilot`, return the JSON response directly. For custom solutions, return an object with a `completion` property for the text to insert, or an `error` property. ```javascript // If using CompletionCopilot in your endpoint // Simply return the response from your endpoint return await response.json(); ``` ```javascript // If implementing a custom solution // Return an object with either completion or error return { completion: "your completion text", // Text to insert in the editor error: "error message" // Optional error message }; ``` -------------------------------- ### Enable Technology-Specific Completions Source: https://monacopilot.dev/configuration/register-options.html Tailor code completions for specific technologies like React, Next.js, or Tailwind CSS by using the `technologies` option. This ensures more relevant suggestions for the chosen tech stack. ```javascript registerCompletion(monaco, editor, { technologies: ['react', 'next.js', 'tailwindcss'], }); ``` -------------------------------- ### Trigger Completions with Editor Action Source: https://monacopilot.dev/configuration/register-options.html Define a custom editor action to manually trigger code completions. This action is bound to a keyboard shortcut and calls `completion.trigger()` when executed. ```javascript const completion = registerCompletion(monaco, editor, { trigger: 'onDemand', }); monaco.editor.addEditorAction({ id: 'monacopilot.triggerCompletion', label: 'Complete Code', contextMenuGroupId: 'navigation', keybindings: [ monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyMod.KeyCode.Space, ], run: () => { completion.trigger(); }, }); ``` -------------------------------- ### Create API Route for Completions Source: https://monacopilot.dev/examples/remix.html Define a Remix action function to handle completion requests using the Mistral provider. ```tsx import {json, type ActionFunctionArgs} from '@remix-run/node'; import {CompletionCopilot, type CompletionRequestBody} from 'monacopilot'; const copilot = new CompletionCopilot(process.env.MISTRAL_API_KEY, { provider: 'mistral', model: 'codestral', }); export const action = async ({request}: ActionFunctionArgs) => { const body: CompletionRequestBody = await request.json(); const completion = await copilot.complete({body}); return json(completion); }; ``` -------------------------------- ### Handling Errors Source: https://monacopilot.dev/configuration/register-options.html Describes how Monacopilot handles errors by default and how to provide a custom error handler. ```APIDOC ## Handling Errors When an error occurs during the completion process or requests, Monacopilot will log it to the console by default rather than throwing errors. This ensures smooth editing even when completions are unavailable. You can provide this callback to handle errors yourself, which will disable the default console logging. ```javascript registerCompletion(monaco, editor, { onError: error => { console.error(error); }, }); ``` ``` -------------------------------- ### Create Page Component Source: https://monacopilot.dev/examples/gatsby.html Integrate the Editor component into a Gatsby page. ```typescript import * as React from "react"; import Editor from "../components/Editor"; export default function IndexPage() { return (

Monacopilot Gatsby Example

); } ``` -------------------------------- ### Handle Completion Requested Event Source: https://monacopilot.dev/configuration/register-options.html The `onCompletionRequested` event fires before a completion request is fetched. It allows tracking request initiation and accessing parameters like endpoint and metadata. ```javascript registerCompletion(monaco, editor, { // ... other options onCompletionRequested: params => { console.log('Completion requested:', { endpoint: params.endpoint, metadata: params.body.completionMetadata, }); }, }); ``` -------------------------------- ### Conditional Completion Triggering with triggerIf Source: https://monacopilot.dev/configuration/register-options.html Allows custom logic to control when code completions are triggered based on the current editor state. ```APIDOC ## Option: triggerIf ### Description Control when completions are triggered based on custom conditions using the `triggerIf` option. ### Parameters #### `triggerIf` Function Parameters - **text** (string) - The current text in the editor. - **position** (object) - The current cursor position. - **column** (number) - The column number of the cursor. - **triggerType** (string) - The type of trigger that initiated the completion ('onIdle', 'onTyping', or 'onDemand'). ### Return Value - `true`: To allow the completion to be triggered. - `false`: To prevent the completion from being triggered. ### Request Example ```javascript registerCompletion(monaco, editor, { // ... other options triggerIf: ({text, position, triggerType}) => { // Only trigger completions when cursor is at the beginning of a line return position.column === 1; }, }); ``` ``` -------------------------------- ### Prompt Data Structure for Custom Models Source: https://monacopilot.dev/advanced/custom-model.html The structure of the prompt object passed to your custom model function. It includes contextual information, instructions, and the content of the file being edited. ```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; } ``` -------------------------------- ### Limit Context Lines for Completions Source: https://monacopilot.dev/configuration/register-options.html Manage lengthy code in the editor by limiting lines in completion requests using `maxContextLines`. Default is 100. Adjust based on desired accuracy and cost. ```javascript registerCompletion(monaco, editor, { maxContextLines: 60, }); ``` -------------------------------- ### Handle completion request completion Source: https://monacopilot.dev/configuration/register-options.html Use onCompletionRequestFinished to access request parameters and the resulting completion response after a request finishes. ```javascript registerCompletion(monaco, editor, { // ... other options onCompletionRequestFinished: (params, response) => { console.log('Completion request finished:', { endpoint: params.endpoint, metadata: params.body.completionMetadata, completion: response.completion }); }, }); ``` -------------------------------- ### Disable Follow-Up Completions Source: https://monacopilot.dev/configuration/register-options.html Control automatic generation of new completions after acceptance using `allowFollowUpCompletions`. Set to `false` to disable. ```javascript registerCompletion(monaco, editor, { allowFollowUpCompletions: false, }); ``` -------------------------------- ### Disable Follow-up Completions for General Models Source: https://monacopilot.dev/advanced/custom-model.html Set `allowFollowUpCompletions` to `false` when using general-purpose models or models without FIM capabilities to prevent poor quality follow-up suggestions. ```javascript registerCompletion(editor, { // Disable follow-up completions for general-purpose models allowFollowUpCompletions: false, // other options... }); ``` -------------------------------- ### Disable Completion Caching Source: https://monacopilot.dev/configuration/register-options.html Monacopilot caches completions by default. Set `enableCaching` to `false` to disable this behavior and reuse cached completions. ```javascript registerCompletion(monaco, editor, { enableCaching: false, }); ``` -------------------------------- ### Custom Error Handling for Completions Source: https://monacopilot.dev/configuration/register-options.html Provide an `onError` callback to handle completion errors yourself, disabling default console logging. Log errors to the console. ```javascript registerCompletion(monaco, editor, { onError: error => { console.error(error); }, }); ```