如何调用百度文心一言API实现智能问答

鼠扑  论坛元老 | 2024-12-2 00:48:54 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 1070|帖子 1070|积分 3210

诸神缄默不语-个人CSDN博文目次
百度需要先认证个人信息才能使用LLM API。

  
1. 获得 API Key

https://aistudio.baidu.com/account/accessToken

点击复制即可。
2. 撰写代码并实现提问和回复

2.1 用openai包实现调用

  1. import openai
  2. import backoff
  3. client = openai.OpenAI(
  4.     api_key=OPENAI_API_KEY,
  5.     base_url="https://aistudio.baidu.com/llm/lmapi/v3"
  6. )
  7. LLM_MODEL="ernie-3.5-8k"
  8. @backoff.on_exception(backoff.expo, (openai.RateLimitError, openai.APITimeoutError))
  9. def llm_check_search(query, msg_history=None, llm_model=LLM_MODEL):
  10.     msg_history = msg_history or []
  11.     new_msg_history = msg_history + [{"role": "user", "content": query}]
  12.     response = client.chat.completions.create(
  13.         model=llm_model,
  14.         messages=[*new_msg_history],
  15.         max_tokens=30
  16.     ).choices[0].message.content
  17.    
  18.     # 返回 LLM 的响应
  19.     return response
  20. print(llm_check_search("你是谁?"))
复制代码
输出:
  1. 我是文心一言,百度研发的知识增强大语言模型。我能够回答各种问题,提供相关的知识和信息,并且可以进行文本创
  2. 作和知识推理等多种任务。如果您有任何问题或需要帮助,请随时告诉我。
复制代码
2.2 用openai包实现流式调用

流式调用就是大模型每次生成一点就返回一点,用户在前端可以更快地看到前半部分内容:
  1. import openai
  2. import backoff
  3. client = openai.OpenAI(
  4.     api_key=OPENAI_API_KEY,
  5.     base_url="https://aistudio.baidu.com/llm/lmapi/v3"
  6. )
  7. LLM_MODEL="ernie-3.5-8k"
  8. @backoff.on_exception(backoff.expo, (openai.RateLimitError, openai.APITimeoutError))
  9. def llm_check_search(query, msg_history=None, llm_model=LLM_MODEL):
  10.     msg_history = msg_history or []
  11.     new_msg_history = msg_history + [{"role": "user", "content": query}]
  12.     response = client.chat.completions.create(
  13.         model=llm_model,
  14.         messages=[*new_msg_history],
  15.         max_tokens=30,
  16.         stream=True
  17.     )
  18.     for chunk in response:
  19.         chunk_content = chunk.choices[0].delta.content
  20.         if chunk_content:
  21.             print(chunk_content)
  22. llm_check_search("你是谁?")
复制代码
输出:
  1. 我是百度
  2. 公司研发
  3. 的知识增强
  4. 大语言
  5. 模型,
  6. 我的中文名
  7. 是文心
  8. 一言,
  9. 英文名是
  10. ERNIE
  11. Bot。
  12. 我可以完成的任务
  13. 包括知识
  14. 问答,
  15. 文本创作
  16. ,知识
  17. 推理,
  18. 数学计算
  19. ,代码
  20. 理解与编写
  21. ,作画
  22. ,翻译
  23. 等。
  24. 如果您有任何
  25. 问题,
  26. 请随时
  27. 向我提问
复制代码
2.3 用openai包实现工具调用

在create()方法中参加tools参数,描述一系列可用的函数。

parameters的值是一个Json Schema。
Object 的字字段用properties描述,array子字段类型
用items描述,可以相互嵌套界说。这样就可以描述任意复杂的Json规范了。
示例入参:{"location": ["北京", "天津"], "date": "2024-01-01"}
tool_choice入参:默认是auto,标识模型自己选择是否使用工具。
None代表不使用工具,Required代表逼迫使用指定的工具。
2.4 构建智能体


2.5 文生图


2.6 图生图


3. 用gradio建立大模型问答网站

我没有专门写一篇介绍gradio的文章,就直接拿这篇博文作为简单示例性教程了。
我看这个模块还挺好使的。
3.1 gradio原生UI

假设本文2.1节的代码写在try_wenxinyiyan1.py中,我们在同目次下新建一个Python文件写如下代码:
  1. import gradio as gr
  2. from try_wenxinyiyan1 import llm_check_search
  3. demo = gr.Interface(
  4.     fn=llm_check_search,
  5.     inputs=["text"],
  6.     outputs=["text"],
  7. )
  8. demo.launch()
