from typing import *
import os
import json
from pathlib import Path
from openai import OpenAI
client = OpenAI(
api_key="MOONSHOT_API_KEY", # Replace MOONSHOT_API_KEY with the API Key you obtained from the Kimi Open Platform
base_url="https://api.moonshot.ai/v1",
)
def upload_files(files: List[str]) -> List[Dict[str, Any]]:
"""
upload_files uploads all the provided files (paths) via the '/v1/files' interface and generates file messages from the extracted content. Each file becomes an independent message with a role of 'system', which the Kimi large language model can correctly identify.
:param files: A list of file paths to be uploaded. The paths can be absolute or relative, and should be passed as strings.
:return: A list of messages containing the file content. Add these messages to the Context, i.e., the messages parameter when calling the `/v1/chat/completions` interface.
"""
messages = []
# For each file path, we upload the file, extract its content, and generate a message with a role of 'system', which is then added to the final messages list.
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 = [
# We use the * syntax to unpack the file_messages, making them the first N messages in the messages list.
*file_messages,
{
"role": "system",
"content": "You are Kimi, an AI assistant provided by Moonshot AI. You excel in Chinese and English conversations. You provide users with safe, helpful, and accurate answers while rejecting any queries related to terrorism, racism, or explicit content. Moonshot AI is a proper noun and should not be translated.",
},
{
"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-k2.5",
messages=messages,
)
print(completion.choices[0].message.content)
if __name__ == '__main__':
main()