Skip to content
Cloudflare Docs
非官方翻译 - 此文档为非官方中文翻译版本,仅供参考。如有疑问请以 英文官方文档 为准。

使用 DeepSeek Coder 模型探索代码生成

Last reviewed: over 1 year ago

探索 Workers AI 上所有可用模型的一个便捷方法是使用 Jupyter Notebook

您可以下载 DeepSeek Coder 笔记本或查看下面嵌入的笔记本。

Watch more videos on our Developer Channel

使用 DeepSeek Coder 探索代码生成

能够生成代码的 AI 模型开启了各种用例。现在 Workers AI 上提供了 DeepSeek Coder 模型 @hf/thebloke/deepseek-coder-6.7b-base-awq@hf/thebloke/deepseek-coder-6.7b-instruct-awq

让我们使用 API 来探索它们!

import sys
!{sys.executable} -m pip install requests python-dotenv
Requirement already satisfied: requests in ./venv/lib/python3.12/site-packages (2.31.0)
Requirement already satisfied: python-dotenv in ./venv/lib/python3.12/site-packages (1.0.1)
Requirement already satisfied: charset-normalizer<4,>=2 in ./venv/lib/python3.12/site-packages (from requests) (3.3.2)
Requirement already satisfied: idna<4,>=2.5 in ./venv/lib/python3.12/site-packages (from requests) (3.6)
Requirement already satisfied: urllib3<3,>=1.21.1 in ./venv/lib/python3.12/site-packages (from requests) (2.1.0)
Requirement already satisfied: certifi>=2017.4.17 in ./venv/lib/python3.12/site-packages (from requests) (2023.11.17)
import os
from getpass import getpass
from IPython.display import display, Image, Markdown, Audio
import requests
%load_ext dotenv
%dotenv

配置您的环境

要使用 API,您需要您的 Cloudflare 帐户 ID(前往 Workers & Pages > 概述 > 帐户详细信息 > 帐户 ID)和一个已启用 Workers AI 的 API 令牌

如果您想将这些文件添加到您的环境中,可以创建一个名为 .env 的新文件

Terminal window
CLOUDFLARE_API_TOKEN="您的令牌"
CLOUDFLARE_ACCOUNT_ID="您的帐户 ID"
if "CLOUDFLARE_API_TOKEN" in os.environ:
api_token = os.environ["CLOUDFLARE_API_TOKEN"]
else:
api_token = getpass("输入您的 Cloudflare API 令牌")
if "CLOUDFLARE_ACCOUNT_ID" in os.environ:
account_id = os.environ["CLOUDFLARE_ACCOUNT_ID"]
else:
account_id = getpass("输入您的帐户 ID")

从注释生成代码

一个常见的用例是在用户提供描述性注释后为其完成代码。

model = "@hf/thebloke/deepseek-coder-6.7b-base-awq"
prompt = "# 一个检查给定单词是否为回文的函数"
response = requests.post(
f"https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/run/{model}",
headers={"Authorization": f"Bearer {api_token}"},
json={"messages": [
{"role": "user", "content": prompt}
]}
)
inference = response.json()
code = inference["result"]["response"]
display(Markdown(f"""
```python
{prompt}
{code.strip()}
```
"""))
# 一个检查给定单词是否为回文的函数
def is_palindrome(word):
# 将单词转换为小写
word = word.lower()
# 反转单词
reversed_word = word[::-1]
# 检查反转后的单词是否与原始单词相同
if word == reversed_word:
return True
else:
return False
# 测试函数
print(is_palindrome("racecar")) # 输出:True
print(is_palindrome("hello")) # 输出:False

协助调试

我们都遇到过这种情况,bug 总会发生。有时那些堆栈跟踪可能非常吓人,而使用代码生成的一个很好的用例是帮助解释问题。

model = "@hf/thebloke/deepseek-coder-6.7b-instruct-awq"
system_message = "用户会给您一些无法工作的代码。请向用户解释可能出了什么问题"
code = """# 欢迎我们的用户
def hello_world(first_name="World"):
print(f"Hello, {name}!")
"""
response = requests.post(
f"https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/run/{model}",
headers={"Authorization": f"Bearer {api_token}"},
json={"messages": [
{"role": "system", "content": system_message},
{"role": "user", "content": code},
]}
)
inference = response.json()
response = inference["result"]["response"]
display(Markdown(response))

您的代码中的错误是您正在尝试使用一个在函数中任何地方都没有定义的变量 name。应该使用的正确变量是 first_name。所以,您应该将 f"Hello, {name}!" 更改为 f"Hello, {first_name}!"

