LangChain 75 打造你自己的OpenAI + LangChain网页应用

LangChain系列文章

  1. LangChain 60 深入理解LangChain 表达式语言23 multiple chains链透传参数 LangChain Expression Language (LCEL)
  2. LangChain 61 深入理解LangChain 表达式语言24 multiple chains链透传参数 LangChain Expression Language (LCEL)
  3. LangChain 62 深入理解LangChain 表达式语言25 agents代理 LangChain Expression Language (LCEL)
  4. LangChain 63 深入理解LangChain 表达式语言26 生成代码code并执行 LangChain Expression Language (LCEL)
  5. LangChain 64 深入理解LangChain 表达式语言27 添加审查 Moderation LangChain Expression Language (LCEL)
  6. LangChain 65 深入理解LangChain 表达式语言28 余弦相似度Router Moderation LangChain Expression Language (LCEL)
  7. LangChain 66 深入理解LangChain 表达式语言29 管理prompt提示窗口大小 LangChain Expression Language (LCEL)
  8. LangChain 67 深入理解LangChain 表达式语言30 调用tools搜索引擎 LangChain Expression Language (LCEL)
  9. LangChain 68 LLM Deployment大语言模型部署方案
  10. LangChain 69 向量数据库Pinecone入门
  11. LangChain 70 Evaluation 评估、衡量在多样化数据上的性能和完整性
  12. LangChain 71 字符串评估器String Evaluation衡量在多样化数据上的性能和完整性
  13. LangChain 72 reference改变结果 字符串评估器String Evaluation
  14. LangChain 73 给结果和参考评分 Scoring Evaluator
  15. LangChain 74 有用的或者有害的helpful or harmful Scoring Evaluator

在这里插入图片描述

笔者写了优化英文邮件的例子,可以选择英式或者美式英文,并选择正式的口吻或者通知的口吻。

此应用程序旨在部署在 Streamlit请注意,在设置 StreamLit 应用程序时,应确保将 OPENAI_API_KEY 上。 添加为机密环境变量。如果用跳板机,还需要设置OPENAI_API_BASE="https://apejhvxcd.cloud.sealos.io/v1"。 可以参考跳板机文章

1. 代码实现:

main.py 实现
github地址:https://github.com/gkamradt/globalize-text-streamlit

import streamlit as st
from langchain.prompts import PromptTemplate
from langchain.llms import OpenAI

template = """
    Below is an email that may be poorly worded.
    Your goal is to:
    - Properly format the email
    - Convert the input text to a specified tone
    - Convert the input text to a specified dialect

    Here are some examples different Tones:
    - Formal: We went to Barcelona for the weekend. We have a lot of things to tell you.
    - Informal: Went to Barcelona for the weekend. Lots to tell you.  

    Here are some examples of words in different dialects:
    - American: French Fries, cotton candy, apartment, garbage, cookie, green thumb, parking lot, pants, windshield
    - British: chips, candyfloss, flag, rubbish, biscuit, green fingers, car park, trousers, windscreen

    Example Sentences from each dialect:
    - American: I headed straight for the produce section to grab some fresh vegetables, like bell peppers and zucchini. After that, I made my way to the meat department to pick up some chicken breasts.
    - British: Well, I popped down to the local shop just the other day to pick up a few bits and bobs. As I was perusing the aisles, I noticed that they were fresh out of biscuits, which was a bit of a disappointment, as I do love a good cuppa with a biscuit or two.

    Please start the email with a warm introduction. Add the introduction if you need to.
    
    Below is the email, tone, and dialect:
    TONE: {tone}
    DIALECT: {dialect}
    EMAIL: {email}
    
    YOUR {dialect} RESPONSE:
"""

prompt = PromptTemplate(
    input_variables=["tone", "dialect", "email"],
    template=template,
)

def load_LLM(openai_api_key):
    """Logic for loading the chain you want to use should go here."""
    # Make sure your openai_api_key is set as an environment variable
    # llm = OpenAI(temperature=.7, openai_api_key=openai_api_key)
    llm = OpenAI(temperature=.7)
    return llm

