专属编程笔记

Utils目录作用

在软件开发中,Utils(或 Utilities)目录通常用于存放一些通用的、不特定于任何模块的工具类或辅助函数。这些工具类或函数为整个应用程序或多个模块提供便利的功能支持,使得代码更加模块化、易于维护和重用。Utils目录可能包含以下类型的文件或类:

  1. 辅助类(Helper Classes):提供通用方法,如日期时间处理、字符串操作、文件处理等。
  2. 自定义异常(Custom Exceptions):用于定义项目中特定的异常处理。
  3. 配置管理(Configuration Management):处理应用程序设置和配置加载。
  4. 日志记录(Logging):提供日志记录和管理功能。
  5. 数据校验(Data Validation):包含用于校验数据有效性的工具。
  6. 加密解密(Encryption/Decryption):提供加密和解密服务的工具。
  7. 网络通信(Networking):包含处理网络请求和响应的实用工具。
  8. 数据库操作(Database Operations):提供数据库连接、查询构建等工具。
  9. 缓存处理(Caching):实现缓存机制的工具,用于提高应用性能。
  10. 第三方库封装(Wrapper for Third-party Libraries):为第三方库提供统一的接口或封装复杂操作。

Utils目录的设计目的在于避免代码重复,并确保在整个项目中以一致的方式处理共通任务。这样做可以提高开发效率,降低维护成本,并确保代码的整洁性和可读性。

if __name__ == "__main__":作用

这里的__name__是Python的一个内置变量,它代表了当前模块的名称。当模块被直接运行时,__name__的值会被设置为"__main__"。如果模块被导入到另一个模块中,__name__的值就会被设置为该模块的名称。

if __name__ == "__main__":的作用是,当这个模块被直接运行时,位于该判断语句下的代码(通常是main()函数)会被执行。如果这个模块被导入到另一个模块中,main()函数则不会被执行。

这样做的好处是,你可以将模块中的功能代码和执行代码分离,使得这个模块既可以作为独立的脚本运行,也可以作为一个功能模块被其他脚本导入和使用

def main():
    print("This is the main function.")

def helper_function():
    print("This is a helper function.")

if __name__ == "__main__":
    main()

在这个例子中,如果这个脚本被直接运行,它会打印出"This is the main function."。如果这个脚本被导入到另一个脚本中,helper_function()可以被调用,但main()不会自动执行。

细节用法

def _format_long_term_memory(task_description: str, memory: BaseChatMemory) -> str:
    return memory.load_memory_variables(
        {"prompt": task_description}
    )["history"]

返回类型注解(Return Type Annotation)

  • -> str 表示函数的返回值应该是一个字符串类型。

类型注解(Type Annotations)

  • task_description: str 表示参数 task_description 应该是一个字符串类型
  • memory: BaseChatMemory 表示参数 memory 应该是一个 BaseChatMemory 类型的实例。BaseChat
  • Memory 可能是一个自定义的类,用于表示聊天记忆或对话历史。
    @abstractmethod
    def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]:
        """Return key-value pairs given the text input to the chain."""

抽象方法(Abstract Method)

  • @abstractmethod 是一个装饰器,它用于标记一个方法为抽象方法。这意味着这个方法在抽象类中不需要实现具体的功能,但它要求任何继承了这个抽象类的具体子类都必须实现这个方法。

参数和类型注解(Parameters and Type Annotations)

  • self 是一个特殊的参数,它代表类实例本身。在 Python 的类方法中,self 用來访问属于类的属性和方法。
  • inputs: Dict[str, Any] 表示参数 inputs 应该是一个字典,其中键是字符串类型,值可以是任何类型(Any)。

返回类型注解(Return Type Annotation)

  • -> Dict[str, Any] 表示方法的返回值应该是一个字典,其中键是字符串类型,值可以是任何类型(Any)。
  • 它提供了方法的简要描述。文档字符串通常用于解释方法或函数的用途、参数和返回值。

文档字符串(Docstring):

"""Return key-value pairs given the text input to the chain.""" 是一个文档字符串,它提供了方法的简要描述。文档字符串通常用于解释方法或函数的用途、参数和返回值。

langchain

定义提示模板

需要培养一种,问题挖空的能力,比如需要构建一个分析词语词性的提示词

 你是一名语言学家,请你分析{XXX词}的词性。

from langchain.prompts import PromptTemplate
 
prompt = PromptTemplate(
    input_variables=["product"],
    template="What is a good name for a company that makes {product}?",
)

print(prompt.format(product="colorful socks"))
What is a good name for a company that makes colorful socks?

链: 在多步骤的工作流中组合 LLM 和提示

最核心的链类型是 LLMChain,它由 PromptTemplate 和 LLM 组成。

扩展前面的示例,我们可以构造一个LLMChain.

它接受用户输入,使用 PromptTemplate 对其进行格式化,然后将格式化后的响应传递给LLM

from langchain.prompts import PromptTemplate
from langchain.llms import OpenAI
 
llm = OpenAI(temperature=0.9)
prompt = PromptTemplate(
    input_variables=["product"],
    template="What is a good name for a company that makes {product}?",
)



from langchain.chains import LLMChain
chain = LLMChain(llm=llm, prompt=prompt)




chain.run("colorful socks")
# -> '\n\nSocktastic!'

我们可以通过将多个链组合在一起,或者通过将链与其他组件组合在一起,来构建更复杂的链

调用链的不同方式

返回结果格式(输入,输出)

默认情况下,_ _ call _ _ 返回输入和输出键值。通过将 return _ only _ output 设置为True,可以将其配置为只返回输出键值。

向链中添加内存

Chain 支持将 BaseMemory 对象作为其内存参数,允许 Chain 对象跨多个调用持久存储数据。换句话说,它使 Chain 成为一个有状态对象。

from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory
 
conversation = ConversationChain(
    llm=chat,
    memory=ConversationBufferMemory()
)
 
conversation.run("Answer briefly. What are the first 3 colors of a rainbow?")
# -> The first three colors of a rainbow are red, orange, and yellow.
conversation.run("And the next 4?")
# -> The next four colors of a rainbow are green, blue, indigo, and violet.
 


#'The next four colors of a rainbow are green, blue, indigo, and violet.'
 

聊天记录

缓冲记忆
现在我们展示如何在链中使用这个简单的概念。我们首先展示 ConversationBufferMemory,它只是 ChatMessageHistory 的一个包装器,用于提取变量中的消息。

我们可以首先提取它作为一个字符串。

from langchain.memory import ConversationBufferMemory
 

memory = ConversationBufferMemory()
memory.chat_memory.add_user_message("hi!")
memory.chat_memory.add_ai_message("whats up?")
 

memory.load_memory_variables({})
 

{'history': 'Human: hi!\nAI: whats up?'}
 

我们还可以获取作为消息列表的历史记录

memory = ConversationBufferMemory(return_messages=True)
memory.chat_memory.add_user_message("hi!")
memory.chat_memory.add_ai_message("whats up?")
 

memory.load_memory_variables({})
 

{'history': [HumanMessage(content='hi!', additional_kwargs={}),
  AIMessage(content='whats up?', additional_kwargs={})]}
 

  • 19
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值