File size: 1,894 Bytes
0e45626
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import streamlit as st
import requests

st.title("ChatGPT-like clone")

# Set AI21 API key from Streamlit secrets
API_KEY = st.secrets["AI21_API_KEY"]

# Function to get response from AI21 Labs API
def get_ai21_response(prompt):
    headers = {
        'Authorization': f'Bearer ' + API_KEY,
        'Content-Type': 'application/json'
    }
    data = {
        'prompt': prompt,
        'maxTokens': 150,
        'temperature': 0.7,
        'topP': 1.0,
        'stopSequences': ["<|endoftext|>"]
    }
    response = requests.post('https://api.ai21.com/studio/v1/j2-jumbo/complete', headers=headers, json=data)
    response_json = response.json()
    return response_json['completions'][0]['data']['text']

# Initialize chat history
if "messages" not in st.session_state:
    st.session_state.messages = []

# Display chat messages from history on app rerun
for message in st.session_state.messages:
    with st.chat_message(message["role"]):
        st.markdown(message["content"])

# Accept user input
if prompt := st.chat_input("What is up?"):
    # Add user message to chat history
    st.session_state.messages.append({"role": "user", "content": prompt})
    # Display user message in chat message container
    with st.chat_message("user"):
        st.markdown(prompt)

    # Create the full conversation prompt
    full_prompt = "\n".join([f"{m['role']}: {m['content']}" for m in st.session_state.messages])
    full_prompt += "\nassistant:"

    # Call AI21 Labs API for assistant response
    assistant_reply = get_ai21_response(full_prompt)

    # Display assistant response in chat message container
    with st.chat_message("assistant"):
        st.markdown(assistant_reply.strip())

    # Add assistant response to chat history
    st.session_state.messages.append({"role": "assistant", "content": assistant_reply.strip()})