Skip to content

Commit

Permalink
fix:change the img output format (#56)
Browse files Browse the repository at this point in the history
* chore:tool description

* feat:spark img gen and markdown update

* feat:change the img output format
  • Loading branch information
Onelevenvy authored Sep 28, 2024
1 parent 00696e5 commit 7a664e3
Show file tree
Hide file tree
Showing 15 changed files with 315 additions and 86 deletions.
8 changes: 7 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -82,4 +82,10 @@ LANGCHAIN_PROJECT=changethis
RECURSION_LIMIT=25

TAVILY_API_KEY=changethisifyouwanttousetavilyserch
OPEN_WEATHER_API_KEY=changethis
OPEN_WEATHER_API_KEY=changethis


# Spark get apikey from https://console.xfyun.cn/app/myapp
SPARK_APPID=changethis
SPARK_APISecret=changethis
SPARK_APIKey=changethis
8 changes: 4 additions & 4 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@
"envFile": "${workspaceFolder}/.env"
},
{
"type": "chrome",
"type": "msedge",
"request": "launch",
"name": "Debug Frontend: Launch Chrome against http://localhost:5173",
"url": "http://localhost:5173",
"webRoot": "${workspaceFolder}/frontend"
"name": "Debug Frontend: Launch Edges against http://localhost:3000",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}/web"
}
]
}
2 changes: 1 addition & 1 deletion backend/app/core/tools/googletranslate/googletranslate.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def google_translate_invoke(content: str, dest: str) -> str:
googletranslate = StructuredTool.from_function(
func=google_translate_invoke,
name="Google Translate",
description="Useful for when you neet to translate text",
description="Useful for when you neet to translate.",
args_schema=GoogleTranslateInput,
return_direct=True,
)
7 changes: 4 additions & 3 deletions backend/app/core/tools/siliconflow/siliconflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,17 @@ def text2img(

response = requests.post(url, json=payload, headers=headers)

return response.json()
return response.json()["images"][0]["url"]

except Exception as e:
return json.dumps(f"Openweather API Key is invalid. {e}")
return json.dumps(f"There is a error occured . {e}")


siliconflow = StructuredTool.from_function(
func=text2img,
name="Image Generation",
description="Image Generation is a tool that can generate images from text prompts.",
description="Siliconflow Image Generation is a tool that can generate images from text prompts using the Siliconflow API.",
args_schema=Text2ImageInput,
return_direct=True,
)

142 changes: 142 additions & 0 deletions backend/app/core/tools/spark/spark.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import base64
import hashlib
import hmac
import json
from datetime import datetime
from time import mktime
from urllib.parse import urlencode
from wsgiref.handlers import format_date_time
import os
import requests
from langchain.pydantic_v1 import BaseModel, Field
from langchain.tools import StructuredTool


class Text2ImageInput(BaseModel):
"""Input for the text2img tool."""

prompt: str = Field(description="the prompt for generating image ")


class AssembleHeaderError(Exception):
def __init__(self, msg):
self.message = msg


class Url:
def __init__(self, host, path, schema):
self.host = host
self.path = path
self.schema = schema


# calculate sha256 and encode to base64
def sha256base64(data):
sha256 = hashlib.sha256()
sha256.update(data)
digest = base64.b64encode(sha256.digest()).decode(encoding="utf-8")
return digest


def parse_url(request_url):
stidx = request_url.index("://")
host = request_url[stidx + 3 :]
schema = request_url[: stidx + 3]
edidx = host.index("/")
if edidx <= 0:
raise AssembleHeaderError("invalid request url:" + request_url)
path = host[edidx:]
host = host[:edidx]
u = Url(host, path, schema)
return u


def assemble_ws_auth_url(request_url, method="GET", api_key="", api_secret=""):
u = parse_url(request_url)
host = u.host
path = u.path
now = datetime.now()
date = format_date_time(mktime(now.timetuple()))
signature_origin = "host: {}\ndate: {}\n{} {} HTTP/1.1".format(
host, date, method, path
)
signature_sha = hmac.new(
api_secret.encode("utf-8"),
signature_origin.encode("utf-8"),
digestmod=hashlib.sha256,
).digest()
signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")
authorization_origin = f'api_key="{api_key}", algorithm="hmac-sha256", headers="host date request-line", signature="{signature_sha}"'

authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(
encoding="utf-8"
)
values = {"host": host, "date": date, "authorization": authorization}

return request_url + "?" + urlencode(values)


def get_body(appid, text):
body = {
"header": {"app_id": appid, "uid": "123456789"},
"parameter": {
"chat": {"domain": "general", "temperature": 0.5, "max_tokens": 4096}
},
"payload": {"message": {"text": [{"role": "user", "content": text}]}},
}
return body


def spark_response(text, appid, apisecret, apikey):
host = "http://spark-api.cn-huabei-1.xf-yun.com/v2.1/tti"
url = assemble_ws_auth_url(
host, method="POST", api_key=apikey, api_secret=apisecret
)
content = get_body(appid, text)
try:
response = requests.post(
url, json=content, headers={"content-type": "application/json"}
).text
return response
except Exception as e:
return json.dumps(f"There is a error occured . {e}")


def img_generation(prompt):
appid = os.environ.get("SPARK_APPID", "")
apisecret = os.environ.get("SPARK_APISECRET", "")
apikey = os.environ.get("SPARK_APIKEY", "")
if not appid or not apisecret or not apikey:
return "api key is not set or not correct"
else:
response = spark_response(
text=prompt,
appid=appid,
apisecret=apisecret,
apikey=apikey,
)
try:
data = json.loads(response)
code = data["header"]["code"]
if code != 0:
return f"error: {code}, {data}"
else:
text = data["payload"]["choices"]["text"]
image_content = text[0]
image_base = image_content["content"]
bs64data = "data:image/jpeg;base64," + image_base

return bs64data
# return aaa

except Exception as e:
return json.dumps(f"There is a error occured . {e}")


spark = StructuredTool.from_function(
func=img_generation,
name="Spark Image Generation",
description="Spark Image Generation is a tool that can generate images from text prompts using the Spark API.",
args_schema=Text2ImageInput,
return_direct=True,
)
6 changes: 3 additions & 3 deletions backend/app/core/tools/tool_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,17 +55,17 @@ def load_external_tools(self):

external_tools = {
"duckduckgo-search": ToolInfo(
description="Searches the web using DuckDuckGo",
description="Searches the web using DuckDuckGo.",
tool=DuckDuckGoSearchRun(),
display_name="DuckDuckGo",
),
"wikipedia": ToolInfo(
description="Searches Wikipedia",
description="Searches Wikipedia.",
tool=WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper()),
display_name="Wikipedia",
),
"tavilysearch": ToolInfo(
description="tavily search useful when searching for information on the internet",
description="Tavily is useful when searching for information on the internet.",
tool=TavilySearchResults(max_results=1),
display_name="Tavily Search",
),
Expand Down
8 changes: 7 additions & 1 deletion web/src/app/(applayout)/dashboard/page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use client";
import useAuth from "@/hooks/useAuth";
import { Box, Container, Text } from "@chakra-ui/react";
import { Box, Container, Image, Text } from "@chakra-ui/react";
import React from "react";

function Dashboard() {
Expand All @@ -14,6 +14,12 @@ function Dashboard() {
Hi, {currentUser?.full_name || currentUser?.email} 👋🏼
</Text>
<Text>Welcome back, nice to see you again!</Text>
<Image
src={'https://sf-maas-uat-prod.oss-cn-shanghai.aliyuncs.com/outputs/f967b5c9-c3c8-4f4b-9f1f-708e2dfda39c_0.png'}
alt="aaa"
width={"auto"}
height={"auto"}
/>
</Box>
</Container>
</>
Expand Down
4 changes: 2 additions & 2 deletions web/src/app/(applayout)/tools/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -122,15 +122,15 @@ function Skills() {
w="8"
tools_name={skill
.display_name!.toLowerCase()
.replace(" ", "_")}
.replace(/ /g, "_")}
/>

<Heading size="md">{skill.display_name}</Heading>
</HStack>
<Box
overflow="hidden"
textOverflow="ellipsis"
whiteSpace="nowrap"
// whiteSpace="nowrap"
>
{skill.description}
</Box>
Expand Down
30 changes: 30 additions & 0 deletions web/src/components/Icons/Tools/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Icon, type IconProps, createIcon } from "@chakra-ui/icons";
import { SiliconFlowIcon } from "../models";

const OpenWeather = createIcon({
displayName: "OpenWeather",
Expand Down Expand Up @@ -330,13 +331,42 @@ const calculator = createIcon({
</svg>
),
});

const spark = createIcon({
displayName: "spark",
viewBox: "0 0 24 24",
path: (
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M21.6547 16.7993C21.3111 18.0034 20.7384 19.0938 20.0054 20.048C18.9058 21.4111 15.1261 21.4111 12.8583 20.8204C10.4072 20.1616 8.6433 18.6395 8.50586 18.5259C9.46797 19.2756 10.6821 19.7072 12.0107 19.7072C15.1948 19.7072 17.7605 17.1174 17.7605 13.9368C17.7605 12.9826 17.5314 12.0966 17.119 11.3015C17.0961 11.2561 17.1419 11.2106 17.1649 11.2333C18.9745 11.5287 22.571 13.2098 21.6547 16.7993Z"
fill="#2751D0"
/>
<path
d="M21.9994 12.7773C21.9994 12.8454 21.9306 12.8682 21.8848 12.8C21.0372 11.0053 19.5483 10.46 17.7615 10.0511C16.4099 9.75577 15.5166 9.3014 15.1271 9.09694C15.0355 9.0515 14.9668 8.98335 14.8751 8.93791C12.0575 7.23404 12.0117 4.30339 12.0117 4.30339V0.0550813C12.0117 0.00964486 12.0804 -0.0130733 12.1034 0.0096449L18.7694 6.50706L19.2734 6.98414C20.7394 8.52898 21.7474 10.5509 21.9994 12.7773Z"
fill="#D82F20"
/>
<path
d="M20.0052 20.0462C18.1726 22.4316 15.2863 23.9992 12.0334 23.9992C6.48985 23.9992 2 19.501 2 13.9577C2 11.2543 3.05374 8.8234 4.7947 7.00594L5.29866 6.50614L9.65107 2.25783C9.69688 2.2124 9.7656 2.25783 9.7427 2.30327C9.67397 2.59861 9.55944 3.28015 9.62816 4.18888C9.71979 5.25664 10.0634 6.68789 11.0713 8.27817C11.6898 9.27777 12.5832 10.3228 13.8202 11.4133C13.9577 11.5496 14.118 11.6632 14.2784 11.7995C14.8281 12.3674 15.1488 13.1171 15.1488 13.9577C15.1488 15.6616 13.7515 17.0474 12.0563 17.0474C11.3233 17.0474 10.659 16.7975 10.1321 16.3659C10.0863 16.3204 10.1321 16.2523 10.1779 16.275C10.2925 16.2977 10.407 16.3204 10.5215 16.3204C11.1171 16.3204 11.6211 15.8433 11.6211 15.2299C11.6211 14.8665 11.4378 14.5257 11.163 14.3439C10.4299 13.7533 9.81142 13.1853 9.28455 12.6173C8.55151 11.8222 8.00174 11.0498 7.61231 10.3001C6.81055 11.2997 6.30659 12.5492 6.30659 13.935C6.30659 15.7979 7.17707 17.4563 8.55152 18.5014C8.68896 18.615 10.4528 20.1371 12.9039 20.7959C15.1259 21.432 18.9057 21.4093 20.0052 20.0462Z"
fill="#69C5F4"
/>
</svg>
),
});
const iconMap: { [key: string]: React.FC } = {
open_weather: OpenWeather,
google_translate: GoogleTranslate,
duckduckgo: DuckduckgoSearch,
Wikipedia: Wikipedia,
tavily_search: tavilysearch,
math_calculator: calculator,
image_generation: SiliconFlowIcon,
spark_image_generation: spark,
};

const DefaultIcon = Wikipedia;
Expand Down
Loading

0 comments on commit 7a664e3

Please sign in to comment.