You-shen commited on
Commit
4191d2d
·
verified ·
1 Parent(s): 1e896e0

Create pre.py

Browse files
Files changed (1) hide show
  1. pre.py +151 -0
pre.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from langchain_openai import ChatOpenAI
3
+ from langchain_core.messages import (
4
+ AIMessage,
5
+ BaseMessage,
6
+ HumanMessage,
7
+ SystemMessage,
8
+ ToolMessage,
9
+ )
10
+ import uuid
11
+ from typing import Dict, List
12
+ from langchain_core.pydantic_v1 import BaseModel, Field
13
+ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
14
+ from langchain_core.output_parsers import StrOutputParser, PydanticToolsParser
15
+
16
+ os.environ["OPENAI_API_KEY"] = "sb-6a683cb3bd63a9b72040aa2dd08feff8b68f08a0e1d959f5"
17
+ os.environ['OPENAI_BASE_URL'] = "https://api.openai-sb.com/v1/"
18
+ llm=ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0.6)
19
+
20
+ denoise_template="""
21
+ 给定的text是一段新闻,你需要对该新闻进行适当的去噪\
22
+ 要求:
23
+ 去除所有多余的信息,保持核心内容的准确性和简洁性。\
24
+ 删除冗余的细节、无关的修饰词和不必要的重复信息。\
25
+ 确保最终文本清晰、简洁,并且能够准确传达主要信息。\
26
+ 对于关系到新闻正确性的关键信息要保留,比如时间、地点、人物等等
27
+ text:{text}
28
+ """
29
+ denoise_prompt=ChatPromptTemplate.from_template(denoise_template)
30
+ denoise_chain=denoise_prompt | llm | StrOutputParser()
31
+
32
+ class SubClaim(BaseModel):
33
+
34
+ """Assess the truthfulness of a sub_claim in a news article."""
35
+ sub_claim: str = Field(..., description="A specific sub-claim from the news article.")
36
+
37
+ examples = []
38
+ news_article = "2024年,普京参观哈尔滨工业大学,并在哈工大礼堂发表演讲。"
39
+ queries = [
40
+ SubClaim(sub_claim="2024年,普京参观了哈尔滨工业大学。"),
41
+ SubClaim(sub_claim="普京在哈工大礼堂发表演讲。"),
42
+ ]
43
+ examples.append({"input": news_article, "tool_calls": queries})
44
+
45
+ news_article = "联合国对一个被指控侵犯人权的国家实施了新的制裁,这是一项历史性举措。制裁包括旅行禁令、资产冻结和贸易限制。这一决定是在人权组织进行广泛调查和报告后做出的。"
46
+ queries = [
47
+ SubClaim(sub_claim="联合国对一个被指控侵犯人权的国家实施了新的制裁。"),
48
+ SubClaim(sub_claim="对其实施的制裁包括旅行禁令、资产冻结和贸易限制。"),
49
+ SubClaim(sub_claim="实施制裁这一决定是在人权组织进行广泛调查和报告后作出的。"),
50
+ ]
51
+ examples.append({"input": news_article, "tool_calls": queries})
52
+
53
+ news_article = "9月1日,连续复读16年,35岁的唐尚珺到华南师范大学报到。唐尚珺面对记者采访时坦言,毕业时已近四十岁,找工作难度很大,计划大学期间创业。"
54
+ queries = [
55
+ SubClaim(sub_claim="9月1日,35岁的唐尚珺到华南师范大学报到。"),
56
+ SubClaim(sub_claim="唐尚珺已经连续复读了16年。"),
57
+ SubClaim(sub_claim="唐尚珺面对记者采访时坦言,毕业时已近四十岁。找工作难度很大,计划大学期间创业。"),
58
+ SubClaim(sub_claim="唐尚珺面对记者采访时坦言,找工作难度很大,计划大学期间创业。")
59
+ ]
60
+ examples.append({"input": news_article, "tool_calls": queries})
61
+
62
+ news_article = "Scientists have discovered a new exoplanet that is potentially habitable. The planet, named Proxima b, is located in the habitable zone of its star, Proxima Centauri, and has conditions that could support liquid water. The discovery was made using the latest data from the European Southern Observatory."
63
+ queries = [
64
+ SubClaim(sub_claim="Scientists have discovered a new exoplanet that is potentially habitable."),
65
+ SubClaim(sub_claim="The planet, named Proxima b, is located in the habitable zone of its star, Proxima Centauri."),
66
+ SubClaim(sub_claim="Proxima b has conditions that could support liquid water."),
67
+ SubClaim(sub_claim="The discovery was made using the latest data from the European Southern Observatory."),
68
+ ]
69
+ examples.append({"input": news_article, "tool_calls": queries})
70
+
71
+ news_article = "The government has announced a new health initiative aimed at reducing childhood obesity by 20% over the next five years. The initiative includes increased funding for physical education programs in schools, public awareness campaigns, and subsidies for healthy school lunches. Critics argue that the plan does not address the root causes of obesity."
72
+ queries = [
73
+ SubClaim(sub_claim="The government has announced a new health initiative aimed at reducing childhood obesity by 20% over the next five years."),
74
+ SubClaim(sub_claim="The initiative includes increased funding for physical education programs in schools."),
75
+ SubClaim(sub_claim="The initiative includes public awareness campaigns."),
76
+ SubClaim(sub_claim="The initiative includes subsidies for healthy school lunches."),
77
+ SubClaim(sub_claim="Critics argue that the plan does not address the root causes of obesity."),
78
+ ]
79
+ examples.append({"input": news_article, "tool_calls": queries})
80
+
81
+ news_article = "2024年,一项新技术被开发出来,可以在10分钟内为电动汽车充满电。这一突破是由麻省理工学院的一��科学家团队实现的。这项技术有望彻底改变电动汽车行业。"
82
+ queries = [
83
+ SubClaim(sub_claim="2024年,一项新技术被开发出来,可以在短短10分钟内为电动汽车充满电。"),
84
+ SubClaim(sub_claim="这一突破是由麻省理工学院的一个科学家团队实现的。"),
85
+ SubClaim(sub_claim="这项快速充满电的技术有望彻底改变电动汽车行业。"),
86
+ ]
87
+ examples.append({"input": news_article, "tool_calls": queries})
88
+ def tool_example_to_messages(example: Dict) -> List[BaseMessage]:
89
+ messages: List[BaseMessage] = [HumanMessage(content=example["input"])]
90
+ openai_tool_calls = []
91
+ for tool_call in example["tool_calls"]:
92
+ openai_tool_calls.append(
93
+ {
94
+ "id": str(uuid.uuid4()),
95
+ "type": "function",
96
+ "function": {
97
+ "name": tool_call.__class__.__name__,
98
+ "arguments": tool_call.json(),
99
+ },
100
+ }
101
+ )
102
+ messages.append(
103
+ AIMessage(content="", additional_kwargs={"tool_calls": openai_tool_calls})
104
+ )
105
+ tool_outputs = example.get("tool_outputs") or [
106
+ "This is an example of a correct usage of this tool. Make sure to continue using the tool this way."
107
+ ] * len(openai_tool_calls)
108
+ for output, tool_call in zip(tool_outputs, openai_tool_calls):
109
+ messages.append(ToolMessage(content=output, tool_call_id=tool_call["id"]))
110
+ return messages
111
+ example_msgs = [msg for ex in examples for msg in tool_example_to_messages(ex)]
112
+
113
+ system="""
114
+ 您是一名新闻分析专家,您的任务是将给定的新闻文章精准地拆解为独立的句子或子目标。\
115
+ 请确保每个句子或子目标都代表一个独立的事实或观点,以便后续的真实性验证。\
116
+ 操作指南:
117
+ 1.句子拆解:逐步拆解新闻文章,将其分解为简明、独立的句子或子目标。每个句子或子目标应聚焦于一个核心事实或概念,避免内容混杂或复杂表达。\
118
+ 2.保持原意:确保每个句子或子目标保持新闻原文的表述和意图,不做任何改写或释义。
119
+ """
120
+ prompt = ChatPromptTemplate.from_messages(
121
+ [
122
+ ("system", system),
123
+ MessagesPlaceholder("examples", optional=True),
124
+ ("human", "{claim}"),
125
+ ]
126
+ )
127
+
128
+ llm_with_tools = llm.bind_tools([SubClaim])
129
+ parser = PydanticToolsParser(tools=[SubClaim])
130
+ query_analyzer_with_examples = (
131
+ prompt.partial(examples=example_msgs) | llm_with_tools | parser
132
+ )
133
+
134
+ trans_template="""
135
+ The question is a list such as [SubQuery (sub_query='...',SubQuery (sub_query='...')...]. \
136
+ There may be one or more sub_query. \
137
+ You need to extract the content from each sub_query. \
138
+ Just need to return the extracted content without any introduction
139
+ Claim: {question}
140
+ """
141
+ trans_template = ChatPromptTemplate.from_template(trans_template)
142
+ tran_chain = trans_template | llm | StrOutputParser()
143
+ def capture_sub_queries(claim: str):
144
+ result = query_analyzer_with_examples.invoke({"claim": claim})
145
+ if isinstance(result, list):
146
+ sub_queries = result
147
+ else:
148
+ sub_queries = []
149
+ result=tran_chain.invoke({"question":sub_queries})
150
+ return result
151
+