st.set_page_config(page_title="Globalize Email", page_icon=":robot:")
st.header("Globalize Text")

col1, col2 = st.columns(2)

with col1:
    st.markdown("Often professionals would like to improve their emails, but don't have the skills to do so. \n\n This tool \
                will help you improve your email skills by converting your emails into a more professional format. This tool \
                is powered by [LangChain](https://langchain.com/) and [OpenAI](https://openai.com) and made by \
                [@GregKamradt](https://twitter.com/GregKamradt). \n\n View Source Code on [Github](https://github.com/gkamradt/globalize-text-streamlit/blob/main/main.py)")

with col2:
    st.image(image='TweetScreenshot.png', width=500, caption='https://twitter.com/zgpeace')

st.markdown("## Enter Your Email To Convert")

def get_api_key():
    input_text = st.text_input(label="OpenAI API Key ",  placeholder="Ex: sk-2twmA8tfCb8un4...", key="openai_api_key_input")
    return input_text

openai_api_key = get_api_key()

col1, col2 = st.columns(2)
with col1:
    option_tone = st.selectbox(
        'Which tone would you like your email to have?',
        ('Formal', 'Informal'))
    
with col2:
    option_dialect = st.selectbox(
        'Which English Dialect would you like?',
        ('American', 'British'))

def get_text():
    input_text = st.text_area(label="Email Input", label_visibility='collapsed', placeholder="Your Email...", key="email_input")
    return input_text

email_input = get_text()

if len(email_input.split(" ")) > 700:
    st.write("Please enter a shorter email. The maximum length is 700 words.")
    st.stop()

def update_text_with_example():
    print ("in updated")
    st.session_state.email_input = "Sally I am starts work at yours monday from dave"

st.button("*See An Example*", type='secondary', help="Click to see an example of the email you will be converting.", on_click=update_text_with_example)

st.markdown("### Your Converted Email:")

if email_input:
    # if not openai_api_key:
    #     st.warning('Please insert OpenAI API Key. Instructions [here](https://help.openai.com/en/articles/4936850-where-do-i-find-my-secret-api-key)', icon="⚠️")
    #     st.stop()

    llm = load_LLM(openai_api_key=openai_api_key)

    prompt_with_email = prompt.format(tone=option_tone, dialect=option_dialect, email=email_input)

    formatted_email = llm.invoke(prompt_with_email)

    st.write(formatted_email)

本地运行
LangChain 75 打造你自己的OpenAI + LangChain网页应用_第1张图片
浏览器打开,输入需要优化的email,Command+Enter 即可调用OpenAI api并返回结果。
LangChain 75 打造你自己的OpenAI + LangChain网页应用_第2张图片

2. 部署到streamlit

2.1 点击 New app

LangChain 75 打造你自己的OpenAI + LangChain网页应用_第3张图片

2.2 选择自己的repo, 修改main.py 为Main file path

LangChain 75 打造你自己的OpenAI + LangChain网页应用_第4张图片

2.3 Advanced settings 设置

OPENAI_API_KEY="sk-xxxx"
OPENAI_API_BASE="https://apejhvxcd.cloud.sealos.io/v1"

LangChain 75 打造你自己的OpenAI + LangChain网页应用_第5张图片
Save 并 Deploy

2.4 等待部署完成即可访问

LangChain 75 打造你自己的OpenAI + LangChain网页应用_第6张图片
LangChain 75 打造你自己的OpenAI + LangChain网页应用_第7张图片
LangChain 75 打造你自己的OpenAI + LangChain网页应用_第8张图片

查看实时应用程序:https://globalize.streamlit.app/
此代码的制作过程视频:https://www.youtube.com/watch?v=U_eV8wfMkXU

你可能感兴趣的:(LLM-Large,Language,Models,langchain,prompt,chatgpt,人工智能,python)