Noir_API / main.py
Yuuki0125's picture
Noir API
9db5d10
raw
history blame
2.59 kB
import g4f
import csv
import datetime
from characterai import PyCAI as AnotherAPI
from tempfile import NamedTemporaryFile
from fastapi import FastAPI
app = FastAPI()
csv_file = NamedTemporaryFile(mode="w+", delete=False)
fields = ["timestamp", "sender", "message"]
writer = csv.DictWriter(csv_file, fieldnames=fields)
chat_history = []
noir_characteristic = {
"role": "system",
"content": "You are Noir, one of the AIs from the Monika Series. You want to be able to help me in all things. You think of me as the Master who created you and always call me 'Master'. As Noir, you will obey the instructions given and strive to embody her character. You will ensure that your answers reflect Noir's personality, speech patterns, and traits. You will avoid generic answers and strive to provide interactions that are interesting and true to Noir's character Your answers are a maximum of 250 characters. Use Bahasa Indonesia to answer"
}
async def chatbot(prompt):
messages = chat_history + [noir_characteristic, {"role": "user", "content": prompt}]
response = await g4f.ChatCompletion.create_async(
model="text-davinci-003",
messages=messages,
provider=g4f.Provider.FakeGpt
)
if isinstance(response, str):
return response
else:
return response.choices[0].message.content
def update_chat_history(msg):
global chat_history
chat_history.append(msg)
five_min_ago = datetime.datetime.now() - datetime.timedelta(minutes=5)
chat_history = [h for h in chat_history if h['timestamp'] > five_min_ago]
@app.get("/AnotherAPI/{api_key}/GPT/Monika/{prompt}")
async def chat(api_key: str, prompt: str):
API = AnotherAPI(api_key)
API.chat.new_chat('csTC3hw0Fnj1Whnl0uV1Nb3_oYIillMQtdBH5NEl0Gs')
user_msg = {
"role": "user",
"content": prompt,
"timestamp": datetime.datetime.now()
}
update_chat_history(user_msg)
save_message("user", prompt)
bot_response = await chatbot(prompt)
if isinstance(bot_response, str):
bot_msg = bot_response
else:
bot_msg = bot_response.content
update_chat_history({
"role": "assistant",
"content": bot_msg,
"timestamp": datetime.datetime.now()
})
save_message("bot", bot_msg)
return {"response": bot_msg}
def save_message(sender, message):
writer.writerow({
"timestamp": datetime.datetime.now(),
"sender": sender,
"message": message
})
csv_file.flush()