python调用扣子coze智能体示例

"""
版本号:1.0
日期:2024/11/14
描述:
"""
import uuid

import jwt
import time
import requests

# OAuth应用的相关信息,需从扣子平台获取并替换
APP_ID = ""  # auth应用id
PUBLIC_KEY_FINGERPRINT = ""  # 公钥
PRIVATE_KEY_PATH = "private_key.pem" # 私钥文件路径

# 扣子API的Endpoint
API_ENDPOINT = "api.coze.cn"


def generate_jwt():
    """
    生成JWT
    """
    # 读取私钥文件
    with open(PRIVATE_KEY_PATH, 'r') as f:
        private_key = f.read()

    # JWT头部信息
    header = {
        "alg": "RS256",
        "typ": "JWT",
        "kid": PUBLIC_KEY_FINGERPRINT
    }

    # JWT负载信息
    payload = {
        "iss": APP_ID,
        "aud": API_ENDPOINT,
        "iat": int(time.time()),
        "exp": int(time.time()) + 86400,  # 这里设置JWT过期时间为1小时,可根据需求调整
        "jti": uuid.uuid4().hex  # 需替换为真正的随机字符串,每次生成JWT时应不同
    }

    # 生成JWT
    jwt_token = jwt.encode(payload, private_key, algorithm='RS256', headers=header)
    return jwt_token


def get_access_token(jwt_token):
    """
    使用JWT获取访问令牌
    """
    url = "https://api.coze.cn/api/permission/oauth2/token"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {jwt_token}"
    }
    data = {
        "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
        "duration_seconds": 86399  # 可根据需求调整有效期,最大为86399秒(24小时)
    }

    response = requests.post(url, headers=headers, json=data)
    if response.status_code == 200:
        return response.json()["access_token"]
    else:
        print(f"获取访问令牌失败,错误码: {response.status_code},错误信息: {response.text}")
        return None


def get_conversion_id(access_token):
    create_url = ' https://api.coze.cn/v1/conversation/create'
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Content-Type': 'application/json'
    }

    res = requests.post(create_url, headers=headers)
    return res.json()['data']['id']


def chat_with_bot(access_token, conversation_id):
    url = 'https://api.coze.cn/v3/chat?conversation_id='+conversation_id
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Content-Type': 'application/json'
    }
    data = {
        "bot_id": "",  # 智能体id,就是智能体详情url后面的那个id
        "user_id": '1234566758',
        "stream": False,
        "auto_save_history": True,
        "additional_messages": [
            {"role": "user", "content": "你是", "content_type": "text"}
        ]
    }
    res = requests.post(url, headers=headers, json=data)
    print(res.json())

    return res.json()['data']['id']


def get_chat_content(i, c, a):
    url = 'https://api.coze.cn/v3/chat/retrieve'
    headers = {
        'Authorization': f'Bearer {a}',
        'Content-Type': 'application/json'
    }
    data = {
        "conversation_id": i,
        "chat_id": c
    }
    res = requests.get(url, headers=headers, json=data)
    print(res.json())




if __name__ == "__main__":
    jwt_token = generate_jwt()
    print(f"生成的JWT: {jwt_token}")
    access_token = get_access_token(jwt_token)
    if access_token:
        print(f"获取的访问令牌: {access_token}")

    # access_token = 'czs_85DxsJ631VZ7owpzB2ucDmo0iiT0cs3UifDhuvD3yRUEhaDH4GU2pbvWXY4aiNwm'

    conversion_id = get_conversion_id(access_token)

    chat_id = chat_with_bot(access_token, conversion_id)
    time.sleep(1)
    get_chat_content(conversion_id, chat_id, access_token)

 

posted @ 2024-11-14 18:22  lytcreate  阅读(127)  评论(0编辑  收藏  举报