crab

crab

The 'crabs in a barrel' mentality only exists if we view ourselves as a crab. The truth is on the map.

使用steamship构建第一个AI应用

这个 AI 应用用来做什么#

这个应用其实就是根据表结构生成不同类型的实体类。

先说实现的结果是什么?

  • 输入语言: python
  • 输入 entity 框架名称: pydantic
  • 输入 references: 建表的 SQL 或者 JSON 文件

entity-generator

run: 就可以得到生成好的 python 代码

Below is the Python code for a Pydantic model based on the given SQL table:

from typing import Optional  
from pydantic import BaseModel  
from datetime import datetime  
  
  
class EDict(BaseModel):  
	id: int  
	create_by: Optional[str]  
	create_time: Optional[datetime]  
	update_by: Optional[str]  
	update_time: Optional[datetime]  
	code: str  
	name: Optional[str]  
	remark: Optional[str]  
  
  
	class Config:  
		orm_mode = True

Please note that the Pydantic model is a simple data validation and serialization library for Python and it doesn't interact with databases directly. You will need an additional library such as SQLAlchemy for working with databases or implement your code to interact with your database. Additionally, if you are using a newer version of Pydantic, you may need to use the Field method for unique constraint and other validation options.

同时也支持 JAVA 的 JPA,Typescript 的 entity 定义,只要输入自己想要的语言和包名就可以.

如何实现这个后端 AI 接口的?#

这是一个后端的 API,使用 streamship 实现实际上非常简单:

  1. https://www.steamship.com/ 注册账号,并且获得 api-key
  2. 安装 streamship
pip install steamship
  1. 设置 api-key, 文件在~/.steamship.json
{
  "apiKey": "mykey"
}
  1. 创建 python 项目,使用 pip 安装 streamship
pip install streamship
  1. 创建第一个可以被外部调用的 API, 文件为 api.py

from steamship import check_environment, RuntimeEnvironments, Steamship

from steamship.invocable import post, PackageService



class EntityGeneratePackage(PackageService):

	PROMPT = "根据以下内容:{references},生成{language}基于{lib_name}实体类"

  

	@post("generate")
	
	def generate(self, language: str, lib_name: str, references: str):
	
		gpt4 = self.client.use_plugin("gpt-4")
		
		task = gpt4.generate(text=self.PROMPT.format(language=language,
		
		lib_name=lib_name, references=references))
		
		task.wait()
		
		return task.output.blocks[0].text
  1. 部署
ship deploy

就这样子第一个调用 openai gpt4 的 AI 程序就完成了,并且是接口可以访问的.

  1. 如果想用这个外部接口 steamship 也提供了非常方便的调用方式
from steamship import Steamship  
  
# Load the package instance stub.  
pkg = Steamship.use(  
	"entity-generator",  
	api_key="YOUR_API_KEY"  
)  
  
# Invoke the method  
resp = pkg.invoke(  
	"generate",  
	language=VALUE,  
	lib_name=VALUE,  
	references=VALUE  
)

小结#

  1. 这个程序很简单,不过 steamship 这个工具还不错,接口和部署都非常方便
  2. steamship 这个写本地函数,部署之后就暴露为 api 的方式不错,客户端调用方式也很简单,值的学习
  3. steamship 上面还有不少其他内容,都是刚刚开始,值的看看
  4. AI 时代或许就是这样无数个小接口就能连接起来实现不错的功能了
  5. 虽然像这种代码生成功能自己用代码实现也可以,但是很显然使用 AI 实现会快太多,所以那些鄙视 no-code/low-code 的开发人员可能要小心了,而那些不写代码的人,AI 会带给他们很好的生产力提升,不需要了解太多,直接用自然语言就可能获得一些代码帮助自己自动化一些工作了

参考阅读:

加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。