当前位置:   article > 正文

python和千帆大模型结合回答某乎问题_如何用python调用百度千帆的api进行智能问答

如何用python调用百度千帆的api进行智能问答

有些问题,自己回答的不够好,可以借助大模型来帮忙回答。

一,要实现这个功能,首先需要写一个调用千帆接口的文件qianfan.py。

import requests
import json

# 如下两个参数,需要自己到千帆大模型去申请创建
API_KEY = "xxxxxxx"
SECRET_KEY = "xxxxxxx"


def get_huida(content):
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=" + get_access_token()

    data={
        "messages": [
            {"role": "user", "content": content}
        ],
        # "stream": True
    }
    payload = json.dumps(data)
    headers = {
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    # print(response.json())
    return response.json()


def get_access_token():
    """
    使用 AK,SK 生成鉴权签名(Access Token)
    :return: access_token,或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))


if __name__ == '__main__':
    get_huida('这里是你需要回答的问题?')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40

二、访问某乎接口进行回答。


import requests
import qianfan

session=requests.session()

session.headers={
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36",
}


def get_cookie():
    #使用rpc方式获取到cookie信息,这里需要自己部署一个服务,来和远程的浏览器进行交互
    url = "http://xxx.xxx.xxx/get?project_name=zhihu"
    resp = requests.get(url)
    resp_dict = resp.json()
    cookie = resp_dict['cookie']
    session = requests.session()
    session.headers["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36"
    for item in cookie.split("; "):
        ret = item.split('=')
        session.cookies[ret[0]] = ret[1]
    resp = session.get(url)
    # print(resp.json())
    # print(resp.text)
    return resp.json()

session.headers["Cookie"]=get_cookie().get("cookie")

def get_answer_list(answer_url):
    resp = session.get(answer_url)
    # print(resp.json())
    data = resp.json()['data']
    return data

def task(answer_url):
    data=get_answer_list(answer_url)
    for item in data:
        # print(item)
        url=item['url']
        title=item['question']['title']
        id=item['question']['id']
        # print(title,id,url)
        print("问题是:",title)
        data=qianfan.get_huida("作为知乎达人,请用知乎的模板来回答这个问题:"+title)
        data=qianfan.get_huida(title)
        huida=data.get('result').replace('\n','<p>')
        if huida:
            print("千帆大模型提供的问题是:",huida)
            put_answer(id,huida)
            print("回答成功!")


def put_answer(answerid='12345678',huida='这个问题,我也不知道怎么回答!'):
    put_url=f'https://www.zhihu.com/api/v4/questions/{answerid}/answers?include=is_visible%2Cpaid_info%2Cpaid_info_content%2Cadmin_closed_comment%2Creward_info%2Cannotation_action%2Cannotation_detail%2Ccollapse_reason%2Cis_normal%2Cis_sticky%2Ccollapsed_by%2Csuggest_edit%2Ccomment_count%2Ccan_comment%2Ccontent%2Ceditable_content%2Cvoteup_count%2Creshipment_settings%2Ccomment_permission%2Ccreated_time%2Cupdated_time%2Creview_info%2Crelevant_info%2Cquestion%2Cexcerpt%2Cattachment%2Creaction_instruction%2Cip_info%2Crelationship.is_authorized%2Cvoting%2Cis_thanked%2Cis_author%2Cis_nothelp%2Cis_labeled%3Bmark_infos%5B*%5D.url%3Bauthor.vip_info%2Cbadge%5B*%5D.topics%3Bsettings.table_of_content.enab'
    data={
        "content": f"{huida}",
        "reshipment_settings": "allowed",
        "comment_permission": "all",
        "reward_setting": {"can_reward": False, "tagline": ""},
        "disclaimer_status": "close",
        "disclaimer_type": "none",
        "commercial_report_info": {"is_report": False},
        "commercial_zhitask_bind_info": None,
        "is_report": False,
        "push_activity": True,
        "table_of_contents_enabled": False,
        "thank_inviter_status": "close",
        "thank_inviter": ""
    }
    session.headers['Content-Type']='application/json'
    resp=session.post(put_url,json=data)
    print(resp.json())

if __name__ == '__main__':
    answer_url="https://www.zhihu.com/api/v4/answer-drafts?offset=0&limit=10&include=data%5B*%5D.schedule"
    task(answer_url)



  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/845669
推荐阅读
相关标签
  

闽ICP备14008679号