这是更正后的代码:

# 欢迎我们的用户
def hello_world(first_name="World"):
print(f"Hello, {first_name}")

现在,当您调用 hello_world() 时,它将默认打印“Hello, World”。如果您调用 hello_world("John"),它将打印“Hello, John”。

编写测试!

编写单元测试是一种常见的最佳实践。在有足够上下文的情况下,编写单元测试是可能的。

model = "@hf/thebloke/deepseek-coder-6.7b-instruct-awq"
system_message = "用户会给您一些代码,并希望用 Python 的 unittest 模块编写测试。"
code = """
class User:
def __init__(self, first_name, last_name=None):
self.first_name = first_name
self.last_name = last_name
if last_name is None:
self.last_name = "Mc" + self.first_name
def full_name(self):
return self.first_name + " " + self.last_name
"""
response = requests.post(
f"https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/run/{model}",
headers={"Authorization": f"Bearer {api_token}"},
json={"messages": [
{"role": "system", "content": system_message},
{"role": "user", "content": code},
]}
)
inference = response.json()
response = inference["result"]["response"]
display(Markdown(response))

这是一个针对 User 类的简单 unittest 测试用例:

import unittest
class TestUser(unittest.TestCase):
def test_full_name(self):
user = User("John", "Doe")
self.assertEqual(user.full_name(), "John Doe")
def test_default_last_name(self):
user = User("Jane")
self.assertEqual(user.full_name(), "Jane McJane")
if __name__ == '__main__':
unittest.main()

在这个测试用例中,我们有两个测试:

  • test_full_name 测试当用户同时有名字和姓氏时 full_name 方法。
  • test_default_last_name 测试当用户只有名字且姓氏设置为“Mc”+ 名字时 full_name 方法。

如果所有这些测试都通过,就意味着 full_name 方法工作正常。如果任何测试失败,

Fill-in-the-middle 代码补全

在开发工具中,一个常见的用例是基于上下文进行自动补全。DeepSeek Coder 提供了提交带有占位符的现有代码的能力,以便模型可以在上下文中完成。

警告:令牌以 <| 为前缀,以 |> 为后缀,请确保复制和粘贴它们。

model = "@hf/thebloke/deepseek-coder-6.7b-base-awq"
code = """
<|fim begin|>import re
from jklol import email_service
def send_email(email_address, body):
<|fim▁hole|>
if not is_valid_email:
raise InvalidEmailAddress(email_address)
return email_service.send(email_address, body)<|fim▁end|>
"""
response = requests.post(
f"https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/run/{model}",
headers={"Authorization": f"Bearer {api_token}"},
json={"messages": [
{"role": "user", "content": code}
]}
)
inference = response.json()
response = inference["result"]["response"]
display(Markdown(f"""
```python
{response.strip()}
```
"""))
is_valid_email = re.match(r"[^@]+@[^@]+\.[^@]+", email_address)

实验性:将数据提取为 JSON

无需威胁模型或将祖母带入提示中。获取您想要的 JSON 格式的数据。

model = "@hf/thebloke/deepseek-coder-6.7b-instruct-awq"
# Learn more at https://json-schema.org/
json_schema = """
{
"title": "User",
"description": "A user from our example app",
"type": "object",
"properties": {
"firstName": {
"description": "The user's first name",
"type": "string"
},
"lastName": {
"description": "The user's last name",
"type": "string"
},
"numKids": {
"description": "Amount of children the user has currently",
"type": "integer"
},
"interests": {
"description": "A list of what the user has shown interest in",
"type": "array",
"items": {
"type": "string"
}
},
},
"required": [ "firstName" ]
}
"""
system_prompt = f"""
The user is going to discuss themselves and you should create a JSON object from their description to match the json schema below.
<BEGIN JSON SCHEMA>
{json_schema}
<END JSON SCHEMA>
Return JSON only. Do not explain or provide usage examples.
"""
prompt = """Hey there, I'm Craig Dennis and I'm a Developer Educator at Cloudflare. My email is [email protected].
I am very interested in AI. I've got two kids. I love tacos, burritos, and all things Cloudflare"""
response = requests.post(
f"https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/run/{model}",
headers={"Authorization": f"Bearer {api_token}"},
json={"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt}
]}
)
inference = response.json()
response = inference["result"]["response"]
display(Markdown(f"""
```json
{response.strip()}
```
"""))
{
"firstName": "Craig",
"lastName": "Dennis",
"numKids": 2,
"interests": ["AI", "Cloudflare", "Tacos", "Burritos"]
}