curl http://localhost:11434/api/chat -d '{
  "model": "llama3.2",
  "messages": [
    { "role": "user", "content": "why is the sky blue?" }
  ]
}'

修改为python代码:

import requests
import json

url = 'http://localhost:11434/api/chat'

# 初始化对话记录
messages = []

while True:
    user_input = input("你: ")
    
    # 添加用户消息到对话记录
    messages.append({"role": "user", "content": user_input})

    # 构建请求数据
    data = {
        "model": "llama3.2",
        "messages": messages
    }

    # 发送请求
    response = requests.post(url, json=data)

    if response.status_code == 200:
        reply = response.json()
        # 假设 API 的回复在 'content' 字段中
        bot_reply = reply.get('content', '没有回复内容。')
        print(f"AI: {bot_reply}")
        # 添加 AI 回复到对话记录
        messages.append({"role": "assistant", "content": bot_reply})
    else:
        print(f"错误: {response.status_code} - {response.text}")
 

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