Skip to main content

引用来源 (Cite sources)

本笔记本展示了如何使用OpenAI函数的能力从文本中提取引用。

from langchain.chains import create_citation_fuzzy_match_chain
from langchain.chat_models import ChatOpenAI
    /Users/harrisonchase/.pyenv/versions/3.9.1/envs/langchain/lib/python3.9/site-packages/deeplake/util/check_latest_version.py:32: UserWarning: A newer version of deeplake (3.6.4) is available. It's recommended that you update to the latest version using `pip install -U deeplake`.
warnings.warn(
question = "作者在大学期间做了什么?"
context = """
我的名字是Jason Liu,我在加拿大多伦多长大,但我出生在中国。
我上了一所艺术高中,但在大学里我学习了计算数学和物理学。
作为合作的一部分,我在包括Stitchfix、Facebook在内的许多公司工作过。
我还在滑铁卢大学创办了数据科学俱乐部,并担任该俱乐部的主席两年。
"""
llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613")
chain = create_citation_fuzzy_match_chain(llm)
result = chain.run(question=question, context=context)
print(result)
    question='作者在大学期间做了什么?' answer=[FactWithEvidence(fact='作者在大学里学习了计算数学和物理学。', substring_quote=['在大学里我学习了计算数学和物理学']), FactWithEvidence(fact='作者在滑铁卢大学创办了数据科学俱乐部,并担任该俱乐部的主席两年。', substring_quote=['在滑铁卢大学创办了数据科学俱乐部', '主席两年'])]
def highlight(text, span):
return (
"..."
+ text[span[0] - 20 : span[0]]
+ "*"
+ "\033[91m"
+ text[span[0] : span[1]]
+ "\033[0m"
+ "*"
+ text[span[1] : span[1] + 20]
+ "..."
)
for fact in result.answer:
print("陈述:", fact.fact)
for span in fact.get_spans(context):
print("引用:", highlight(context, span))
print()
    陈述: 作者在大学里学习了计算数学和物理学。
引用: ...艺术高中,但*在大学里我学习了计算数学和物理学*。
作为合作的一部分,我...

陈述: 作者在滑铁卢大学创办了数据科学俱乐部,并担任该俱乐部的主席两年。
引用: ...x, Facebook.
我还*在滑铁卢大学创办了数据科学俱乐部*,并担任该俱乐部的...
引用: ...erloo and I was the *president of the club for 2 years*.
...