curl --request POST \
--url https://api.moonshot.ai/v1/files \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: multipart/form-data' \
--form file='@example-file'import requests
url = "https://api.moonshot.ai/v1/files"
files = { "file": ("example-file", open("example-file", "rb")) }
headers = {"Authorization": "Bearer <token>"}
response = requests.post(url, files=files, headers=headers)
print(response.text)const form = new FormData();
form.append('file', '<string>');
const options = {method: 'POST', headers: {Authorization: 'Bearer <token>'}};
options.body = form;
fetch('https://api.moonshot.ai/v1/files', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.moonshot.ai/v1/files",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"example-file\"\r\nContent-Type: application/octet-stream\r\n\r\n<string>\r\n-----011000010111000001101001--",
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: multipart/form-data"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "https://api.moonshot.ai/v1/files"
payload := strings.NewReader("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"example-file\"\r\nContent-Type: application/octet-stream\r\n\r\n<string>\r\n-----011000010111000001101001--")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://api.moonshot.ai/v1/files")
.header("Authorization", "Bearer <token>")
.body("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"example-file\"\r\nContent-Type: application/octet-stream\r\n\r\n<string>\r\n-----011000010111000001101001--")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.moonshot.ai/v1/files")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request.body = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"example-file\"\r\nContent-Type: application/octet-stream\r\n\r\n<string>\r\n-----011000010111000001101001--"
response = http.request(request)
puts response.read_body{
"id": "<string>",
"object": "file",
"bytes": 123,
"created_at": 123,
"filename": "<string>",
"purpose": "file-extract",
"status": "ready",
"status_details": "<string>"
}{
"error": {
"message": "<string>",
"type": "<string>",
"code": "<string>"
}
}{
"error": {
"message": "<string>",
"type": "<string>",
"code": "<string>"
}
}{
"error": {
"message": "<string>",
"type": "<string>",
"code": "<string>"
}
}Upload File
Upload a file for text content extraction, image understanding, or video understanding. Supports text-based formats such as pdf, doc, and txt.
curl --request POST \
--url https://api.moonshot.ai/v1/files \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: multipart/form-data' \
--form file='@example-file'import requests
url = "https://api.moonshot.ai/v1/files"
files = { "file": ("example-file", open("example-file", "rb")) }
headers = {"Authorization": "Bearer <token>"}
response = requests.post(url, files=files, headers=headers)
print(response.text)const form = new FormData();
form.append('file', '<string>');
const options = {method: 'POST', headers: {Authorization: 'Bearer <token>'}};
options.body = form;
fetch('https://api.moonshot.ai/v1/files', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.moonshot.ai/v1/files",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"example-file\"\r\nContent-Type: application/octet-stream\r\n\r\n<string>\r\n-----011000010111000001101001--",
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: multipart/form-data"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "https://api.moonshot.ai/v1/files"
payload := strings.NewReader("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"example-file\"\r\nContent-Type: application/octet-stream\r\n\r\n<string>\r\n-----011000010111000001101001--")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://api.moonshot.ai/v1/files")
.header("Authorization", "Bearer <token>")
.body("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"example-file\"\r\nContent-Type: application/octet-stream\r\n\r\n<string>\r\n-----011000010111000001101001--")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.moonshot.ai/v1/files")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request.body = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"example-file\"\r\nContent-Type: application/octet-stream\r\n\r\n<string>\r\n-----011000010111000001101001--"
response = http.request(request)
puts response.read_body{
"id": "<string>",
"object": "file",
"bytes": 123,
"created_at": 123,
"filename": "<string>",
"purpose": "file-extract",
"status": "ready",
"status_details": "<string>"
}{
"error": {
"message": "<string>",
"type": "<string>",
"code": "<string>"
}
}{
"error": {
"message": "<string>",
"type": "<string>",
"code": "<string>"
}
}{
"error": {
"message": "<string>",
"type": "<string>",
"code": "<string>"
}
}- File ID change: newly generated file IDs now carry the
file_prefix - Improved document parsing: better parsing of complex content such as tables and formulas
- Image handling change: images are no longer OCR’d for text extraction. For image understanding, upload images with
purpose="image". See Use Vision Models - Automatic renaming of duplicate files: when an uploaded file has the same name as an existing file, the server automatically renames the new file to avoid conflicts
Supported Formats
Supported Formats
.pdf, .txt, .csv, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .md, .dot, .epub, .html, .json, .mobi, .log, .go, .h, .c, .cpp, .cxx, .cc, .cs, .java, .js, .css, .jsp, .php, .py, .py3, .asp, .yaml, .yml, .ini, .conf, .ts, .tsx, and more.Note: Image files no longer support content extraction (file-extract). For image understanding, upload images with purpose="image". See Use Vision Models.File Content Extraction Example
File Content Extraction Example
purpose="file-extract" if you want the model to use the extracted file contents as context.- python
- curl
- node.js
from pathlib import Path
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["MOONSHOT_API_KEY"],
base_url = "https://api.moonshot.ai/v1",
)
# xlnet.pdf is an example file; we support text formats such as pdf and doc.
file_object = client.files.create(file=Path("xlnet.pdf"), purpose="file-extract")
# Note: retrieve_content is deprecated in the latest version.
# If you are using the latest SDK, use files.content instead.
file_content = client.files.content(file_id=file_object.id).text
messages = [
{
"role": "system",
"content": "You are Kimi, an AI assistant provided by Moonshot AI. You are particularly skilled in Chinese and English conversations. You provide users with safe, helpful, and accurate answers. You will refuse to answer any questions involving terrorism, racism, pornography, or violence. Moonshot AI is a proper noun and should not be translated into other languages.",
},
{
"role": "system",
"content": file_content,
},
{"role": "user", "content": "Please give a brief introduction of what xlnet.pdf is about"},
]
completion = client.chat.completions.create(
model="kimi-k3",
messages=messages,
temperature=0.6,
)
print(completion.choices[0].message)
# xlnet.pdf is a sample file
curl https://api.moonshot.ai/v1/files \
-H "Authorization: Bearer $MOONSHOT_API_KEY" \
-F purpose="file-extract" \
-F file="@xlnet.pdf"
const OpenAI = require("openai");
const fs = require("fs");
const client = new OpenAI({
apiKey: process.env.MOONSHOT_API_KEY,
baseURL: "https://api.moonshot.ai/v1",
});
async function main() {
let file_object = await client.files.create({
file: fs.createReadStream("xlnet.pdf"),
purpose: "file-extract"
});
// retrieve_content is deprecated in the latest version.
let file_content = await (await client.files.content(file_object.id)).text();
let messages = [
{
"role": "system",
"content": "You are Kimi, an AI assistant provided by Moonshot AI. You are more proficient in Chinese and English conversations. You provide users with safe, helpful, and accurate answers. You will refuse to answer any questions related to terrorism, racism, pornography, or violence. Moonshot AI is a proper noun and should not be translated into other languages.",
},
{
"role": "system",
"content": file_content,
},
{"role": "user", "content": "Please give a brief introduction of what xlnet.pdf is about"},
];
const completion = await client.chat.completions.create({
model: "kimi-k3",
messages: messages,
temperature: 0.6
});
console.log(completion.choices[0].message.content);
}
main();
$MOONSHOT_API_KEY with your own API key, or set it as an environment variable before making the call.Multi-file Chat Example
Multi-file Chat Example
from typing import *
import os
import json
from pathlib import Path
from openai import OpenAI
client = OpenAI(
base_url="https://api.moonshot.ai/v1",
api_key=os.environ["MOONSHOT_API_KEY"],
)
def upload_files(files: List[str]) -> List[Dict[str, Any]]:
"""
upload_files uploads all provided files (paths) via the file upload API '/v1/files',
retrieves the uploaded file content, and generates file messages. Each file becomes
an independent message with role set to system. The Kimi model will correctly
recognize the file content in these system messages.
:param files: A list of file paths to upload. Paths can be absolute or relative,
passed as strings.
:return: A list of messages containing file content. Add these messages to the Context,
i.e., the messages parameter when calling the `/v1/chat/completions` API.
"""
messages = []
for file in files:
file_object = client.files.create(file=Path(file), purpose="file-extract")
file_content = client.files.content(file_id=file_object.id).text
messages.append({
"role": "system",
"content": file_content,
})
return messages
def main():
file_messages = upload_files(files=["upload_files.py"])
messages = [
*file_messages,
{
"role": "system",
"content": "You are Kimi, an AI assistant provided by Moonshot AI. You are more proficient in Chinese and English conversations. You provide users with safe, helpful, and accurate answers. You will refuse to answer any questions related to terrorism, racism, pornography, or violence. Moonshot AI is a proper noun and should not be translated into other languages.",
},
{
"role": "user",
"content": "Summarize the content of these files.",
},
]
print(json.dumps(messages, indent=2, ensure_ascii=False))
completion = client.chat.completions.create(
model="kimi-k3",
messages=messages,
)
print(completion.choices[0].message.content)
if __name__ == '__main__':
main()
Image or Video Understanding
Image or Video Understanding
purpose="image" or purpose="video".Please refer to Using Vision Models for end-to-end examples.Authorizations
The Authorization header expects a Bearer token. Use an MOONSHOT_API_KEY as the token. This is a server-side secret key. Generate one on the API keys page in your dashboard.
Body
The file to upload
Specifies how the uploaded file will be processed. file-extract: extract content from text-based files (such as pdf, doc, txt); images are not supported; image: upload images for vision understanding; video: upload videos for video understanding; batch: upload JSONL files for batch processing
file-extract, image, video, batch Response
Uploaded file metadata
Unique file identifier
Object type
"file"
File size in bytes
Unix timestamp when the file was created
Original file name
Purpose used when uploading the file. file-extract: extract content from text-based files (such as pdf, doc, txt); images are not supported; image: upload images for vision understanding; video: upload videos for video understanding; batch: upload JSONL files for batch processing
file-extract, image, video, batch Processing status of the file
"ready"
Additional status details when processing fails or returns warnings
Was this page helpful?