Spaces:
Running
Running
import os | |
from dotenv import load_dotenv | |
from langchain_anthropic import ChatAnthropic | |
from langchain_core.prompts import ChatPromptTemplate | |
import streamlit as st | |
from langchain_core.output_parsers import StrOutputParser | |
# Load the API key from the environment | |
load_dotenv() | |
from pydantic import SecretStr | |
# Check if the API keys are set | |
claude_api_key = os.getenv("CLAUDE_API_KEY") | |
# claude_api_key = SecretStr(claude_api_key) if claude_api_key is not None else None #convert the API key to SecretStr | |
langchain_api_key = os.getenv("LANGCHAIN_API_KEY") | |
langchain_project = os.getenv("LANGCHAIN_PROJECT") | |
# Check if the API keys are set | |
if claude_api_key is None: | |
raise EnvironmentError("CLAUDE_API_KEY not set in environment") | |
if langchain_api_key is None: | |
raise EnvironmentError("LANGCHAIN_API_KEY not set in environment") | |
if langchain_project is None: | |
raise EnvironmentError("LANGCHAIN_APP_NAME not set in environment") | |
# Set the LangChain tracing and endpoint environment variables | |
os.environ["LANGCHAIN_TRACING_V2"] = "True" | |
os.environ["LANGCHAIN_ENDPOINT"] = "https://api.smith.langchain.com" | |
os.environ["LANGCHAIN_API_KEY"] = langchain_api_key | |
os.environ["LANGCHAIN_PROJECT"] = langchain_project | |
# Chat prompt template | |
prompt = ChatPromptTemplate.from_messages([ | |
("system", "You are world class technical documentation writer."), | |
("user", "{input}") | |
]) | |
# Streamlit setup | |
st.set_page_config(page_title="Langchain Anthropic Chat", page_icon=":robot:") | |
st.title("Langchain Anthropic Chat") | |
input_text = st.text_input("Enter your question here") | |
submit = st.button("Submit") | |
st.subheader("Output") | |
# Function to get output from LLM | |
def Output_From_LLM(input_text): | |
output_parser = StrOutputParser() | |
llm = ChatAnthropic(anthropic_api_key=claude_api_key,model_name="claude-3-sonnet-20240229", temperature=0.2, max_tokens_to_sample=1024) # type: ignore | |
chain = prompt | llm | output_parser | |
result = chain.invoke({"input": input_text}) | |
return result | |
# Display the output | |
if submit: | |
result = Output_From_LLM(input_text) | |
st.write(result) | |