复制代码
运行后打开给出的网址(http://127.0.0.1:7860)效果如图所示:

3.2 文心一言风格UI

  1. import gradio as gr
  2. from try_wenxinyiyan1 import llm_check_search
  3. # 修改自定义 CSS
  4. custom_css = """
  5. body {
  6.     background-color: #f0f8ff;  /* 淡蓝色背景 */
  7. }
  8. .container {max-width: 730px; margin: auto; padding-top: 0;}
  9. .title-container {
  10.     display: flex;
  11.     flex-direction: column;
  12.     align-items: center;
  13.     justify-content: center;
  14.     margin-top: 5rem;
  15.     margin-bottom: 2rem;
  16. }
  17. .main-title {
  18.     font-size: 2.5em;
  19.     font-weight: bold;
  20.     color: #1e90ff;  /* 深蓝色标题 */
  21.     display: flex;
  22.     align-items: center;
  23.     justify-content: center;
  24. }
  25. .main-title img {
  26.     width: 40px;
  27.     height: 40px;
  28.     margin-right: 10px;
  29.     filter: invert(39%) sepia(95%) saturate(1095%) hue-rotate(194deg) brightness(103%) contrast(101%);  /* 将图标改为蓝色 */
  30. }
  31. .powered-by {
  32.     font-size: 0.8em;
  33.     color: #4682b4;  /* 钢蓝色 */
  34.     margin-top: 0.5rem;
  35. }
  36. #component-1 {
  37.     border: none !important;
  38.     box-shadow: none !important;
  39.     background: none !important;
  40. }
  41. #component-1 .form {
  42.     border: 1px solid #87cefa;  /* 淡蓝色边框 */
  43.     border-radius: 4px;
  44.     padding: 10px;
  45.     background-color: white;
  46. }
  47. .button-container {
  48.     display: flex;
  49.     flex-direction: column;
  50.     align-items: center;
  51. }
  52. .search-button.primary {
  53.     min-width: 120px !important;
  54.     justify-content: center !important;
  55.     background-color: #1e90ff !important;  /* 深蓝色按钮 */
  56.     color: white !important;
  57.     border: none !important;
  58. }
  59. .search-button.primary:hover {
  60.     background-color: #4169e1 !important;  /* 悬停时稍深的蓝色 */
  61. }
  62. .search-button.primary span {
  63.     margin: 0 auto !important;
  64. }
  65. """
  66. # 修改自定义 HTML 标题
  67. custom_title = """
  68. <div class="title-container">
  69.     <div class="main-title">
  70.         <img src="https://img.icons8.com/ios-filled/50/000000/search--v1.png" alt="Search Icon"/>
  71.         <span>AI问答机</span>
  72.     </div>
  73.     <div class="powered-by">Powered by 文心大模型</div>
  74. </div>
  75. """
  76. with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as iface:
  77.     gr.HTML(custom_title)
  78.     with gr.Column(elem_classes="container"):
  79.         query_input = gr.Textbox(
  80.             lines=1,
  81.             placeholder="想对文心一言问什么?",
  82.             label=None,
  83.             container=False,
  84.         )
  85.         gr.Examples(
  86.             examples=[["火鸡好吃吗?"], ["感恩节的来源是什么?"], ["哲学专业学什么?"]],
  87.             inputs=query_input,
  88.         )
  89.         with gr.Column(elem_classes="button-container"):
  90.             submit_button = gr.Button("搜索一下", elem_classes="search-button primary")
  91.         output = gr.Markdown()
  92.     submit_button.click(fn=llm_check_search, inputs=query_input, outputs=output)
  93. if __name__ == "__main__":
  94.     iface.launch()
复制代码
效果:

3.3 gradio其他介绍


  • flag按钮是用来保存输入输出信息到当地的
  • 在launch()函数中设置参数share=True就可以公开分享链接
4. 参数介绍


  • messages

    • role:system / user / assistant / tool
    • content
    • tool_calls(assistant信息调用工具时放置工具信息)
    • tool_call_id(tool信息中对应assistant信息中tool_calls值的id键的值)

5. 本文撰写过程中参考的网络资料


  • 文心一言官方课程“乘风季·开辟者进阶计划训练营课程”

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

鼠扑

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表