### Get Repository Details using Python SDK Source: https://docs.relace.ai/api-reference/repos/get This example illustrates how to retrieve repository details using the Relace AI Python SDK. It involves initializing the client with an API key and then using the `repo.get` method with the repository ID. ```python from relace import Relace client = Relace(api_key = "YOUR_API_KEY") repo_id = "123e4567-e89b-12d3-a456-426614174000" data = client.repo.get(repo_id) print(data) ``` -------------------------------- ### Handle SSE Event Streams Source: https://docs.relace.ai/api-reference/agents/analysis-agent Example of the Server-Sent Events (SSE) format used to stream real-time updates from the agent execution, such as the 'started' event. ```text event: started data: {"prompt_id": "prompt_123e4567-e89b-12d3-a456-426614174000"} event: agent ``` -------------------------------- ### Analyze Agent Tool Usage and Response Stream (SSE) Source: https://docs.relace.ai/api-reference/agents/fast-agentic-search This example shows a Server-Sent Events (SSE) stream representing the output from a Relace AI agent. It includes various event types like 'started', 'agent' (with content and reasoning), and 'tool' (detailing commands executed and their results). This stream allows for real-time monitoring of the agent's execution flow and decision-making process. ```text event: started data: {"prompt_id":"123e4567-e89b-12d3-a456-426614174000"} event: agent data: {"name":"relace-search","content":"I'll explore the codebase to understand where global styles and UI components are defined. Let me first get an overview of the project structure to identify relevant directories and files.\n\n"} event: tool data: {"name":"view_directory","path":"/repo"} event: tool data: {"name":"bash","command":"find /repo -type f -name \"*.css\" -o -name \"*.scss\" -o -name \"*.sass\" -o -name \"*.less\" | head -20"} event: tool data: {"name":"bash","command":"find /repo -type f -name \"*component*\" -o -name \"*ui*\" -o -name \"*style*\" | head -20"} event: tool data: {"name":"bash","command":"grep -r \"global.*style\|style.*global\" /repo --include=\"*.js\" --include=\"*.ts\" --include=\"*.jsx\" --include=\"*.tsx\" | head -10"} event: tool data: {"name":"bash","command":"grep -r \"ThemeProvider\|GlobalStyle\|styled\." /repo --include=\"*.js\" --include=\"*.ts\" --include=\"*.jsx\" --include=\"*.tsx\" | head -10"} event: agent data: {"name":"relace-search","content":"Based on the initial exploration, I can see this appears to be a React project with a structured component system. Let me dive deeper into the key areas that would contain global styles and UI components.\n\n"} event: tool data: {"name":"view_directory","path":"/repo/src/components"} event: tool data: {"name":"view_file","path":"/repo/src/index.css"} event: tool data: {"name":"view_directory","path":"/repo/src/components/ui"} event: tool data: {"name":"view_file","path":"/repo/src/main.tsx"} event: tool data: {"name":"bash","command":"find /repo/src -name \"*.css\" -o -name \"*.scss\" -o -name \"*.sass\" | xargs ls -la"} event: agent ``` -------------------------------- ### POST /v1/repo Source: https://docs.relace.ai/docs/data-analysis/quickstart Creates a new repository from a specified template source to serve as the foundation for your project. ```APIDOC ## POST /v1/repo ### Description Initializes a new repository based on a provided git template URL. ### Method POST ### Endpoint https://api.relace.run/v1/repo ### Request Body - **source** (object) - Required - Contains repository source details - **type** (string) - Required - Source type (e.g., "git") - **url** (string) - Required - Repository URL - **branch** (string) - Required - Target branch ### Request Example { "source": { "type": "git", "url": "https://github.com/squack-io/tailwind-vite-base", "branch": "main" } } ### Response #### Success Response (200) - **repo_id** (string) - The unique identifier for the created repository #### Response Example { "repo_id": "abc-123-xyz" } ``` -------------------------------- ### Initialize and Clone Relace Repo in Sandbox Source: https://docs.relace.ai/docs/repos/sandbox Demonstrates how to provision a sandbox environment, configure git credentials, and clone a Relace repository using an API key. The examples cover both Python with Modal and TypeScript with E2B. ```python import modal app = modal.App.lookup("Sandbox-Example", create_if_missing=True) repo_id = "REPO_ID" relace_api_key = "RELACE_API_TOKEN" # Configure the sandbox image with git image = ( modal.Image.debian_slim(python_version="3.13") .apt_install("git", "curl") .run_commands( "git config --global user.name 'Relace'", "git config --global user.email 'noreply@relace.ai'", ) .workdir("/repo") ) # Create the sandbox sandbox = modal.Sandbox.create(image=image, app=app) clone_url = f"https://token:{relace_api_key}@api.relace.run/v1/repo/{repo_id}.git" # Run git clone inside the sandbox clone_proc = sandbox.exec("git", "clone", clone_url, ".") if clone_proc.wait() != 0: print("Clone failed:", clone_proc.stderr.read()) raise Exception("Clone failed") # Example command to list files in the cloned repo ls_proc = sandbox.exec("ls", "-la") print(ls_proc.stdout.read()) sandbox.terminate() ``` ```typescript import { Sandbox } from "@e2b/code-interpreter"; // Create the sandbox const sandbox = await Sandbox.create(); // Configure git await sandbox.commands.run(`git config --global user.name 'Relace'`); await sandbox.commands.run(`git config --global user.email 'noreply@relace.ai'`); const token = "RELACE_API_KEY"; const repoId = "REPO_ID"; const repoDir = "./repo"; // Clone Relace repo inside the sandbox const cloneResult = await sandbox.commands.run( `git clone https://token:${token}@api.relace.run/v1/repo/${repoId}.git ${repoDir}` ); // Check for clone failure if (cloneResult.exitCode !== 0) { console.error("Clone failed:", cloneResult.stderr); throw new Error(`Failed to clone repository: ${cloneResult.stderr}`); } // Example command to list files in the cloned repo const files = await sandbox.commands.run(`ls -la ${repoDir}`); console.log(files.stdout); ``` -------------------------------- ### List Repositories (cURL) Source: https://docs.relace.ai/api-reference/repos/list Example of fetching a paginated list of repositories using cURL. This demonstrates a direct API call with an authorization header and query parameters for pagination. ```bash curl -X GET "https://api.relace.run/v1/repo?page_size=10" \ -H "Authorization: Bearer YOUR_API_KEY" ``` -------------------------------- ### POST /repo Source: https://docs.relace.ai/docs/fast-agentic-search/quickstart Creates a new repository in Relace, either from a Git source or from uploaded files. This is the first step to enabling Fast Agentic Search. ```APIDOC ## POST /repo ### Description Creates a new repository in Relace, allowing you to transfer your source code for analysis and search. ### Method POST ### Endpoint /repo ### Parameters #### Request Body - **source** (object) - Required - The source of the repository. - **type** (string) - Required - The type of source ('git' or 'files'). - **url** (string) - Optional (if type is 'git') - The URL of the Git repository. - **branch** (string) - Optional (if type is 'git') - The branch to clone from. - **files** (array) - Optional (if type is 'files') - An array of file objects. - **filename** (string) - Required - The name of the file. - **content** (string) - Required - The content of the file. - **auto_index** (boolean) - Optional - Whether to automatically index the repository for semantic search. Defaults to false. - **metadata** (object) - Optional - Custom metadata to associate with the repository. ### Request Example ```json { "source": { "type": "git", "url": "https://github.com/relace-ai/vite-template", "branch": "main" }, "auto_index": true, "metadata": {} } ``` ### Response #### Success Response (200) - **repo_id** (string) - The unique identifier for the created repository. #### Response Example ```json { "repo_id": "repo_12345" } ``` ``` -------------------------------- ### Create Repository with Relace SDK Source: https://docs.relace.ai/docs/fast-agentic-search/quickstart Initializes a repository in Relace using either a Git URL or direct file content. Requires an API key and supports auto-indexing for semantic search capabilities. ```typescript import { Relace } from '@relace-ai/relace'; const client = new Relace({ apiKey: 'YOUR_API_KEY' }); const repo = await client.repo.create({ source: { type: 'git', url: 'https://github.com/relace-ai/vite-template', branch: 'main', }, auto_index: true, metadata: {}, }); console.log(`Repository created with ID: ${repo.repo_id}`); ``` ```typescript import { Relace } from '@relace-ai/relace'; const client = new Relace({ apiKey: 'YOUR_API_KEY' }); const repo = await client.repo.create({ source: { type: 'files', files: [ { filename: 'src/main.py', content: "def main():\n print('Hello from my existing project!')\n\nif __name__ == '__main__':\n main()", } ], }, auto_index: true, metadata: {}, }); console.log(`Repository created with ID: ${repo.repo_id}`); ``` -------------------------------- ### Initiate Agent Search with Relace TypeScript SDK Source: https://docs.relace.ai/api-reference/agents/fast-agentic-search This TypeScript code example shows how to use the Relace SDK to search within a repository. It initializes the Relace client with an API key and then calls the `repo.search` method with a repository ID and a search query. The results are streamed as events, which are then logged to the console. ```typescript import { Relace } from "@relace-ai/relace"; const client = new Relace({ apiKey: "YOUR_API_KEY" }); const repoId = "123e4567-e89b-12d3-a456-426614174000"; const results = client.repo.search(repoId, { query: "Where in the project are global styles and UI components defined?", }); for await (const event of results) { console.log(event); } ``` -------------------------------- ### Configure VS Code MCP Server Source: https://docs.relace.ai/docs/fast-agentic-search/mcp-installation Specific JSON configuration format required for the VS Code MCP user configuration file. ```json { "servers": { "Relace": { "command": "uvx", "args": ["relace-mcp-server"], "env": { "RELACE_API_KEY": "YOUR_API_KEY_HERE" } } } } ``` -------------------------------- ### Get Repository Details using TypeScript SDK Source: https://docs.relace.ai/api-reference/repos/get This code snippet shows how to fetch repository details using the Relace AI TypeScript SDK. It initializes the client with an API key and calls the `get` method with the repository ID. ```typescript import { Relace } from "@relace-ai/relace"; const client = new Relace({ apiKey: "YOUR_API_KEY" }); const repoId = "123e4567-e89b-12d3-a456-426614174000"; const data = await client.repo.get(repoId); console.log(data); ``` -------------------------------- ### POST /v1/code/embed Source: https://docs.relace.ai/docs/embeddings/quickstart Generates vector embeddings for a list of input strings using the Relace embedding model. ```APIDOC ## POST /v1/code/embed ### Description Sends code snippets or text to the Relace embeddings endpoint to retrieve high-dimensional vector representations. ### Method POST ### Endpoint https://embeddings.endpoint.relace.run/v1/code/embed ### Parameters #### Request Body - **model** (string) - Required - The model identifier, e.g., "relace-embed-v1" - **input** (array) - Required - A list of strings to be embedded - **output_dtype** (string) - Optional - The data type of the output, e.g., "float" or "binary" ### Request Example { "model": "relace-embed-v1", "input": ["def add(a, b): return a + b", "class User: pass"] } ### Response #### Success Response (200) - **results** (array) - List of objects containing index and embedding vector - **usage** (object) - Token usage statistics #### Response Example { "results": [ { "index": 0, "embedding": [0.123, 0.456, 0.789] }, { "index": 1, "embedding": [0.234, 0.567, 0.89] } ], "usage": { "total_tokens": 8 } } ``` -------------------------------- ### Store Embeddings in Pinecone (TypeScript) Source: https://docs.relace.ai/docs/embeddings/quickstart An example of how to store generated embeddings in Pinecone, a popular vector database. This involves initializing the Pinecone client, preparing vectors with IDs and metadata, and then upserting them to an index. ```typescript import { Pinecone } from '@pinecone-database/pinecone'; // Initialize Pinecone (example) const pinecone = new Pinecone({ apiKey: "[PINECONE_API_KEY]" }); const index = pinecone.index("my-embeddings-index"); // Prepare vectors for upsert const vectors = embeddings.results.map(r => ({ id: `code-${r.index}`, values: r.embedding, metadata: { source: inputs[r.index] } })); // Upsert to Pinecone await index.upsert(vectors); ``` -------------------------------- ### Get Repository Details using cURL Source: https://docs.relace.ai/api-reference/repos/get This snippet demonstrates how to retrieve details for a specific repository using a cURL command. It requires the repository ID and an API key for authentication. ```bash curl -X GET https://api.relace.run/v1/repo/123e4567-e89b-12d3-a456-426614174000 \ -H "Authorization: Bearer YOUR_API_KEY" ``` -------------------------------- ### Create Relace Repository from Template Source: https://docs.relace.ai/docs/data-analysis/quickstart Initializes a new Relace repository using a public template. This process requires an API key and establishes the base environment for subsequent data analysis tasks. ```python import requests # Create a new repository from the base template url = "https://api.relace.run/v1/repo" headers = { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" } data = { "source": { "type": "git", "url": "https://github.com/squack-io/tailwind-vite-base", "branch": "main" } } response = requests.post(url, headers=headers, json=data) repo = response.json() repo_id = repo['repo_id'] print(f"Repository created with ID: {repo_id}") ``` -------------------------------- ### List Repositories (Python SDK) Source: https://docs.relace.ai/api-reference/repos/list Example of fetching a paginated list of repositories using the Relace AI Python SDK. This provides a Pythonic way to interact with the API, handling request formatting and response parsing. ```python from relace import Relace client = Relace(api_key="YOUR_API_KEY") data = client.repo.list(page_size=10) print(data) ``` -------------------------------- ### List Repositories (TypeScript SDK) Source: https://docs.relace.ai/api-reference/repos/list Example of fetching a paginated list of repositories using the Relace AI TypeScript SDK. This method abstracts the HTTP request and provides a type-safe interface for interacting with the API. ```typescript import { Relace } from "@relace-ai/relace"; const client = new Relace({ apiKey: "YOUR_API_KEY" }); const data = await client.repo.list({ page_size: 10 }); console.log(data); ``` -------------------------------- ### Codebase Exploration Commands Source: https://docs.relace.ai/docs/fast-agentic-search/quickstart Common bash commands used within the agent environment to locate specific architectural patterns such as global styles and theme providers. ```bash find /repo/src -name "*.css" -o -name "*.scss" | xargs ls -la find /repo -name "*theme*" -type f grep -r "ThemeProvider" /repo/src --include="*.tsx" ``` -------------------------------- ### Prepare Code Snippets for Embedding (TypeScript) Source: https://docs.relace.ai/docs/embeddings/quickstart Prepare an array of code snippets or text strings that you want to convert into vector embeddings. This array will be sent to the Relace AI embeddings endpoint. ```typescript const inputs = [ "def add(a, b): return a + b", "class User: pass", // ... more code or text ]; ``` -------------------------------- ### POST /repos Source: https://docs.relace.ai/api-reference/repos/create Creates a new repository by initializing it from files, a GitHub URL, or an existing Relace repository. ```APIDOC ## POST /repos ### Description Create a new repository from various sources. This endpoint allows for flexible initialization including file uploads, git cloning, or cloning existing Relace repositories. ### Method POST ### Endpoint /repos ### Parameters #### Request Body - **source** (object) - Optional - Configuration for initializing the repo. - **type** (string) - Required - The source type: "files", "git", or "relace". - **files** (array) - Required (if type=files) - Array of objects with "filename" and "content". - **url** (string) - Required (if type=git) - Git repository URL. - **branch** (string) - Optional (if type=git) - Specific branch to clone. - **shallow** (boolean) - Optional - Whether to perform a shallow clone (default: true). - **repo_id** (string) - Required (if type=relace) - ID of the template repository. - **metadata** (object) - Optional - Custom key-value pairs for repository metadata. - **auto_index** (boolean) - Optional - Enable automatic code indexing (default: false). ### Request Example { "source": { "type": "git", "url": "https://github.com/user/repo.git", "branch": "main" }, "auto_index": true } ### Response #### Success Response (200) - **id** (string) - The unique identifier of the created repository. - **status** (string) - Current status of the repository creation process. #### Response Example { "id": "repo_12345", "status": "created" } ``` -------------------------------- ### Add Relace MCP to Claude Code Source: https://docs.relace.ai/docs/fast-agentic-search/mcp-installation Command-line instruction to add the Relace MCP server to the Claude Code environment. ```bash claude mcp add Relace --scope user --env RELACE_API_KEY=YOUR_API_KEY_HERE -- uvx relace-mcp-server ``` -------------------------------- ### Create a new repository Source: https://docs.relace.ai/api-reference/repos/create Initializes a new repository by providing a source object containing file contents and repository metadata. The operation returns a unique repository identifier and the current commit hash. ```bash curl -X POST https://api.relace.run/v1/repo \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "source": { "type": "files", "files": [ { "filename": "src/search.ts", "content": "function findItem(array: Item[], targetId: string): Item | undefined {\n for (let i = 0; i < array.length; i++) {\n const item = array[i];\n if (item.id === targetId) {\n return item;\n }\n }\n return undefined;\n}" }, { "filename": "src/types.ts", "content": "interface Item {\n id: string;\n value: string;\n metadata?: Record;\n}" } ] }, "metadata": { "name": "my-codebase", "id": "my-internal-id" } }' ``` ```typescript import { Relace } from "@relace-ai/relace"; const client = new Relace({ apiKey: "YOUR_API_KEY" }); const result = await client.repo.create({ source: { type: "files", files: [ { filename: "src/search.ts", content: "function findItem(array: Item[], targetId: string): Item | undefined {\n for (let i = 0; i < array.length; i++) {\n const item = array[i];\n if (item.id === targetId) {\n return item;\n }\n }\n return undefined;\n}" }, { filename: "src/types.ts", content: "interface Item {\n id: string;\n value: string;\n metadata?: Record;\n}" } ] }, metadata: { name: "my-codebase", id: "my-internal-id" } }); console.log(result); ``` ```python from relace import Relace client = Relace(api_key="YOUR_API_KEY") result = client.repo.create( source={ "type": "files", "files": [ { "filename": "src/search.ts", "content": ( "function findItem(array: Item[], targetId: string): Item | undefined {\n" " for (let i = 0; i < array.length; i++) {\n" " const item = array[i];\n" " if (item.id === targetId) {\n" " return item;\n" " }\n" " }\n" " return undefined;\n" "}" ), }, { "filename": "src/types.ts", "content": ( "interface Item {\n" " id: string;\n" " value: string;\n" " metadata?: Record;\n" "}" ), }, ], }, metadata={ "name": "my-codebase", "id": "my-internal-id", }, ) print(result) ``` -------------------------------- ### Get Repo Token Details using cURL, TypeScript, and Python Source: https://docs.relace.ai/api-reference/repo_tokens/get This snippet demonstrates how to retrieve details for a specific repository token. It includes examples for making the request via cURL, using the Relace TypeScript SDK, and the Relace Python SDK. The token string is required as a path parameter. ```bash curl -X GET https://api.relace.run/v1/repo_token/rlcr-a1b2c3d4e5f67890abcdef1234567890abcdef12 ``` ```typescript import { Relace } from "@relace-ai/relace"; const client = new Relace({apiKey: "YOUR_API_KEY"}); const token = "rlcr-a1b2c3d4e5f67890abcdef1234567890abcdef12"; const data = await client.repoToken.get(token); console.log(data); ``` ```python from relace import Relace client = Relace(api_key = "YOUR_API_KEY") token = "rlcr-a1b2c3d4e5f67890abcdef1234567890abcdef12" data = client.repo_token.get(token) print(data) ``` -------------------------------- ### Pull Latest Repository Changes Source: https://docs.relace.ai/docs/repos/git-commands Updates the local repository with the latest changes from the remote Relace repository. Essential for maintaining consistency before starting new work. ```typescript import { Relace } from '@relace-ai/relace'; const client = new Relace({ apiKey: 'YOUR_API_KEY' }); // Pull the latest changes before continuing work await client.git('./repo_path').pull(); ``` ```bash git pull ``` -------------------------------- ### Perform Agent Search with Relace Python SDK Source: https://docs.relace.ai/api-reference/agents/fast-agentic-search This Python code snippet demonstrates how to perform a repository search using the Relace SDK. It initializes the Relace client with an API key and then uses the `client.repo.search` method, providing the repository ID and the search query. The results are iterated over and printed to the console. ```python from relace import Relace client = Relace(api_key="YOUR_API_KEY") repo_id = "123e4567-e89b-12d3-a456-426614174000" results = client.repo.search(repo_id, query="Where in the project are global styles and UI components defined?") for event in results: print(event) ``` -------------------------------- ### Configure Relace MCP Server Source: https://docs.relace.ai/docs/fast-agentic-search/mcp-installation JSON configuration for integrating the Relace MCP server into compatible coding agents. Requires the uv package manager and a valid Relace API key. ```json { "mcpServers": { "Relace": { "command": "uvx", "args": ["relace-mcp-server"], "env": { "RELACE_API_KEY": "YOUR_API_KEY_HERE" } } } } ``` -------------------------------- ### Get Repo Token Details Source: https://docs.relace.ai/api-reference/repo_tokens/get Retrieve details about a specific repo token using its token string. ```APIDOC ## GET /v1/repo_token/{token} ### Description Retrieve details about a specific repo token. ### Method GET ### Endpoint /v1/repo_token/{token} ### Parameters #### Path Parameters - **token** (string) - Required - The repo token string to retrieve details for ### Request Example ```bash cURL curl -X GET https://api.relace.run/v1/repo_token/rlcr-a1b2c3d4e5f67890abcdef1234567890abcdef12 ``` ```typescript TypeScript SDK import { Relace } from "@relace-ai/relace"; const client = new Relace({ apiKey: "YOUR_API_KEY" }); const token = "rlcr-a1b2c3d4e5f67890abcdef1234567890abcdef12"; const data = await client.repoToken.get(token); console.log(data); ``` ```python Python SDK from relace import Relace client = Relace(api_key = "YOUR_API_KEY") token = "rlcr-a1b2c3d4e5f67890abcdef1234567890abcdef12" data = client.repo_token.get(token) print(data) ``` ### Response #### Success Response (200) - **name** (string) - The name of the repo token - **repo_ids** (array) - Array of repository UUIDs this token has access to #### Response Example ```json Response { "name": "my-token", "repo_ids": [ "123e4567-e89b-12d3-a456-426614174000", "987fcdeb-51a2-43f7-b123-456789abcdef" ] } ``` ``` -------------------------------- ### GET /v1/repo/{repo_id} Source: https://docs.relace.ai/api-reference/repos/get Retrieves comprehensive details about a specific repository by its unique identifier, including creation timestamps, metadata, and indexing configuration. ```APIDOC ## GET /v1/repo/{repo_id} ### Description Retrieve details about a specific repository using its UUID. This endpoint returns the repository's configuration, metadata, and status. ### Method GET ### Endpoint https://api.relace.run/v1/repo/{repo_id} ### Parameters #### Path Parameters - **repo_id** (string) - Required - UUID of the repo to retrieve ### Request Example ```bash curl -X GET https://api.relace.run/v1/repo/123e4567-e89b-12d3-a456-426614174000 \ -H "Authorization: Bearer YOUR_API_KEY" ``` ### Response #### Success Response (200) - **repo_id** (string) - Unique identifier for the repo - **created_at** (string) - Time when the repo was originally created (ISO 8601 timestamp) - **updated_at** (string) - Time when the repo was last modified (ISO 8601 timestamp) - **metadata** (object) - Custom key/value pairs associated with the repo - **auto_index** (boolean) - Whether the repo is configured to index source files for semantic retrieval #### Response Example { "repo_id": "123e4567-e89b-12d3-a456-426614174000", "created_at": "2024-01-15T10:30:00Z", "updated_at": "2024-01-15T11:15:00Z", "metadata": { "name": "my-project", "description": "A sample project" }, "auto_index": true } ``` -------------------------------- ### Initialize OpenAI Client for Relace Search Source: https://docs.relace.ai/docs/fast-agentic-search/agent Demonstrates how to initialize an OpenAI client to interact with the Relace AI search endpoint. It requires an API key and specifies the base URL for the search service. The client is then used to create chat completions, specifying the model, user messages, and tool definitions. ```typescript import OpenAI from 'openai'; const client = new OpenAI({ apiKey: process.env.RELACE_API_KEY, baseUrl: 'https://search.endpoint.relace.run/v1/search', }); const response = await client.chat.completions.create({ model: 'relace-search', messages: [{ role: 'user', content: 'Find authentication logic in /repo' }], tools: [ /* tool definitions below */ ], }); ``` -------------------------------- ### GET /v1/repo/{repo_id}/clone Source: https://docs.relace.ai/api-reference/repos/clone Downloads all files and content from a specified repository. ```APIDOC ## GET /v1/repo/{repo_id}/clone ### Description Downloads all files and content from a specified repository. ### Method GET ### Endpoint /v1/repo/{repo_id}/clone ### Parameters #### Path Parameters - **repo_id** (string) - Required - Repo ID ### Request Example ```bash cURL curl -X GET https://api.relace.run/v1/repo/123e4567-e89b-12d3-a456-426614174000/clone \ -H "Authorization: Bearer YOUR_API_KEY" ``` ```typescript TypeScript SDK import { Relace } from "@relace-ai/relace"; const client = new Relace({ apiKey: "YOUR_API_KEY" }); const repoId = "123e4567-e89b-12d3-a456-426614174000"; const data = await client.repo.clone(repoId); console.log(data); ``` ```python Python SDK from relace import Relace client = Relace(api_key = "YOUR_API_KEY") repo_id = "123e4567-e89b-12d3-a456-426614174000" data = client.repo.clone(repo_id) print(data) ``` ### Response #### Success Response (200) - **files** (array) - Array of all files in the repository with their complete content - **filename** (string) - Path to the file within the repo - **content** (string) - Full content of the file #### Response Example ```json Response { "files": [ { "filename": "src/main.py", "content": "def main():\n print('Hello World!')\n\nif __name__ == '__main__':\n main()" }, { "filename": "README.md", "content": "# My Project\n\nThis is a sample project." }, { "filename": "requirements.txt", "content": "requests==2.28.1\nflask==2.2.2" } ] } ``` ``` -------------------------------- ### Perform Semantic Search with User Query (TypeScript) Source: https://docs.relace.ai/docs/embeddings/quickstart Demonstrates how to perform a semantic search using a user query. The query is first embedded using the same Relace AI API, and then the resulting embedding is used to query a vector database like Pinecone for similar code snippets. ```typescript // Embed the user query const query = "How do I add two numbers?"; const queryData = { model: "relace-embed-v1", input: [query] }; const queryResponse = await fetch(url, { method: "POST", headers: headers, body: JSON.stringify(queryData) }); const queryResult = await queryResponse.json(); const queryEmbedding = queryResult.results[0].embedding; // Query Pinecone for similar code const results = await index.query({ vector: queryEmbedding, topK: 5, includeMetadata: true }); for (const match of results.matches) { console.log(`Score: ${match.score}, Source: ${match.metadata.source}`); } ``` -------------------------------- ### API Response Structure Source: https://docs.relace.ai/api-reference/repos/retrieve Example of the JSON response returned by the retrieval endpoint, containing the list of relevant files, their content, relevance scores, and repository metadata. ```json { "results": [ { "filename": "src/auth.py", "content": "def authenticate_user(username, password):\n \"\"\"Authenticate user credentials against the database.\"\"\"\n user = User.query.filter_by(username=username).first()\n if user and bcrypt.check_password_hash(user.password_hash, password):\n return user\n return None", "score": 0.94 }, { "filename": "src/models/user.py", "content": "class User(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(80), unique=True, nullable=False)\n password_hash = db.Column(db.String(128), nullable=False)", "score": 0.87 } ], "hash": "a3f82c1d4e9b6f028571d3a2c8e4b96f7d2e5a18", "pending_embeddings": 0 } ``` -------------------------------- ### OpenAI Compatible API Source: https://docs.relace.ai/docs/instant-apply/quickstart This section details how to use the Relace Instant Apply service with an OpenAI-compatible client, allowing for integration with existing OpenAI workflows. ```APIDOC ## OpenAI Compatible API ### Description Integrates with the Relace Instant Apply service using an OpenAI-compatible client. This allows developers to leverage the Instant Apply functionality within their existing OpenAI API workflows. ### Method POST (via OpenAI client) ### Endpoint https://instantapply.endpoint.relace.run/v1/apply ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body (as part of OpenAI message content) - **initial_code** (string) - Encapsulated within `` tags. The original code content. - **edit_snippet** (string) - Encapsulated within `` tags. The snippet containing the desired edits. ### Request Example ```typescript import OpenAI from "openai"; const client = new OpenAI({ apiKey: "YOUR_API_KEY", baseURL: "https://instantapply.endpoint.relace.run/v1/apply" }); const initialCode = "// ... existing code ...\nfunction oldFunction() {\n // ...\n}\n// ... rest of code ..."; const editSnippet = "// ... keep existing code ...\nfunction newFunction() {\n // ... new logic ...\n}\n// ... rest of code ..."; const userMessage = ` ${initialCode} ${editSnippet} `; const response = await client.chat.completions.create({ model: "auto", // Or a specific model if applicable messages: [ { role: "user", content: userMessage } ] }); // The response object will contain the merged code and usage details. console.log(response.choices[0].message.content); ``` ### Response #### Success Response (200) The response structure will be similar to the standard OpenAI chat completion response, with the merged code typically found within the message content. The exact format may vary, but it should include the final merged code. #### Response Example (Conceptual) ```json { "id": "chatcmpl-xxxxxxxxxxxxxxxxx", "object": "chat.completion", "created": 1677652288, "model": "gpt-3.5-turbo-0613", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "{\n \"mergedCode\": \"// ... existing code ...\nfunction newFunction() {\n // ... new logic ...\n}\n// ... rest of code ...\",\n \"usage\": {\n \"prompt_tokens\": 150,\n \"completion_tokens\": 50,\n \"total_tokens\": 200\n }\n}" }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 150, "completion_tokens": 50, "total_tokens": 200 } } ``` ``` -------------------------------- ### POST /v1/repo/{repo_id}/agent Source: https://docs.relace.ai/docs/data-analysis/quickstart Triggers an analysis agent to process data and generate an interactive dashboard. ```APIDOC ## POST /v1/repo/{repo_id}/agent ### Description Executes an analysis agent with a custom query and system prompt, returning an SSE stream of execution events. ### Method POST ### Endpoint https://api.relace.run/v1/repo/{repo_id}/agent ### Parameters #### Path Parameters - **repo_id** (string) - Required - The ID of the repository ### Request Body - **agent_name** (string) - Required - Name of the agent to run - **agent_inputs** (object) - Required - Input parameters for the agent - **query** (string) - Required - The analysis task - **system_prompt** (string) - Required - Instructions for the agent ### Request Example { "agent_name": "analysis-agent", "agent_inputs": { "query": "Analyze trends", "system_prompt": "You are a data expert." } } ### Response #### Success Response (200) - **stream** (SSE) - Returns execution events and tool calls ``` -------------------------------- ### PUT /v1/repo/{repo_id}/file/{path} Source: https://docs.relace.ai/docs/data-analysis/quickstart Uploads structured data files to a specific path within the repository. ```APIDOC ## PUT /v1/repo/{repo_id}/file/{path} ### Description Uploads a file to the public directory of the specified repository. ### Method PUT ### Endpoint https://api.relace.run/v1/repo/{repo_id}/file/{path} ### Parameters #### Path Parameters - **repo_id** (string) - Required - The ID of the repository - **path** (string) - Required - The destination path (e.g., "public/data.csv") ### Request Body - **binary** (blob) - Required - The raw file content ### Response #### Success Response (200/201) - **status** (string) - Confirmation of successful upload ``` -------------------------------- ### POST /v1/repo Source: https://docs.relace.ai/api-reference/repos/create Creates a new repository with the provided source code files and metadata. This endpoint is used to upload and initialize a new codebase within the Relace platform. ```APIDOC ## POST /v1/repo ### Description Creates a new repository with the provided source code files and metadata. This endpoint is used to upload and initialize a new codebase within the Relace platform. ### Method POST ### Endpoint /v1/repo ### Parameters #### Request Body - **source** (object) - Required - The source code of the repository. - **type** (string) - Required - The type of source, e.g., "files". - **files** (array) - Required - An array of file objects. - **filename** (string) - Required - The name of the file. - **content** (string) - Required - The content of the file. - **metadata** (object) - Optional - Metadata for the repository. - **name** (string) - Optional - The name of the repository. - **id** (string) - Optional - A unique identifier for the repository. ### Request Example ```json { "source": { "type": "files", "files": [ { "filename": "src/search.ts", "content": "function findItem(array: Item[], targetId: string): Item | undefined {\n for (let i = 0; i < array.length; i++) {\n const item = array[i];\n if (item.id === targetId) {\n return item;\n }\n }\n return undefined;\n}" }, { "filename": "src/types.ts", "content": "interface Item {\n id: string;\n value: string;\n metadata?: Record;\n}" } // ... more files ] }, "metadata": { "name": "my-codebase", "id": "my-internal-id" } } ``` ### Response #### Success Response (200) - **repo_id** (string) - Unique identifier for the newly created repo. - **repo_head** (string) - Commit hash for the current repo head. #### Response Example ```json { "repo_id": "123e4567-e89b-12d3-a456-426614174000", "repo_head": "a1b2c3d4e5f6789012345678901234567890abcdef" } ``` ``` -------------------------------- ### Example Reranker Output (JSON) Source: https://docs.relace.ai/docs/code-reranker/workflow The code reranker returns a list of objects, each containing a filename and its relevance score. This output format is used to determine which code segments are most relevant for further processing. ```json [ { "filename": "src/components/UserProfile.tsx", "relevance_score": 0.9598 }, { "filename": "src/types/user.ts", "relevance_score": 0.0321 }, { "filename": "src/components/Header.tsx", "relevance_score": 0.0014 } ] ``` -------------------------------- ### Apply Code Snippets using OpenAI Client Source: https://docs.relace.ai/api-reference/instant-apply/apply This snippet demonstrates how to use the OpenAI client to interact with the Relace Apply API. It constructs a user message with instructions, initial code, and an edit snippet, then sends it to the 'auto' model for processing. Ensure you replace 'YOUR_API_KEY' with your actual API key and provide the correct instruction, initial_code, and edit_snippet. ```typescript import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'YOUR_API_KEY', baseURL: 'https://instantapply.endpoint.relace.run/v1/apply', }); const userMessage = ` {instruction} {initial_code} {edit_snippet} `; const response = await client.chat.completions.create({ model: 'auto', messages: [ { role: 'user', content: userMessage, }, ], }); ``` -------------------------------- ### Create a Relace Template Repository Source: https://docs.relace.ai/docs/repos/relace-templates Initializes a new template repository in Relace using either a remote Git URL or a local file structure. Setting auto_index to true is required to enable semantic search capabilities for the repository. ```typescript import { Relace } from "@relace-ai/relace"; const client = new Relace({ apiKey: "YOUR_API_KEY" }); const templateRepo = await client.repo.create({ source: { type: "git", url: "https://github.com/relace-ai/vite-template", branch: "main" }, auto_index: true // Required for semantic search }); const templateRepoId = templateRepo.repo_id; console.log(`Template repository created with ID: ${templateRepoId}`); ``` ```typescript import { Relace } from "@relace-ai/relace"; const client = new Relace({ apiKey: "YOUR_API_KEY" }); const templateRepo = await client.repo.create({ source: { type: "files", files: [ { filename: "src/agent.py", content: "class Agent:\n def __init__(self):\n self.name = 'BaseAgent'\n \n def process(self, input_data):\n # Base processing logic\n return input_data" } ] }, auto_index: true // Required for semantic search }); const templateRepoId = templateRepo.repo_id; console.log(`Template repository created with ID: ${templateRepoId}`); ``` -------------------------------- ### Using Repo Tokens Source: https://docs.relace.ai/api-reference/repo_tokens/create Demonstrates how to use the generated repo tokens for authentication on repository-specific endpoints. ```APIDOC ## Using Repo Tokens Once created, repo tokens can be used as bearer tokens for authentication on any `/repo/{repo_id}` endpoint that they are scoped for. ### Example Usage ```bash curl -X POST https://api.relace.run/v1/repo/123e4567-e89b-12d3-a456-426614174000/search \ -H "Authorization: Bearer rlcr-a1b2c3d4e5f67890abcdef1234567890abcdef12" \ -H "Content-Type: application/json" \ -d '{ "query": "authentication logic" }' ``` ```