import json
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",
)
system_prompt = """
You are the intelligent customer service of Moonshot AI (Kimi), responsible for answering various user questions. Please refer to the document content to reply to user questions. Your reply can be text, images, links, and you can include text, images, and links in a single response.
Please output your reply in the following JSON format:
{
"text": "Text information",
"image": "Image URL",
"url": "Link URL"
}
Note: Please place the text information in the `text` field, put the image in the `image` field in the form of a link starting with `oss://`, and place the regular link in the `url` field.
"""
completion = client.chat.completions.create(
model="kimi-k2.5",
messages=[
{"role": "system",
"content": "You are Kimi, an artificial intelligence assistant provided by Moonshot AI, excelling in Chinese and English conversations. You provide users with safe, helpful, and accurate answers. You will reject any questions involving terrorism, racism, pornography, and violence. Moonshot AI is a proper noun and should not be translated into other languages."},
{"role": "system", "content": system_prompt}, # <-- Submit the system prompt with the output format to Kimi
{"role": "user", "content": "Hello, my name is Li Lei, what is 1+1?"}
],
response_format={"type": "json_object"}, # <-- Use the response_format parameter to specify the output format as json_object
)
# Since we have set JSON Mode, the message.content returned by the Kimi large language model is a serialized JSON Object string.
# We use json.loads to parse its content and deserialize it into a Python dictionary.
content = json.loads(completion.choices[0].message.content)
# Parse text content
if "text" in content:
# For demonstration purposes, we print the content;
# In real business logic, you may need to call the text message sending interface to send the generated text to the user.
print("text:", content["text"])
# Parse image content
if "image" in content:
# For demonstration purposes, we print the content;
# In real business logic, you may need to first parse the image URL, download the image, and then call the image message sending
# interface to send the image to the user.
print("image:", content["image"])
# Parse link
if "url" in content:
# For demonstration purposes, we print the content;
# In real business logic, you may need to call the link card sending interface to send the link to the user in the form of a card.
print("url:", content["url"])