美文网首页
2024-06-20 langchain 笔记01

2024-06-20 langchain 笔记01

作者: 国服最坑开发 | 来源:发表于2024-06-19 20:56 被阅读0次
    # https://python.langchain.com/v0.2/docs/tutorials/llm_chain/
    import os
    import dotenv
    from langchain_openai import ChatOpenAI
    from langchain_core.messages import HumanMessage, SystemMessage
    from langchain_core.output_parsers import StrOutputParser
    
    dotenv.load_dotenv()
    base_url = os.environ["base_url"]
    api_key = os.environ["api_key"]
    
    
    def sample_01():
        """
        最基础的调用openai的方法
        """
        # 构建gpt
        model = ChatOpenAI(base_url=base_url, api_key=api_key, model="gpt-3.5-turbo")
        messages = [
            SystemMessage(content="Translate the following from English into Chinese"),
            HumanMessage(content="Hi!"),
        ]
        # 返回 AIMessage格式的
        ai_resp = model.invoke(messages)
    
        # 提取 AIMessage 中的 content 信息
        parser = StrOutputParser()
        msg = parser.invoke(ai_resp)
        print(msg)
    
        # 把上面两种对象使用管理串起来,变成一个chain
        chain = model | parser
        print(chain.invoke(messages))
    
    
    from langchain_core.prompts import ChatPromptTemplate
    
    
    def sample_02():
        model = ChatOpenAI(base_url=base_url, api_key=api_key, model="gpt-3.5-turbo")
        
        # 构建一个系统role 的prompt模板
        system_template = "Translate the following into {language}:"
        
        # 生成带变量的 system&user prompt 对话模板
        prompt_template = ChatPromptTemplate.from_messages(
            [("system", system_template), ("user", "{text}")]
        )
        
        # 代入变量,得到最后完整的 prompt对象
        result = prompt_template.invoke({"language":"italian", "text":"hi"})
        
        print(result)
        print(result.to_messages)
        
        parser = StrOutputParser()
        
        # chain 
        chain = prompt_template | model | parser
        
        print(chain.invoke({"language": "italian", "text": "hi"}))
    
    if __name__ == "__main__":
        sample_02()
    
    

    相关文章

      网友评论

          本文标题:2024-06-20 langchain 笔记01

          本文链接:https://www.haomeiwen.com/subject/pufccjtx.html