当前位置:   article > 正文

用 Python 对接 Azure 的 chatGPT4 接口实现聊天功能_azure chatgpt gpt 4

azure chatgpt gpt 4

今天拿到了 Azure 授权的 chatGPT4  的接口,内心很激动,终于可以安心使用chatGPT4了。赶紧采用 gradio 组件封装了一个简单的对话窗口来体验一下 GPT4 的超能力,看似简单的功能在显示打字机效果时,还是花了一些时间思考。

代码如下:

1)先安装 python 的 gradio 组件

pip install gradio

2)运行如下代码,尽情享受超能力吧

  1. import time
  2. import gradio as gr
  3. import mdtex2html
  4. import os
  5. import openai
  6. openai.api_type = "azure"
  7. openai.api_base = "https://xxxx.openai.azure.com/"
  8. openai.api_version = "2023-05-15"
  9. openai.api_key = "API_KEY"
  10. # This will correspond to the custom name you chose for your deployment when you deployed a model.
  11. deployment_name = 'XXXXXXX'
  12. prompt = """
  13. 我想让你充当数学历史老师,提供有关数学概念的历史发展和不同数学家的贡献的信息。
  14. 你应该只提供信息而不是解决数学问题。使用以下格式回答:“{数学家/概念} - {他们的贡献/发展的简要总结}。
  15. 我的第一个问题是“毕达哥拉斯对数学的贡献是什么?”
  16. """
  17. prompt = ""
  18. def predict(chatbot, input, history, temperature, max_tokens, top_p, chat_turns=0):
  19. chat_turns = chat_turns +1
  20. chatbot.append((input, ""))
  21. history.append(input)
  22. messages = []
  23. messages.append({"role": "system", "content": prompt})
  24. try:
  25. # print("==========request======:", question)
  26. messages.append({"role": "user", "content": input})
  27. response = openai.ChatCompletion.create(
  28. engine=deployment_name,
  29. messages=messages,
  30. temperature=temperature,
  31. max_tokens=max_tokens,
  32. top_p=top_p,
  33. frequency_penalty=0,
  34. presence_penalty=0,
  35. stop=None,
  36. stream=True,
  37. )
  38. except Exception as e:
  39. print(e)
  40. return e
  41. content = {'role': '', 'content': ''}
  42. for event in response:
  43. if event['choices'][0]['finish_reason'] == 'stop':
  44. print(f'收到的完成数据: {content}')
  45. history.append(content["content"])
  46. break
  47. for delta_k, delta_v in event['choices'][0]['delta'].items():
  48. print(f'流响应数据: {delta_k} = {delta_v}')
  49. content[delta_k] += delta_v
  50. responses = [(u, b) for u, b in zip(history[::2], history[1::2])]
  51. # responses = [(input, content[delta_k])]
  52. responses.append((input, content[delta_k]))
  53. yield responses, history, chat_turns
  54. def reset_user_input():
  55. return gr.update(value='')
  56. def reset_state():
  57. return [], [],0
  58. with gr.Blocks() as demo:
  59. gr.HTML("""<h1 align="center">悦高软件-人工智能数字助手 GPT-4</h1>""")
  60. # radio = gr.Radio(value='gpt-3.5-turbo',
  61. # choices=['gpt-3.5-turbo', 'gpt-4'], label='models')
  62. chatbot = gr.Chatbot()
  63. with gr.Row():
  64. with gr.Column(scale=4):
  65. with gr.Column(scale=12):
  66. user_input = gr.Textbox(show_label=False, placeholder="请输入内容...", lines=12).style(
  67. container=False)
  68. with gr.Column(min_width=32, scale=1):
  69. submitBtn = gr.Button("提交", variant="primary")
  70. with gr.Column(scale=1):
  71. emptyBtn = gr.Button("重新对话")
  72. max_length = gr.Slider(
  73. 0, 4096, value=800, step=1.0, label="Maximum length", interactive=True)
  74. top_p = gr.Slider(0, 1, value=0.95, step=0.01,
  75. label="Top P", interactive=True)
  76. temperature = gr.Slider(
  77. 0, 1, value=0.7, step=0.01, label="Temperature", interactive=True)
  78. chat_turns = gr.Slider(1,20,value=0,step=1,label="对话轮数",info="记录历史对话轮数",interactive=False)
  79. state = gr.State([])
  80. submitBtn.click(predict, inputs=[chatbot, user_input, state, temperature, max_length, top_p, chat_turns], outputs=[
  81. chatbot, state, chat_turns], queue=True, show_progress=True)
  82. submitBtn.click(reset_user_input, [], [user_input])
  83. emptyBtn.click(reset_state, outputs=[
  84. chatbot, state, chat_turns], show_progress=True)
  85. demo.title = "Yogoo AI"
  86. demo.queue()
  87. demo.launch(share=False, inbrowser=True)

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

闽ICP备14008679号