Python中類型注解Literal的實現(xiàn)
查看LangChain源碼時,發(fā)現(xiàn)Literal:
class Document(BaseMedia):
"""Class for storing a piece of text and associated metadata.
!!! note
`Document` is for **retrieval workflows**, not chat I/O. For sending text
to an LLM in a conversation, use message types from `langchain.messages`.
Example:
```python
from langchain_core.documents import Document
document = Document(
page_content="Hello, world!", metadata={"source": "https://example.com"}
)
```
"""
page_content: str
"""String text."""
type: Literal["Document"] = "Document"
作用:靜態(tài)代碼檢查時,如果type為其他值,即!="Document",會發(fā)生報錯。 注:在不實際運行程序(不執(zhí)行代碼)的情況下,通過分析源代碼的文本結(jié)構(gòu)來找出潛在的錯誤。
進一步,LangChain 框架中的深層作用
序列化時的“防偽標簽” 當 LangChain 將 Document 對象轉(zhuǎn)換成 JSON 字符串時,type: Literal["Document"] 保證了輸出的 JSON 里一定會包含這個標簽 如下:
print(f"轉(zhuǎn)換格式后:\n{json.dumps(document1_json, ensure_ascii=False, indent=2)}")
# 轉(zhuǎn)換格式后,{
# "lc": 1,
# "type": "constructor",
# "id": [
# "langchain",
# "schema",
# "document",
# "Document"
# ],
# "kwargs": {
# "metadata": {
# "author": "張三",
# "page": 10
# },
# "page_content": "LangChain 是一個用于開發(fā)大語言模型應用的框架。",
# "type": "Document"
# }
# }
配合 Pydantic 的運行時校驗 Pydantic 會直接拋出驗證錯誤,防止臟數(shù)據(jù)污染系統(tǒng)
例子:
from pydantic import BaseModel
from typing import Literal
class MyClass(BaseModel):
type: Literal["red"] = "red"
obj = MyClass()
obj.type = "Image" # ? Pydantic 會在運行時拋出 ValidationError
到此這篇關(guān)于Python中類型注解Literal的實現(xiàn)的文章就介紹到這了,更多相關(guān)Python 類型注解Literal內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
膠水語言Python與C/C++的相互調(diào)用的實現(xiàn)
這篇文章主要介紹了膠水語言Python與C/C++的相互調(diào)用的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-05-05
Python函數(shù)any()和all()的用法及區(qū)別介紹
any函數(shù):any(x),只要x中有一個不為空,0,false就返回True,否則返回False。all(x)函數(shù)必須x中的所有元素均不為空,0,false才會返回True,否則返回False。接下來通過本文給大家介紹Python函數(shù)any()和all()的用法及區(qū)別介紹,需要的朋友參考下吧2018-09-09
python 實現(xiàn) hive中類似 lateral view explode的功能示例
這篇文章主要介紹了python 實現(xiàn) hive中類似 lateral view explode的功能示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05
Python 實現(xiàn)將numpy中的nan和inf,nan替換成對應的均值
這篇文章主要介紹了Python 實現(xiàn)將numpy中的nan和inf,nan替換成對應的均值,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
Python可變參數(shù)會自動填充前面的默認同名參數(shù)實例
今天小編就為大家分享一篇Python可變參數(shù)會自動填充前面的默認同名參數(shù)實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11

