诸神缄默不语-个人CSDN博文目次
百度需要先认证个人信息才能使用LLM API。
1. 获得 API Key
https://aistudio.baidu.com/account/accessToken
点击复制即可。
2. 撰写代码并实现提问和回复
2.1 用openai包实现调用
- import openai
- import backoff
- client = openai.OpenAI(
- api_key=OPENAI_API_KEY,
- base_url="https://aistudio.baidu.com/llm/lmapi/v3"
- )
- LLM_MODEL="ernie-3.5-8k"
- @backoff.on_exception(backoff.expo, (openai.RateLimitError, openai.APITimeoutError))
- def llm_check_search(query, msg_history=None, llm_model=LLM_MODEL):
- msg_history = msg_history or []
- new_msg_history = msg_history + [{"role": "user", "content": query}]
- response = client.chat.completions.create(
- model=llm_model,
- messages=[*new_msg_history],
- max_tokens=30
- ).choices[0].message.content
-
- # 返回 LLM 的响应
- return response
- print(llm_check_search("你是谁?"))
复制代码 输出:
- 我是文心一言,百度研发的知识增强大语言模型。我能够回答各种问题,提供相关的知识和信息,并且可以进行文本创
- 作和知识推理等多种任务。如果您有任何问题或需要帮助,请随时告诉我。
复制代码 2.2 用openai包实现流式调用
流式调用就是大模型每次生成一点就返回一点,用户在前端可以更快地看到前半部分内容:
- import openai
- import backoff
- client = openai.OpenAI(
- api_key=OPENAI_API_KEY,
- base_url="https://aistudio.baidu.com/llm/lmapi/v3"
- )
- LLM_MODEL="ernie-3.5-8k"
- @backoff.on_exception(backoff.expo, (openai.RateLimitError, openai.APITimeoutError))
- def llm_check_search(query, msg_history=None, llm_model=LLM_MODEL):
- msg_history = msg_history or []
- new_msg_history = msg_history + [{"role": "user", "content": query}]
- response = client.chat.completions.create(
- model=llm_model,
- messages=[*new_msg_history],
- max_tokens=30,
- stream=True
- )
- for chunk in response:
- chunk_content = chunk.choices[0].delta.content
- if chunk_content:
- print(chunk_content)
- llm_check_search("你是谁?")
复制代码 输出:
- 我是百度
- 公司研发
- 的知识增强
- 大语言
- 模型,
- 我的中文名
- 是文心
- 一言,
- 英文名是
- ERNIE
- Bot。
- 我可以完成的任务
- 包括知识
- 问答,
- 文本创作
- ,知识
- 推理,
- 数学计算
- ,代码
- 理解与编写
- ,作画
- ,翻译
- 等。
- 如果您有任何
- 问题,
- 请随时
- 向我提问
- 。
复制代码 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文件写如下代码:
- import gradio as gr
- from try_wenxinyiyan1 import llm_check_search
- demo = gr.Interface(
- fn=llm_check_search,
- inputs=["text"],
- outputs=["text"],
- )
- demo.launch()
复制代码 运行后打开给出的网址(http://127.0.0.1:7860)效果如图所示:
3.2 文心一言风格UI
- import gradio as gr
- from try_wenxinyiyan1 import llm_check_search
- # 修改自定义 CSS
- custom_css = """
- body {
- background-color: #f0f8ff; /* 淡蓝色背景 */
- }
- .container {max-width: 730px; margin: auto; padding-top: 0;}
- .title-container {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- margin-top: 5rem;
- margin-bottom: 2rem;
- }
- .main-title {
- font-size: 2.5em;
- font-weight: bold;
- color: #1e90ff; /* 深蓝色标题 */
- display: flex;
- align-items: center;
- justify-content: center;
- }
- .main-title img {
- width: 40px;
- height: 40px;
- margin-right: 10px;
- filter: invert(39%) sepia(95%) saturate(1095%) hue-rotate(194deg) brightness(103%) contrast(101%); /* 将图标改为蓝色 */
- }
- .powered-by {
- font-size: 0.8em;
- color: #4682b4; /* 钢蓝色 */
- margin-top: 0.5rem;
- }
- #component-1 {
- border: none !important;
- box-shadow: none !important;
- background: none !important;
- }
- #component-1 .form {
- border: 1px solid #87cefa; /* 淡蓝色边框 */
- border-radius: 4px;
- padding: 10px;
- background-color: white;
- }
- .button-container {
- display: flex;
- flex-direction: column;
- align-items: center;
- }
- .search-button.primary {
- min-width: 120px !important;
- justify-content: center !important;
- background-color: #1e90ff !important; /* 深蓝色按钮 */
- color: white !important;
- border: none !important;
- }
- .search-button.primary:hover {
- background-color: #4169e1 !important; /* 悬停时稍深的蓝色 */
- }
- .search-button.primary span {
- margin: 0 auto !important;
- }
- """
- # 修改自定义 HTML 标题
- custom_title = """
- <div class="title-container">
- <div class="main-title">
- <img src="https://img.icons8.com/ios-filled/50/000000/search--v1.png" alt="Search Icon"/>
- <span>AI问答机</span>
- </div>
- <div class="powered-by">Powered by 文心大模型</div>
- </div>
- """
- with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as iface:
- gr.HTML(custom_title)
- with gr.Column(elem_classes="container"):
- query_input = gr.Textbox(
- lines=1,
- placeholder="想对文心一言问什么?",
- label=None,
- container=False,
- )
- gr.Examples(
- examples=[["火鸡好吃吗?"], ["感恩节的来源是什么?"], ["哲学专业学什么?"]],
- inputs=query_input,
- )
- with gr.Column(elem_classes="button-container"):
- submit_button = gr.Button("搜索一下", elem_classes="search-button primary")
- output = gr.Markdown()
- submit_button.click(fn=llm_check_search, inputs=query_input, outputs=output)
- if __name__ == "__main__":
- 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企服之家,中国第一个企服评测及商务社交产业平台。 |