单轮对话实现
from openai import OpenAI
try:
client = OpenAI(base_url="http://localhost:11434/v1/", api_key="ollama")
chat_completion = client.chat.completions.create(
messages=[{"role": "user", "content": "你好,请介绍下自己"}], model="llama3"
)
print(chat_completion.choices[0].message.content)
except Exception as e:
print(f"错误: {e}")
多轮对话实现
from openai import OpenAI
def run_chat_session():
try:
client = OpenAI(base_url="http://localhost:11434/v1/", api_key="ollama")
print("聊天开始!输入 'exit' 或 'quit' 退出")
print("-" * 40)
chat_history = []
while True:
try:
user_input = input("用户:").strip()
if user_input.lower() in ["exit", "quit", "退出"]:
print("退出对话。")
break
if not user_input:
print("请输入有效内容")
continue
chat_history.append({"role": "user", "content": user_input})
chat_completion = client.chat.completions.create(
messages=chat_history, model="llama3"
)
model_response = chat_completion.choices[0]
print("AI:", model_response.message.content)
print("-" * 40)
chat_history.append(
{"role": "assistant", "content": model_response.message.content}
)
except KeyboardInterrupt:
print("\n用户中断对话")
break
except Exception as e:
print(f"对话错误:{e}")
print("继续对话,输入 'exit' 退出")
continue
except Exception as e:
print(f"初始化错误: {e}")
if __name__ == "__main__":
run_chat_session()