提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 安装对应的包
- 启动ollama
- 启动llama2大模型(新开一个终端)
- python接口对话
- streamlit对话
安装对应的包
# linux 安装curl -fsSL https://ollama.com/install.sh | shpip install ollamapip install streamlit
启动ollama
ollama serve
启动llama2大模型(新开一个终端)
ollama pull llama2
ollama run llama2
python接口对话
import ollamaresponse = ollama.chat(model='llama2', messages=[{'role': 'user','content': '为什么天空是蓝色的?',},
])
print(response['message']['content'])
天空呈现蓝色调是因为光线的特定波长被空气中的分子和微粒散射的结果。当阳光通过地球的大气层时,它包含了各种波长的光线,从紫色到红色。其中一部分蓝光和少量紫外线会穿过大气层到达我们的眼睛,而其他波长的光则会被大气的分子和悬浮在空气中的微粒(如氮气和氧气分子、臭氧和灰尘)散射。散射过程遵循物理学中的瑞利-贾可夫定律,该定律指出当波长较短的电磁波(如蓝光)遇到气体分子的自由电子时,它们更有可能被偏转角度较大的方向散射出去;而波长较长的光线(如红光)则不太容易被散射。这就是为什么天空在日出和日落时会呈现出鲜艳的橙黄色,因为这时太阳光中的蓝色成分已经被大量散射了,而红色光线穿透大气层的能力相对较强。此外,由于地球的自转,我们观察到的天空是左右不对称的。从地球上看向太空的方向(例如北方),蓝光会被更多地散射回来,因此天空看起来更蓝。而在南边,蓝光已经被更多的大气分子和灰尘吸收或反射了,所以天空的颜色会相对较暗。这种偏振效应也解释了为什么我们在夜晚看到的星空通常是黑暗的,而白天则是明亮的蓝色背景。
streamlit对话
app.py
# 引入streamlit UI库
import streamlit as st
# 引入 ollama
import ollama
# 获取ollama的模型列表
model_list = ollama.list()
# 设置默认模型名字为 llama2:7b-chat
if "model_name" not in st.session_state:st.session_state["model_name"] = "yi"
# 初始化聊天信息数组
if "messages" not in st.session_state:st.session_state.messages = []
# 设置边栏
with st.sidebar:# 侧边栏的标题st.subheader("Settings")# 下拉框 选择模型, 默认选中llama2option = st.selectbox('Select a model',[model['name'] for model in model_list['models']])st.write('You selected:', option)st.session_state["model_name"] = option
# 页面标题 与llama聊天
st.title(f"Chat with {st.session_state['model_name']}")
# 遍历聊天数组
for message in st.session_state.messages:# 根据角色with st.chat_message(message["role"]):# 输出内容st.markdown(message["content"])if prompt := st.chat_input("What is up?"):st.session_state.messages.append({"role": "user", "content": prompt})with st.chat_message("user"):st.markdown(prompt)with st.chat_message("assistant"):# 大模型返回后就清空输入框message_placeholder = st.empty()full_response = ""for chunk in ollama.chat(model=st.session_state["model_name"],messages=[{"role": m["role"], "content": m["content"]}for m in st.session_state.messages],# 逐渐打出stream=True,):if 'message' in chunk and 'content' in chunk['message']:full_response += (chunk['message']['content'] or "")message_placeholder.markdown(full_response + "▌")message_placeholder.markdown(full_response)st.session_state.messages.append({"role": "assistant", "content": full_response})
再开一个终端,streamlit run app.py
[ollama模型](https://ollama.com/library)
[https://juejin.cn/post/7346919387351859234?share_token=2936809a-a663-4704-94f2-3c48d50d3ade]
[https://juejin.cn/post/7347667306460577843]
[https://zhuanlan.zhihu.com/p/679893306]
[https://zhuanlan.zhihu.com/p/686952702]
[https://sspai.com/post/85193#!]
[https://qwen.readthedocs.io/zh-cn/latest/run_locally/ollama.html]
[https://blog.csdn.net/weixin_40425640/article/details/136700562]