使用 python 调用硅基流动 Deepseek 等模型api,进行聊天对话

首先需要在用硅基流动官网注册账号:
  • https://cloud.siliconflow.cn/models
随后,点击API 密钥部分,获得自己的 api

在这里插入图片描述

基于python 的调用

使用的代码如下,粘贴到命名为main.py的文件中:

import requests
from rich.markdown import Markdown
from rich.console import Console
from rich.prompt import Prompt

# 配置信息
API_URL = "https://api.siliconflow.cn/v1/chat/completions"
API_KEY = "你的api"
model = "deepseek-ai/DeepSeek-R1"

console = Console()
messages = []

def chat_completion(messages):
    """调用API: https://siliconflow.cn/zh-cn/models"""
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "model": model,
        "messages": messages,
        "temperature": 0.7,
        "max_tokens": 1024,
        "response_format": {"type": "text"}
    }
    
    try:
        response = requests.post(API_URL, json=payload, headers=headers)
        response.raise_for_status()
        return response.json()['choices'][0]['message']['content']
    except Exception as e:
        console.print(f"[bold red]API请求失败: {str(e)}[/]")
        return None

def main():
    console.print("[bold green]对话已开始,输入 'exit' 结束对话[/]")
    
    while True:
        user_input = Prompt.ask("[bold cyan]你的问题[/]")
        
        if user_input.lower() in ['exit', 'quit']:
            break
            
        if not user_input.strip():
            continue
            
        messages.append({"role": "user", "content": user_input})
        
        console.print("[italic yellow]思考中...[/]")
        response = chat_completion(messages)
        
        if response:
            messages.append({"role": "assistant", "content": response})
            
            console.print("\n[bold magenta]回答:[/]")
            console.print(Markdown(response))
            console.print("\n" + "-"*50 + "\n")

if __name__ == "__main__":
    main()

注意!上述代码配置信息部分输入你的api,以及选择相应的模型。

随后可以使用python main.py运行:

在返回的提示框中输入自己的问题即可
如上,在返回的提示框中输入自己的问题即可!

分享结束,转载请注明出处!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值