当前位置:   article > 正文

python调用GPT-4-API/gpt3.5-api/chatGML-API/llama2-API/文心一言ERNIE-BOT-API_chatgml 免费接口调用

chatgml 免费接口调用

关于如何开通GPT-API服务,请参考这一篇文章
目前仅使用到单轮对话,记录一下,之后拓展需求继续在该篇博客补充

调用GPT-4进行单轮对话

(调用API需科学上网,科学上网之后还是报connectionerror之类的,就是使用的节点的问题,网络问题)

import openai
import openai.error

openai.log = None
openai.api_key = "sk-******"

def get_gpt4_response(content, max_retries=10):
    messages = [{"role": "user", "content": content}]
    for attempt in range(max_retries):
        try:
            response = openai.ChatCompletion.create(
                model="gpt-4-1106-preview",
                messages=messages,
                temperature = 0.95,
            )
            return response.choices[0].message.content
        except openai.error.APIConnectionError as e:
            print("再次请求中")
            continue
    return "请求失败:超过最大重试次数"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
get_gpt4_response(content='山东的简称是啥,一个字回答我')
  • 1

输出:

调用GPT3.5

(调用API需科学上网,科学上网之后还是报connectionerror之类的,就是使用的节点的问题,网络问题)

import openai
import openai.error
def query_gpt3(prompt):
    openai.api_key = 'sk-**********'  

    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",  model
        messages=[{"role": "user", "content": prompt}]
    )

    return response.choices[0].message['content'].strip()

# 要询问的问题
prompt = "你是gpt3.5还是gpt4?"

# 获取GPT-3的回答
answer = query_gpt3(prompt)
print("GPT-3 Answer:", answer)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

调用llama2-70B(百度接口)

申请入口:Llama-2-70b-chat


import requests
import json

def get_access_token():

    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=***&client_secret=***"
    
    payload = json.dumps("")
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload)
    return response.json().get("access_token")


def main():
        
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/llama_2_7b?access_token=" + get_access_token()
    
    payload = json.dumps({
         "messages": [
            {
                "role": "user",
                "content": "please introduce yourself"
            }
        ]
    })
    headers = {
        'Content-Type': 'application/json'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload)
    
    print(response.text)
    

if __name__ == '__main__':
    main()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

调用chatGML

申请入口:智谱AI大模型MaaS开放平台

import zhipuai

zhipuai.api_key = "********"
response = zhipuai.model_api.sse_invoke(
    model="chatglm_turbo",
    prompt=[
        {"role": "user", "content": "请介绍一下你自己"}
    ],
    temperature=0.95,
    top_p=0.7,
    incremental=True
)

for event in response.events():
  if event.event == "add":
      print(event.data)
  elif event.event == "error" or event.event == "interrupted":
      print(event.data)
  elif event.event == "finish":
      print(event.data)
      print(event.meta)
  else:
      print(event.data)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

调用ERNIE-BOT 4.0

申请入口:ERNIE-BOT 4.0

import requests
import json

def get_access_token():
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=****&client_secret=****"
    response = requests.post(url)
    return response.json().get("access_token")

def call_wenxin_api(content):
    access_token = get_access_token()
    url = f"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token={access_token}"
    
    payload = json.dumps({
        "messages": [
            {
                "role": "user",
                "content": content
            },
        ]
    })
    headers = {
        'Content-Type': 'application/json'
    }
    
    response = requests.post(url, headers=headers, data=payload)
    response_json = response.json()

    # 直接获取 result 的值
    return response_json.get("result")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
call_wenxin_api('山东的简称是什么?')
  • 1

输出:山东的简称是“鲁”

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/356888
推荐阅读
相关标签
  

闽ICP备14008679号