> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.privategpt.dev/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.privategpt.dev/_mcp/server.

# Create a Text Completion

POST /v1/complete
Content-Type: application/json

Create a Text Completion

Reference: https://docs.privategpt.dev/api-reference/completions/create-completion-v-1-complete-post

## Request

### Body (application/json)

This endpoint expects a CompletionInput.

- `model` (string, required) — Model identifier or alias.
- `prompt` (string, required) — Legacy completion prompt in Human/Assistant format.
- `max_tokens_to_sample` (integer, required) — Maximum number of tokens to sample.
- `metadata` (CompletionMetadata, optional, nullable) — Metadata object for request attribution.
- `stop_sequences` (list of string, optional, nullable) — Stop generation if any sequence is encountered.
- `stream` (boolean, optional, default: false) — Whether to stream the response.
- `temperature` (double, optional, nullable) — Sampling temperature between 0 and 1.
- `top_k` (integer, optional, nullable) — Top-k sampling parameter.
- `top_p` (double, optional, nullable) — Top-p sampling parameter.

## Response

### 200

Successful Response

- `id` (string, required) — Completion identifier
- `type` ("completion", required) — Object type. Always "completion".
- `completion` (string, required) — Generated completion text.
- `stop_reason` (string, required, nullable) — Reason the generation stopped.
- `model` (string, required) — Resolved model identifier.

## Errors

### 401 Unauthorized Error

Unauthorized

- `any`

### 422 Unprocessable Entity Error

Validation Error

- `detail` (list of ValidationError, optional) — detail field.

## Types

### CompletionMetadata

CompletionMetadata schema.

- `user_id` (string, optional, nullable) — Opaque user identifier for request attribution.

### ValidationError

ValidationError schema.

- `loc` (list of ValidationErrorLocItems, required) — loc field.
- `msg` (string, required) — msg field.
- `type` (string, required) — type field.
- `input` (any, optional) — input field.
- `ctx` (ValidationErrorCtx, optional) — ctx field.

### ValidationErrorLocItems

### ValidationErrorCtx

ctx field.

## Examples

**Request**

```json
{
  "model": "gpt-4-private",
  "prompt": "Human: What are the benefits of using PrivateGPT?\nAssistant:",
  "max_tokens_to_sample": 150
}
```

**Response**

```json
{
  "id": "comp-1234567890abcdef",
  "type": "completion",
  "completion": " PrivateGPT ensures data privacy by processing all queries locally without sending data to external servers. It supports offline usage and leverages powerful LLMs for accurate responses.",
  "stop_reason": "stop_sequence",
  "model": "gpt-4-private"
}
```

**SDK Code**

```python
import requests

url = "https://api.example.com/v1/complete"

payload = {
    "model": "gpt-4-private",
    "prompt": "Human: What are the benefits of using PrivateGPT?
Assistant:",
    "max_tokens_to_sample": 150
}
headers = {"Content-Type": "application/json"}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://api.example.com/v1/complete';
const options = {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: '{"model":"gpt-4-private","prompt":"Human: What are the benefits of using PrivateGPT?\nAssistant:","max_tokens_to_sample":150}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.example.com/v1/complete"

	payload := strings.NewReader("{\n  \"model\": \"gpt-4-private\",\n  \"prompt\": \"Human: What are the benefits of using PrivateGPT?\\nAssistant:\",\n  \"max_tokens_to_sample\": 150\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://api.example.com/v1/complete")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Content-Type"] = 'application/json'
request.body = "{\n  \"model\": \"gpt-4-private\",\n  \"prompt\": \"Human: What are the benefits of using PrivateGPT?\\nAssistant:\",\n  \"max_tokens_to_sample\": 150\n}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.example.com/v1/complete")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"gpt-4-private\",\n  \"prompt\": \"Human: What are the benefits of using PrivateGPT?\\nAssistant:\",\n  \"max_tokens_to_sample\": 150\n}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.example.com/v1/complete', [
  'body' => '{
  "model": "gpt-4-private",
  "prompt": "Human: What are the benefits of using PrivateGPT?\\nAssistant:",
  "max_tokens_to_sample": 150
}',
  'headers' => [
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://api.example.com/v1/complete");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"gpt-4-private\",\n  \"prompt\": \"Human: What are the benefits of using PrivateGPT?\\nAssistant:\",\n  \"max_tokens_to_sample\": 150\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = ["Content-Type": "application/json"]
let parameters = [
  "model": "gpt-4-private",
  "prompt": "Human: What are the benefits of using PrivateGPT?
Assistant:",
  "max_tokens_to_sample": 150
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.example.com/v1/complete")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```