|
"""This module contains functions to interact with the OpenRouter API. |
|
It load dotenv, OpenAI and other necessary packages to interact |
|
with the OpenRouter API. |
|
Also stores the chat history in a list.""" |
|
from dotenv import load_dotenv |
|
from openai import OpenAI |
|
from IPython.display import Markdown, display |
|
import os |
|
|
|
|
|
load_dotenv(override=True) |
|
|
|
|
|
openrouter_api_key = os.getenv('OPENROUTER_API_KEY') |
|
|
|
if openrouter_api_key: |
|
print(f"OpenAI API Key exists and begins {openrouter_api_key[:8]}") |
|
else: |
|
print("OpenAI API Key not set - please head to the troubleshooting guide in the setup folder") |
|
|
|
|
|
chatHistory = [] |
|
|
|
|
|
def chatWithOpenRouter(model:str, prompt:str)-> str: |
|
""" This function takes a model and a prompt and shows the response |
|
in markdown format. It uses the OpenAI class from the openai package""" |
|
|
|
|
|
|
|
llmRequest = OpenAI( |
|
api_key=openrouter_api_key, |
|
base_url="https://openrouter.ai/api/v1" |
|
) |
|
|
|
|
|
chatHistory.append({"role": "user", "content": prompt}) |
|
|
|
|
|
response = llmRequest.chat.completions.create( |
|
model=model, |
|
messages=chatHistory |
|
) |
|
|
|
|
|
assistantResponse = response.choices[0].message.content |
|
|
|
|
|
display(Markdown(f"**Assistant:** {assistantResponse}")) |
|
|
|
|
|
chatHistory.append({"role": "assistant", "content": assistantResponse}) |
|
|
|
|
|
def getOpenrouterResponse(model:str, prompt:str)-> str: |
|
""" |
|
This function takes a model and a prompt and returns the response |
|
from the OpenRouter API, using the OpenAI class from the openai package. |
|
""" |
|
llmRequest = OpenAI( |
|
api_key=openrouter_api_key, |
|
base_url="https://openrouter.ai/api/v1" |
|
) |
|
|
|
|
|
chatHistory.append({"role": "user", "content": prompt}) |
|
|
|
|
|
response = llmRequest.chat.completions.create( |
|
model=model, |
|
messages=chatHistory |
|
) |
|
|
|
|
|
assistantResponse = response.choices[0].message.content |
|
|
|
|
|
chatHistory.append({"role": "assistant", "content": assistantResponse}) |
|
|
|
|
|
return assistantResponse |
|
|
|
|
|
|
|
def clearChatHistory(): |
|
""" This function clears the chat history. It can't be undone!""" |
|
chatHistory.clear() |