整體流程

0 前置操作
API_KEY、SECRET_KEY自行購買
import requests
import json
import logging
API_KEY = "api_key"
SECRET_KEY = "secret_key"
CORPUS_DIR = "./corpus"
LOG_PATH = "./log/dev.txt"
# handler = logging.FileHandler(filename=LOG_PATH, encoding='utf-8')
logging.basicConfig(filename=LOG_PATH,
format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S ',
level=logging.INFO)
logger = logging.getLogger()
# KZT = logging.StreamHandler()
# KZT.setLevel(logging.DEBUG)
# logger.addHandler(KZT)
獲取鑒權(quán)簽名token,以及發(fā)送post請求
def get_access_token():
"""
使用 AK,SK 生成鑒權(quán)簽名(Access Token)
:return: access_token,或是None(如果錯(cuò)誤)
"""
url = "https://aip.baidubce.com/oauth/2.0/token"
params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
access_token = str(requests.post(url, params=params).json().get("access_token"))
logger.info("Starting to 文心一言 chatbot!")
return access_token
def get_response(content, stream=False):
url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token=" + get_access_token()
headers = {}
data = json.dumps({
"messages": [
{
"role": "user",
"content": content
}
],
"stream": stream
})
if stream:
response = requests.request("POST", url, headers=headers, data=data).text
else:
response = requests.request("POST", url, headers=headers, data=data).json()
return response
1 單輪對話
def single_dialogue(corpus_path):
"""
單輪對話
:return:
"""
""
with open(corpus_path, "r", encoding='utf-8') as f:
lines = [line.strip() for line in f.readlines()]
content = "".join(lines)
question = input("請輸入您的問題!")
logger.info(question)
content = content + "Question:" + question
response = get_response(content)
result = response['result']
logger.info(result)
return result
效果:
請輸入您的問題!諸葛亮出生于?
諸葛亮出生于公元181年。
2 多輪對話
def multiple_dialogue(corpus_path):
"""
多輪對話
:return:
"""
# global response, data
# url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token=" + get_access_token() # Ernie-Lite
url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=" + get_access_token() # 文心一言云服務(wù)
with open(corpus_path, "r",encoding='utf-8') as f:
lines = [line.strip() for line in f.readlines()]
content = "".join(lines)
result = ""
count = 1
messages = []
while True:
# 提問,封裝response
question = input("請輸入您的問題:")
if question == "q" or question == 'quit': # 退出規(guī)則
break
logger.info(question)
if count == 1:
content = content + "Question:" + question
else:
content = question
messages.append({"role": "user", "content": content})
data_str = json.dumps({
"messages": messages,
"stream": False
})
response = requests.request("POST", url, data=data_str).json()
# 獲取結(jié)果
result = response['result']
messages.append({"role": "assistant", "content": result})
logger.info(result)
print(f"Answer{count}:{result}")
count += 1
return result
效果:
請輸入您的問題:諸葛亮是哪國的
Answer1:諸葛亮是三國時(shí)期蜀漢丞相。
請輸入您的問題:諸葛亮有哪些貢獻(xiàn)
Answer2:諸葛亮對中國文化的貢獻(xiàn)和對蜀漢政權(quán)的貢獻(xiàn)是不可磨滅的。他的主要貢獻(xiàn)集中在以下幾個(gè)方面:
1. 在政治方面,諸葛亮提出了一系列治國方略,如禮儀治邦、依法治國、任人唯賢、君臣分治等,這些治國方略在今天仍然有重要的現(xiàn)實(shí)意義。
2. 在經(jīng)濟(jì)方面,諸葛亮注重農(nóng)業(yè)和手工業(yè)的發(fā)展,提倡“勤儉節(jié)約”,推行屯田政策,促進(jìn)社會經(jīng)濟(jì)發(fā)展。
3. 在文化方面,諸葛亮編纂了《諸葛亮集》和《出師表》等重要文獻(xiàn),這些文獻(xiàn)對中國文化的發(fā)展具有重要的推動(dòng)作用。
4. 在科技方面,諸葛亮發(fā)明了木牛流馬、連發(fā)弩等,這些發(fā)明對中國古代科技的發(fā)展做出了重要貢獻(xiàn)。
5. 在哲學(xué)方面,諸葛亮提出了“以民為本”、“禮儀為先”等哲學(xué)思想,這些思想對中國古代哲學(xué)的發(fā)展產(chǎn)生了重要影響。
6. 在歷史方面,諸葛亮留下了《三國演義》等重要?dú)v史著作,這些著作對中國歷史文化的傳承和發(fā)展具有重要的推動(dòng)作用。
7. 在教育方面,諸葛亮注重人才培養(yǎng)和教育普及,推行“崇文重教”的政策,對中國古代教育的發(fā)展產(chǎn)生了重要影響。
總之,諸葛亮是中國歷史上偉大的文化名人之一,他的貢獻(xiàn)不僅體現(xiàn)在對中國文化的推動(dòng)和發(fā)展上,也體現(xiàn)在對人類社會的進(jìn)步和發(fā)展上。
請輸入您的問題:后人對諸葛亮的評價(jià)
Answer3:后人對諸葛亮的評價(jià)一般是褒揚(yáng)的。
陳壽曾經(jīng)說過“諸葛亮之為相國也,撫百姓,示儀軌,約官職,從權(quán)制,開誠心,布公道;盡忠益時(shí)者雖仇必賞,犯法怠慢者雖親必罰,服罪輸情者雖重必釋,游辭巧飾者雖輕必戮;善無微而不賞,惡無纖而不貶;庶事精練,物理其本,循名責(zé)實(shí),虛偽不齒;終于邦域 之內(nèi),咸畏 而愛之,刑政雖峻 而無怨者,以其用心平 而勸戒明也”。
唐太宗曾經(jīng)說過:“撥亂整危資樸素,納忠容直在自己。自古埋輪兼釣鱉,何人肯辦斬鯨級”。
宋真宗說過:“蘊(yùn)策定戎,不妨談笑。成功高退,依舊蕭然”。
康熙說過:“讀書好兵,霸王之器。至乃集大成于三略,功蓋一時(shí),名震往古”。
諸葛亮在有限的政治實(shí)踐活動(dòng)中,充分顯示了他的治世之才和緯地之才。他的“法治”理念,盡管與今天的法治內(nèi)涵不盡相同,卻打開了中國古代“法治” 的先河,把中國古代政治文明推向了一個(gè)新的境界。
請輸入您的問題:q
后人對諸葛亮的評價(jià)一般是褒揚(yáng)的。
陳壽曾經(jīng)說過“諸葛亮之為相國也,撫百姓,示儀軌,約官職,從權(quán)制,開誠心,布公道;盡忠益時(shí)者雖仇必賞,犯法怠慢者雖親必罰,服罪輸情者雖重必釋,游辭巧飾者雖輕必戮;善無微而不賞,惡無纖而不貶;庶事精練,物理其本,循名責(zé)實(shí),虛偽不齒;終于邦域 之內(nèi),咸畏 而愛之,刑政雖峻 而無怨者,以其用心平 而勸戒明也”。
唐太宗曾經(jīng)說過:“撥亂整危資樸素,納忠容直在自己。自古埋輪兼釣鱉,何人肯辦斬鯨級”。
宋真宗說過:“蘊(yùn)策定戎,不妨談笑。成功高退,依舊蕭然”。
康熙說過:“讀書好兵,霸王之器。至乃集大成于三略,功蓋一時(shí),名震往古”。
諸葛亮在有限的政治實(shí)踐活動(dòng)中,充分顯示了他的治世之才和緯地之才。他的“法治”理念,盡管與今天的法治內(nèi)涵不盡相同,卻打開了中國古代“法治” 的先河,把中國古代政治文明推向了一個(gè)新的境界。
進(jìn)程已結(jié)束,退出代碼為 0
3 流式單輪對話
def single_dialogue_stream(corpus_path):
"""
流式單輪對話
:return:
"""
with open(corpus_path, "r", encoding='utf-8') as f:
lines = [line.strip() for line in f.readlines()]
content = "".join(lines)
question = input("請輸入您的問題!")
logger.info(question)
content = content + "Question:" + question
response = get_response(content, stream=True)
print(response)
# result = response['result']
# logger.info(result)
# print(result)
# return result
流式與非流式的區(qū)別:輸出的response格式不一致
流式
請輸入您的問題!諸葛亮是哪里人
data: {"id":"as-unikt1hna9","object":"chat.completion","created":1685435336,"sentence_id":0,"is_end":false,"result":"諸葛亮是徐州瑯琊陽都(今山東臨沂市沂南縣)人。","need_clear_history":false,"usage":{"prompt_tokens":344,"completion_tokens":20,"total_tokens":364}}
data: {"id":"as-unikt1hna9","object":"chat.completion","created":1685435337,"sentence_id":1,"is_end":true,"result":"","need_clear_history":false,"usage":{"prompt_tokens":344,"completion_tokens":0,"total_tokens":364}}
常規(guī)文章來源:http://www.zghlxwxcb.cn/news/detail-511163.html
{'id': 'as-vf81wriqi3', 'object': 'chat.completion', 'created': 1685435476, 'result': '根據(jù)歷史記載,諸葛亮是徐州瑯琊陽都(今山東臨沂市沂南縣)人。他的祖籍是泰山郡所在今天山東省泰安市一部分、濟(jì)寧地區(qū)南部及今濰坊市南部。', 'need_clear_history': False, 'usage': {'prompt_tokens': 344, 'completion_tokens': 60, 'total_tokens': 404}}
4 流式多輪對話
類似,可參考多輪對話,修改stream=True文章來源地址http://www.zghlxwxcb.cn/news/detail-511163.html
def multiple_dialogue_stream():
"""
流式多輪對話
:return:
"""
pass
到了這里,關(guān)于文心大模型使用——文心一言API的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!