Commit a2c8fcf8 authored by Wade's avatar Wade

add docker compose

parent 7440fa13
# Stage 1: Build stage
FROM golang:1.24-alpine AS build
WORKDIR /app
# Install dependencies for swag CLI (git is required)
RUN apk add --no-cache git
# Install swag CLI for Swagger generation
# RUN go install github.com/swaggo/swag/cmd/swag@latest
# Copy and download dependencies
COPY go.mod go.sum ./
RUN go mod download
# Copy the source code
COPY . .
# Generate Swagger docs
# RUN swag init -g cmd/agentchat/main.go -o docs
# Build the Go application
RUN CGO_ENABLED=0 GOOS=linux go build -o myapp .
# Stage 2: Final stage
FROM alpine:edge
WORKDIR /app
# Copy the binary from the build stage
COPY --from=build /app/myapp .
# Copy swagger.yaml (optional, since it's embedded in the binary)
COPY --from=build /app/docs/swagger.yaml /app/docs/swagger.yaml
# Install curl and CA certificates
RUN apk update && apk add --no-cache curl ca-certificates
# Expose port
EXPOSE 8000
# Set the entrypoint command
ENTRYPOINT ["/app/myapp"]
\ No newline at end of file
{"level":"info","pid":11627,"time":1749036605,"caller":"/Users/wade/project/wuban/agentchat/log.go:69","message":"This message appears when log level set to Debug or Info"}
{"level":"info","pid":11627,"time":1749036651,"caller":"/Users/wade/project/wuban/agentchat/main.go:229","message":"input--------{\"content\":\"What is the capital of UK?\",\"model\":\"gpt-3.5-turbo\",\"apiKey\":\"sk-1234567890abcdef\",\"from\":\"Alice\",\"from_id\":\"user123\",\"to\":\"Bob\",\"to_id\":\"user456\"}"}
{"level":"info","pid":11627,"time":1749036651,"caller":"/Users/wade/project/wuban/agentchat/main.go:255","message":"qaAsJson--------{\"ID\":16,\"CreatedAt\":\"2025-06-04T09:50:02.837091Z\",\"FromID\":\"user123\",\"From\":\"Alice\",\"Question\":\"What is the capital of UK?\",\"Answer\":null,\"Summary\":null,\"To\":\"Bob\",\"ToID\":\"user4567\"}"}
{"level":"info","pid":11627,"time":1749036656,"caller":"/Users/wade/project/wuban/agentchat/main.go:281","message":"promptInput.Context: Paris is the capital of France?\nUSA is the largest importer of coffee?\n"}
{"level":"info","pid":11627,"time":1749036665,"caller":"/Users/wade/project/wuban/agentchat/main.go:294","message":"promptInput.Graph : 知识库中提供的内容不足以回答此问题\n\n<references title=\"References\" references=\"[]\" />\n"}
{"level":"info","pid":12824,"time":1749036924,"caller":"/Users/wade/project/wuban/agentchat/log.go:69","message":"This message appears when log level set to Debug or Info"}
{"level":"info","pid":12824,"time":1749036930,"caller":"/Users/wade/project/wuban/agentchat/main.go:255","message":"input--------{\"content\":\"What is the capital of UK?\",\"model\":\"gpt-3.5-turbo\",\"apiKey\":\"sk-1234567890abcdef\",\"from\":\"Alice\",\"from_id\":\"user123\",\"to\":\"Bob\",\"to_id\":\"user456\"}"}
{"level":"info","pid":12824,"time":1749036931,"caller":"/Users/wade/project/wuban/agentchat/main.go:281","message":"qaAsJson--------{\"ID\":27,\"CreatedAt\":\"2025-06-04T11:30:53.508295Z\",\"FromID\":\"user123\",\"From\":\"Alice\",\"Question\":\"What is the capital of UK?\",\"Answer\":\"Well now, if Paris is the heart of France, and the US loves its coffee, then you're probably wondering about the UK. The capital of the UK is London, a truly grand city!\\n\",\"Summary\":\"\",\"To\":\"Bob\",\"ToID\":\"user456\"}"}
{"level":"info","pid":12824,"time":1749036933,"caller":"/Users/wade/project/wuban/agentchat/main.go:307","message":"promptInput.Context: Paris is the capital of France?\nUSA is the largest importer of coffee?\n"}
{"level":"info","pid":12824,"time":1749036937,"caller":"/Users/wade/project/wuban/agentchat/main.go:320","message":"promptInput.Graph : 知识库中提供的内容不足以回答此问题\n\n<references title=\"References\" references=\"[]\" />\n"}
{"level":"info","pid":18861,"time":1749038762,"caller":"/Users/wade/project/wuban/agentchat/log.go:69","message":"This message appears when log level set to Debug or Info"}
{"level":"info","pid":18861,"method":"DeepSeek.Init","time":1749038762,"caller":"/Users/wade/project/wuban/agentchat/plugins/deepseek/deepseek.go:91","message":"Initializing DeepSeek plugin"}
{"level":"info","pid":18861,"method":"DeepSeek.Init","time":1749038762,"caller":"/Users/wade/project/wuban/agentchat/plugins/deepseek/deepseek.go:104","message":"Initialization successful"}
{"level":"info","pid":18861,"method":"Milvus.Init","time":1749038762,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:75","message":"Initializing Milvus plugin"}
{"level":"info","pid":18861,"method":"Milvus.Init","time":1749038764,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:87","message":"Initialization successful"}
{"level":"info","pid":18861,"method":"GraphKnowledge.Init","time":1749038764,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:299","message":"Initializing GraphKnowledge plugin"}
{"level":"info","pid":18861,"method":"NewClient","ip":"54.92.111.204","port":5670,"time":1749038764,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:93","message":"Creating new GraphRAG client"}
{"level":"info","pid":18861,"method":"GraphKnowledge.Init","time":1749038764,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:311","message":"Initialization successful"}
{"level":"info","pid":18861,"method":"DefineIndexerAndRetriever","collection":"chatRag1","dimension":768,"time":1749038764,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:152","message":"Defining indexer and retriever"}
{"level":"info","pid":18861,"method":"Milvus.newDocStore","collection":"chatRag1","dimension":768,"time":1749038764,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:201","message":"Creating new doc store"}
{"level":"info","pid":18861,"method":"Milvus.newDocStore","collection":"chatRag1","time":1749038765,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:302","message":"Doc store created successfully"}
{"level":"info","pid":18861,"method":"DefineIndexerAndRetriever","collection":"chatRag1","time":1749038765,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:182","message":"Indexer and retriever defined successfully"}
{"level":"info","pid":18861,"method":"DefineIndexerAndRetriever","time":1749038765,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:357","message":"Defining indexer and retriever"}
{"level":"info","pid":18861,"method":"GraphKnowledge.newDocStore","space_id":"","model_name":"Qwen/Qwen2.5-Coder-32B-Instruct","time":1749038765,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:393","message":"Creating new doc store"}
{"level":"info","pid":18861,"method":"GraphKnowledge.newDocStore","time":1749038765,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:399","message":"Doc store created successfully"}
{"level":"info","pid":18861,"method":"DefineIndexerAndRetriever","time":1749038765,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:376","message":"Indexer and retriever defined successfully"}
{"level":"info","pid":18861,"time":1749038774,"caller":"/Users/wade/project/wuban/agentchat/main.go:255","message":"input--------{\"content\":\"What is the capital of UK?\",\"model\":\"gpt-3.5-turbo\",\"apiKey\":\"sk-1234567890abcdef\",\"from\":\"Alice\",\"from_id\":\"user123\",\"to\":\"Bob\",\"to_id\":\"user456\"}"}
{"level":"info","pid":18861,"time":1749038774,"caller":"/Users/wade/project/wuban/agentchat/main.go:281","message":"qaAsJson--------{\"ID\":28,\"CreatedAt\":\"2025-06-04T11:35:33.142254Z\",\"FromID\":\"user123\",\"From\":\"Alice\",\"Question\":\"What is the capital of UK?\",\"Answer\":\"I'm sorry, but the provided context doesn't contain information about the capital of the UK.\\n\",\"Summary\":\"\",\"To\":\"Bob\",\"ToID\":\"user456\"}"}
{"level":"info","pid":18861,"method":"docStore.Retrieve","collection":"chatRag1","time":1749038774,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:450","message":"Starting retrieve operation"}
{"level":"info","pid":18861,"method":"docStore.Retrieve","collection":"chatRag1","documents":2,"time":1749038778,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:640","message":"Retrieve operation completed successfully"}
{"level":"info","pid":18861,"time":1749038778,"caller":"/Users/wade/project/wuban/agentchat/main.go:307","message":"promptInput.Context: Paris is the capital of France?\nUSA is the largest importer of coffee?\n"}
{"level":"info","pid":18861,"method":"docStore.Retrieve","space_id":"","time":1749038778,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:755","message":"Starting retrieve operation"}
{"level":"info","pid":18861,"method":"docStore.Retrieve","space_id":"","documents":1,"time":1749038786,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:892","message":"Retrieve operation completed successfully"}
{"level":"info","pid":18861,"time":1749038786,"caller":"/Users/wade/project/wuban/agentchat/main.go:320","message":"promptInput.Graph : 知识库中提供的内容不足以回答此问题\n\n<references title=\"References\" references=\"[]\" />\n"}
{"level":"info","pid":18861,"time":1749038813,"caller":"/Users/wade/project/wuban/agentchat/main.go:255","message":"input--------{\"content\":\"What is the capital of UK?\",\"model\":\"gpt-3.5-turbo\",\"apiKey\":\"sk-1234567890abcdef\",\"from\":\"Alice\",\"from_id\":\"user123\",\"to\":\"Bob\",\"to_id\":\"user456\"}"}
{"level":"info","pid":18861,"time":1749038814,"caller":"/Users/wade/project/wuban/agentchat/main.go:281","message":"qaAsJson--------{\"ID\":29,\"CreatedAt\":\"2025-06-04T12:06:16.535774Z\",\"FromID\":\"user123\",\"From\":\"Alice\",\"Question\":\"What is the capital of UK?\",\"Answer\":\"I'm sorry, but the provided information does not contain the answer to your question about the capital of the UK.\\n\",\"Summary\":\"\",\"To\":\"Bob\",\"ToID\":\"user456\"}"}
{"level":"info","pid":18861,"method":"docStore.Retrieve","collection":"chatRag1","time":1749038814,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:450","message":"Starting retrieve operation"}
{"level":"info","pid":18861,"method":"docStore.Retrieve","collection":"chatRag1","documents":2,"time":1749038815,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:640","message":"Retrieve operation completed successfully"}
{"level":"info","pid":18861,"time":1749038815,"caller":"/Users/wade/project/wuban/agentchat/main.go:307","message":"promptInput.Context: Paris is the capital of France?\nUSA is the largest importer of coffee?\n"}
{"level":"info","pid":18861,"method":"docStore.Retrieve","space_id":"","time":1749038815,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:755","message":"Starting retrieve operation"}
{"level":"fatal","pid":18861,"time":1749038816,"caller":"/Users/wade/project/wuban/agentchat/main.go:362","message":"Server failed: failed to shutdown server: context canceled"}
{"level":"info","pid":19911,"time":1749039201,"caller":"/Users/wade/project/wuban/agentchat/log.go:69","message":"This message appears when log level set to Debug or Info"}
{"level":"info","pid":19911,"method":"DeepSeek.Init","time":1749039201,"caller":"/Users/wade/project/wuban/agentchat/plugins/deepseek/deepseek.go:91","message":"Initializing DeepSeek plugin"}
{"level":"info","pid":19911,"method":"DeepSeek.Init","time":1749039201,"caller":"/Users/wade/project/wuban/agentchat/plugins/deepseek/deepseek.go:104","message":"Initialization successful"}
{"level":"info","pid":19911,"method":"Milvus.Init","time":1749039201,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:75","message":"Initializing Milvus plugin"}
{"level":"info","pid":19911,"method":"Milvus.Init","time":1749039203,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:87","message":"Initialization successful"}
{"level":"info","pid":19911,"method":"GraphKnowledge.Init","time":1749039203,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:299","message":"Initializing GraphKnowledge plugin"}
{"level":"info","pid":19911,"method":"NewClient","ip":"54.92.111.204","port":5670,"time":1749039203,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:93","message":"Creating new GraphRAG client"}
{"level":"info","pid":19911,"method":"GraphKnowledge.Init","time":1749039203,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:311","message":"Initialization successful"}
{"level":"info","pid":19911,"method":"DefineIndexerAndRetriever","collection":"chatRag1","dimension":768,"time":1749039203,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:152","message":"Defining indexer and retriever"}
{"level":"info","pid":19911,"method":"Milvus.newDocStore","collection":"chatRag1","dimension":768,"time":1749039203,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:201","message":"Creating new doc store"}
{"level":"info","pid":19911,"method":"Milvus.newDocStore","collection":"chatRag1","time":1749039204,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:302","message":"Doc store created successfully"}
{"level":"info","pid":19911,"method":"DefineIndexerAndRetriever","collection":"chatRag1","time":1749039204,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:182","message":"Indexer and retriever defined successfully"}
{"level":"info","pid":19911,"method":"DefineIndexerAndRetriever","time":1749039204,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:357","message":"Defining indexer and retriever"}
{"level":"info","pid":19911,"method":"GraphKnowledge.newDocStore","space_id":"","model_name":"Qwen/Qwen2.5-Coder-32B-Instruct","time":1749039204,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:393","message":"Creating new doc store"}
{"level":"info","pid":19911,"method":"GraphKnowledge.newDocStore","time":1749039204,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:399","message":"Doc store created successfully"}
{"level":"info","pid":19911,"method":"DefineIndexerAndRetriever","time":1749039204,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:376","message":"Indexer and retriever defined successfully"}
{"level":"info","pid":19911,"time":1749039212,"caller":"/Users/wade/project/wuban/agentchat/main.go:255","message":"input--------{\"content\":\"What is the capital of UK?\",\"model\":\"gpt-3.5-turbo\",\"apiKey\":\"sk-1234567890abcdef\",\"from\":\"Alice\",\"from_id\":\"user123\",\"to\":\"Bob\",\"to_id\":\"user456\"}"}
{"level":"info","pid":19911,"time":1749039212,"caller":"/Users/wade/project/wuban/agentchat/main.go:281","message":"qaAsJson--------{\"ID\":30,\"CreatedAt\":\"2025-06-04T12:06:55.995343Z\",\"FromID\":\"user123\",\"From\":\"Alice\",\"Question\":\"What is the capital of UK?\",\"Answer\":null,\"Summary\":null,\"To\":\"Bob\",\"ToID\":\"user456\"}"}
{"level":"info","pid":19911,"method":"docStore.Retrieve","collection":"chatRag1","time":1749039212,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:450","message":"Starting retrieve operation"}
{"level":"info","pid":19911,"method":"docStore.Retrieve","collection":"chatRag1","documents":2,"time":1749039215,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:640","message":"Retrieve operation completed successfully"}
{"level":"info","pid":19911,"time":1749039215,"caller":"/Users/wade/project/wuban/agentchat/main.go:307","message":"promptInput.Context: Paris is the capital of France?\nUSA is the largest importer of coffee?\n"}
{"level":"info","pid":19911,"method":"docStore.Retrieve","space_id":"","time":1749039215,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:755","message":"Starting retrieve operation"}
{"level":"info","pid":19911,"method":"docStore.Retrieve","space_id":"","documents":1,"time":1749039220,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:892","message":"Retrieve operation completed successfully"}
{"level":"info","pid":19911,"time":1749039220,"caller":"/Users/wade/project/wuban/agentchat/main.go:320","message":"promptInput.Graph : 知识库中提供的内容不足以回答此问题\n\n<references title=\"References\" references=\"[]\" />\n"}
{"level":"info","pid":20548,"time":1749039434,"caller":"/Users/wade/project/wuban/agentchat/log.go:69","message":"This message appears when log level set to Debug or Info"}
{"level":"info","pid":20548,"method":"DeepSeek.Init","time":1749039434,"caller":"/Users/wade/project/wuban/agentchat/plugins/deepseek/deepseek.go:91","message":"Initializing DeepSeek plugin"}
{"level":"info","pid":20548,"method":"DeepSeek.Init","time":1749039434,"caller":"/Users/wade/project/wuban/agentchat/plugins/deepseek/deepseek.go:104","message":"Initialization successful"}
{"level":"info","pid":20548,"method":"Milvus.Init","time":1749039434,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:75","message":"Initializing Milvus plugin"}
{"level":"info","pid":20548,"method":"Milvus.Init","time":1749039435,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:87","message":"Initialization successful"}
{"level":"info","pid":20548,"method":"GraphKnowledge.Init","time":1749039435,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:299","message":"Initializing GraphKnowledge plugin"}
{"level":"info","pid":20548,"method":"NewClient","ip":"54.92.111.204","port":5670,"time":1749039435,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:93","message":"Creating new GraphRAG client"}
{"level":"info","pid":20548,"method":"GraphKnowledge.Init","time":1749039435,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:311","message":"Initialization successful"}
{"level":"info","pid":20548,"method":"DefineIndexerAndRetriever","collection":"chatRag1","dimension":768,"time":1749039435,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:152","message":"Defining indexer and retriever"}
{"level":"info","pid":20548,"method":"Milvus.newDocStore","collection":"chatRag1","dimension":768,"time":1749039435,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:201","message":"Creating new doc store"}
{"level":"info","pid":20548,"method":"Milvus.newDocStore","collection":"chatRag1","time":1749039436,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:302","message":"Doc store created successfully"}
{"level":"info","pid":20548,"method":"DefineIndexerAndRetriever","collection":"chatRag1","time":1749039436,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:182","message":"Indexer and retriever defined successfully"}
{"level":"info","pid":20548,"method":"DefineIndexerAndRetriever","time":1749039436,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:357","message":"Defining indexer and retriever"}
{"level":"info","pid":20548,"method":"GraphKnowledge.newDocStore","space_id":"","model_name":"Qwen/Qwen2.5-Coder-32B-Instruct","time":1749039436,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:393","message":"Creating new doc store"}
{"level":"info","pid":20548,"method":"GraphKnowledge.newDocStore","time":1749039436,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:399","message":"Doc store created successfully"}
{"level":"info","pid":20548,"method":"DefineIndexerAndRetriever","time":1749039436,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:376","message":"Indexer and retriever defined successfully"}
{"level":"info","pid":20548,"time":1749039446,"caller":"/Users/wade/project/wuban/agentchat/main.go:255","message":"input--------{\"content\":\"What is the capital of UK?\",\"model\":\"gpt-3.5-turbo\",\"apiKey\":\"sk-1234567890abcdef\",\"from\":\"Alice\",\"from_id\":\"user123\",\"to\":\"Bob\",\"to_id\":\"user456\"}"}
{"level":"info","pid":20548,"time":1749039446,"caller":"/Users/wade/project/wuban/agentchat/main.go:281","message":"qaAsJson--------{\"ID\":31,\"CreatedAt\":\"2025-06-04T12:13:34.277943Z\",\"FromID\":\"user123\",\"From\":\"Alice\",\"Question\":\"What is the capital of UK?\",\"Answer\":\"The provided context does not contain the answer to the question \\\"What is the capital of UK?\\\".\\n\",\"Summary\":\"\",\"To\":\"Bob\",\"ToID\":\"user456\"}"}
{"level":"info","pid":20548,"method":"docStore.Retrieve","collection":"chatRag1","time":1749039446,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:450","message":"Starting retrieve operation"}
{"level":"info","pid":20548,"method":"docStore.Retrieve","collection":"chatRag1","documents":2,"time":1749039448,"caller":"/Users/wade/project/wuban/agentchat/plugins/milvus/milvus.go:640","message":"Retrieve operation completed successfully"}
{"level":"info","pid":20548,"time":1749039448,"caller":"/Users/wade/project/wuban/agentchat/main.go:307","message":"promptInput.Context: Paris is the capital of France?\nUSA is the largest importer of coffee?\n"}
{"level":"info","pid":20548,"method":"docStore.Retrieve","space_id":"","time":1749039448,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:755","message":"Starting retrieve operation"}
{"level":"info","pid":20548,"method":"docStore.Retrieve","space_id":"","documents":1,"time":1749039455,"caller":"/Users/wade/project/wuban/agentchat/plugins/graphrag/graph.go:892","message":"Retrieve operation completed successfully"}
{"level":"info","pid":20548,"time":1749039455,"caller":"/Users/wade/project/wuban/agentchat/main.go:320","message":"promptInput.Graph : 知识库中提供的内容不足以回答此问题\n\n<references title=\"References\" references=\"[]\" />\n"}
{"level":"info","pid":20548,"method":"LogQuestionAnswer","question":"What is the capital of UK?","context":"Paris is the capital of France?\nUSA is the largest importer of coffee?\n","graph":"知识库中提供的内容不足以回答此问题\n\n<references title=\"References\" references=\"[]\" />\n","last summary":"","answer":"The knowledge base and graph context do not contain information about the capital of the UK.\n","time":1749039456,"caller":"/Users/wade/project/wuban/agentchat/main.go:344","message":"Question and answer pair recorded"}
version: '3.9'
services:
agentchat:
container_name: "agentchat"
build:
context: . # Build context is the current directory
dockerfile: Dockerfile # Dockerfile for agentchat
volumes:
- /var/log:/var/log
environment:
- GEMINI_API_KEY=${GEMINI_API_KEY} # Reference variable from .env
ports:
- "8000:8000"
entrypoint: /app/myapp
docker-host:
image: qoomon/docker-host
cap_add: ['NET_ADMIN', 'NET_RAW']
mem_limit: 8M
restart: on-failure
# etcd:
# container_name: milvus-etcd
# image: quay.io/coreos/etcd:v3.5.18
# environment:
# - ETCD_AUTO_COMPACTION_MODE=revision
# - ETCD_AUTO_COMPACTION_RETENTION=1000
# - ETCD_QUOTA_BACKEND_BYTES=4294967296
# - ETCD_SNAPSHOT_COUNT=50000
# volumes:
# - ${DOCKER_VOLUME_DIRECTORY:-.}/volumes/etcd:/etcd
# command: etcd -advertise-client-urls=http://etcd:2379 -listen-client-urls http://0.0.0.0:2379 --data-dir /etcd
# healthcheck:
# test: ["CMD", "etcdctl", "endpoint", "health"]
# interval: 30s
# timeout: 20s
# retries: 3
# minio:
# container_name: milvus-minio
# image: minio/minio:RELEASE.2023-03-20T20-16-18Z
# environment:
# MINIO_ACCESS_KEY: minioadmin
# MINIO_SECRET_KEY: minioadmin
# ports:
# - "9001:9001"
# - "9000:9000"
# volumes:
# - ${DOCKER_VOLUME_DIRECTORY:-.}/volumes/minio:/minio_data
# command: minio server /minio_data --console-address ":9001"
# healthcheck:
# test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"]
# interval: 30s
# timeout: 20s
# retries: 3
# standalone:
# container_name: milvus-standalone
# image: milvusdb/milvus:v2.5.10
# command: ["milvus", "run", "standalone"]
# security_opt:
# - seccomp:unconfined
# environment:
# ETCD_ENDPOINTS: etcd:2379
# MINIO_ADDRESS: minio:9000
# volumes:
# - ${DOCKER_VOLUME_DIRECTORY:-.}/volumes/milvus:/var/lib/milvus
# healthcheck:
# test: ["CMD", "curl", "-f", "http://localhost:9091/healthz"]
# interval: 30s
# start_period: 90s
# timeout: 20s
# retries: 3
# ports:
# - "19530:19530"
# - "9091:9091"
# depends_on:
# - "etcd"
# - "minio"
# db:
# image: mysql/mysql-server
# environment:
# MYSQL_USER: 'user'
# MYSQL_PASSWORD: 'password'
# MYSQL_ROOT_PASSWORD: 'aa123456'
# ports:
# - 3306:3306
# volumes:
# - dbgpt-myql-db:/var/lib/mysql
# - ./docker/examples/my.cnf:/etc/my.cnf
# - ./docker/examples/sqls:/docker-entrypoint-initdb.d
# - ./assets/schema/dbgpt.sql:/docker-entrypoint-initdb.d/dbgpt.sql
# restart: unless-stopped
# webserver:
# image: eosphorosai/dbgpt-openai:latest
# command: dbgpt start webserver --config /app/configs/dbgpt-graphrag.toml
# environment:
# - SILICONFLOW_API_KEY=${SILICONFLOW_API_KEY}
# - MYSQL_PASSWORD=aa123456
# - MYSQL_HOST=db
# - MYSQL_PORT=3306
# - MYSQL_DATABASE=dbgpt
# - MYSQL_USER=root
# - OPENAI_API_KEY=sk-UIpD9DohtE0Ok4wtFdC21668Dc3241629e8aA05d5dAeFdA1
# volumes:
# - ./configs:/app/configs
# - /data:/data
# # May be you can mount your models to container
# - /data/models:/app/models
# - dbgpt-data:/app/pilot/data
# - dbgpt-message:/app/pilot/message
# depends_on:
# - db
# - tugraph
# ports:
# - 5670:5670/tcp
# # webserver may be failed, it must wait all sqls in /docker-entrypoint-initdb.d execute finish.
# restart: unless-stopped
# networks:
# - dbgptnet
# ipc: host
# tugraph:
# image: tugraph/tugraph-runtime-centos7:4.5.1
# command: lgraph_server -d run --enable_plugin true
# ports:
# - 7070:7070
# - 7687:7687
# - 9090:9090
# container_name: tugraph_demo
# restart: unless-stopped
# volumes:
# dbgpt-myql-db:
# dbgpt-data:
# dbgpt-message:
# dbgpt-alembic-versions:
......@@ -74,6 +74,8 @@ require (
github.com/swaggo/files v1.0.1 // indirect
github.com/swaggo/http-swagger v1.3.4 // indirect
github.com/swaggo/swag v1.16.4 // indirect
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.1180 // indirect
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/lkeap v1.0.1179 // indirect
github.com/test-go/testify v1.1.4 // indirect
github.com/tidwall/gjson v1.18.0 // indirect
github.com/tidwall/match v1.1.1 // indirect
......@@ -105,4 +107,4 @@ require (
gopkg.in/yaml.v3 v3.0.1 // indirect
)
replace github.com/firebase/genkit/go => ../genkit/go
replace github.com/firebase/genkit/go => github.com/wade-liwei/genkit-web/go v0.0.0-20250605093206-aab2d64e9700
\ No newline at end of file
......@@ -318,6 +318,11 @@ github.com/swaggo/http-swagger v1.3.4 h1:q7t/XLx0n15H1Q9/tk3Y9L4n210XzJF5WtnDX64
github.com/swaggo/http-swagger v1.3.4/go.mod h1:9dAh0unqMBAlbp1uE2Uc2mQTxNMU/ha4UbucIg1MFkQ=
github.com/swaggo/swag v1.16.4 h1:clWJtd9LStiG3VeijiCfOVODP6VpHtKdQy9ELFG3s1A=
github.com/swaggo/swag v1.16.4/go.mod h1:VBsHJRsDvfYvqoiMKnsdwhNV9LEMHgEDZcyVYX0sxPg=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.1179/go.mod h1:r5r4xbfxSaeR04b166HGsBa/R4U3SueirEUpXGuw+Q0=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.1180 h1:k1q0xmirtk285MAjO79xcgYMNj5KBbNGbdiN3is8p2E=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.1180/go.mod h1:r5r4xbfxSaeR04b166HGsBa/R4U3SueirEUpXGuw+Q0=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/lkeap v1.0.1179 h1:JiFl6PpxQCHStBvlEtkr0hZKwAT8i/OX3C0hyqsIeEQ=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/lkeap v1.0.1179/go.mod h1:tmxc9DURqZNGJIbv6aWci0FxwkqrSevwkmStsFeX5LE=
github.com/test-go/testify v1.1.4 h1:Tf9lntrKUMHiXQ07qBScBTSA0dhYQlu83hswqelv1iE=
github.com/test-go/testify v1.1.4/go.mod h1:rH7cfJo/47vWGdi4GPj16x3/t1xGOj2YxzmNQzk2ghU=
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
......@@ -337,6 +342,8 @@ github.com/valyala/fasthttp v1.6.0/go.mod h1:FstJa9V+Pj9vQ7OJie2qMHdwemEDaDiSdBn
github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8=
github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
github.com/valyala/tcplisten v0.0.0-20161114210144-ceec8f93295a/go.mod h1:v3UYOV9WzVtRmSR+PDvWpU/qWl4Wa5LApYYX4ZtKbio=
github.com/wade-liwei/genkit-web/go v0.0.0-20250605093206-aab2d64e9700 h1:eLxnJ2ApSEvLfsaeW7jHVzAJ9Px/Nu4DLuw0zzwWtOU=
github.com/wade-liwei/genkit-web/go v0.0.0-20250605093206-aab2d64e9700/go.mod h1:+YRtLa+m5EQLU6B0ukcrhaeukNeJx1EKYvTOFqdp9NI=
github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc=
github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw=
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
......
......@@ -7,6 +7,7 @@ import (
"fmt"
"net/http"
"strings"
"time"
"github.com/firebase/genkit/go/ai"
"github.com/firebase/genkit/go/genkit"
......@@ -307,6 +308,9 @@ func main() {
log.Info().Msgf("promptInput.Context: %s", promptInput.Context)
}
begin := time.Now()
graphResponse, err := ai.Retrieve(ctx, graphRetriever, ai.WithDocs(dRequest))
if err != nil {
log.Error().Msgf("graph Retrieve err.Error() %s", err.Error())
......@@ -320,6 +324,11 @@ func main() {
log.Info().Msgf("promptInput.Graph : %s", promptInput.Graph)
}
fmt.Println("graph time",time.Since(begin).Seconds())
resp, err := simpleQaPrompt.Execute(ctx, ai.WithInput(promptInput))
if err != nil {
......
ubuntu@ip-172-26-8-199:~/DB-GPT$ cat docker-compose.yml
# To run current docker compose file, you should prepare the siliconflow api key in your environment.
# SILICONFLOW_API_KEY=${SILICONFLOW_API_KEY} docker compose up -d
services:
......@@ -68,5 +66,3 @@ networks:
driver: bridge
name: dbgptnet
ubuntu@ip-172-26-8-199:~/DB-GPT$
package main
import (
"fmt"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
lkeap "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/lkeap/v20240522"
)
func main() {
// 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
// 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性
// 以下代码示例仅供参考,建议采用更安全的方式来使用密钥
// 请参见:https://cloud.tencent.com/document/product/1278/85305
// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
//os.Setenv("TENCENTCLOUD_SECRET_ID", "AKID64oLfmfLtESUJ6i8LPSM4gCVbiniQuBF")
//os.Setenv("TENCENTCLOUD_SECRET_KEY", "rX2JMBnBMJ2YqulOo37xa5OUMSN4Xnpd")
credential := common.NewCredential(
"AKID64oLfmfLtESUJ6i8LPSM4gCVbiniQuBF",
"rX2JMBnBMJ2YqulOo37xa5OUMSN4Xnpd",
)
// 使用临时密钥示例
// credential := common.NewTokenCredential("SecretId", "SecretKey", "Token")
// 实例化一个client选项,可选的,没有特殊需求可以跳过
cpf := profile.NewClientProfile()
cpf.HttpProfile.Endpoint = "lkeap.tencentcloudapi.com"
// 实例化要请求产品的client对象,clientProfile是可选的
client, _ := lkeap.NewClient(credential, "ap-guangzhou", cpf)
// 实例化一个请求对象,每个接口都会对应一个request对象
request := lkeap.NewQueryRewriteRequest()
request.Model = common.StringPtr("*")
// 返回的resp是一个QueryRewriteResponse的实例,与请求对象对应
response, err := client.QueryRewrite(request)
if _, ok := err.(*errors.TencentCloudSDKError); ok {
fmt.Printf("An API error has returned: %s", err)
return
}
if err != nil {
panic(err)
}
// 输出json格式的字符串回包
fmt.Printf("%s", response.ToJsonString())
}
\ No newline at end of file
// Copyright 2025
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
package knowledge
import (
"context"
"encoding/json"
"fmt"
"os"
"sync"
"github.com/rs/zerolog/log"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
lkeap "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/lkeap/v20240522"
)
// ClientConfig holds configuration options for the Tencent Cloud LKEAP client.
type ClientConfig struct {
SecretID string // Tencent Cloud Secret ID
SecretKey string // Tencent Cloud Secret Key
Token string // Optional: Temporary token for authentication
Endpoint string // API endpoint (default: lkeap.tencentcloudapi.com)
Region string // Tencent Cloud region (optional)
}
// KnowledgeClient manages interactions with the Tencent Cloud LKEAP API.
type KnowledgeClient struct {
client *lkeap.Client
config ClientConfig
mu sync.Mutex
initted bool
}
// NewKnowledgeClient creates a new KnowledgeClient with the given configuration.
func NewKnowledgeClient(config ClientConfig) *KnowledgeClient {
log.Info().
Str("method", "NewKnowledgeClient").
Str("endpoint", config.Endpoint).
Str("region", config.Region).
Msg("Creating new KnowledgeClient")
return &KnowledgeClient{
config: config,
}
}
// Init initializes the KnowledgeClient.
func (kc *KnowledgeClient) Init(ctx context.Context) error {
log.Info().Str("method", "KnowledgeClient.Init").Msg("Initializing KnowledgeClient")
kc.mu.Lock()
defer kc.mu.Unlock()
if kc.initted {
log.Error().Str("method", "KnowledgeClient.Init").Msg("Client already initialized")
return fmt.Errorf("knowledge client already initialized")
}
// Load configuration defaults
if kc.config.SecretID == "" {
kc.config.SecretID = os.Getenv("TENCENTCLOUD_SECRET_ID")
}
if kc.config.SecretKey == "" {
kc.config.SecretKey = os.Getenv("TENCENTCLOUD_SECRET_KEY")
}
if kc.config.Token == "" {
kc.config.Token = os.Getenv("TENCENTCLOUD_TOKEN")
}
if kc.config.Endpoint == "" {
kc.config.Endpoint = "lkeap.tencentcloudapi.com"
}
if kc.config.Region == "" {
kc.config.Region = "" // Region can be empty for global APIs
}
// Validate configuration
if kc.config.SecretID == "" || kc.config.SecretKey == "" {
log.Error().Str("method", "KnowledgeClient.Init").Msg("SecretID and SecretKey are required")
return fmt.Errorf("knowledge: SecretID and SecretKey are required")
}
// Create credential
var credential *common.Credential
if kc.config.Token != "" {
credential = common.NewTokenCredential(kc.config.SecretID, kc.config.SecretKey, kc.config.Token)
log.Debug().Str("method", "KnowledgeClient.Init").Msg("Using temporary token credential")
} else {
credential = common.NewCredential(kc.config.SecretID, kc.config.SecretKey)
log.Debug().Str("method", "KnowledgeClient.Init").Msg("Using standard credential")
}
// Create client profile
cpf := profile.NewClientProfile()
cpf.HttpProfile.Endpoint = kc.config.Endpoint
// Initialize client
client, err := lkeap.NewClient(credential, kc.config.Region, cpf)
if err != nil {
log.Error().
Err(err).
Str("method", "KnowledgeClient.Init").
Msg("Failed to create LKEAP client")
return err
}
kc.client = client
kc.initted = true
log.Info().Str("method", "KnowledgeClient.Init").Msg("Initialization successful")
return nil
}
// QueryRewriteRequest defines the input for a query rewrite operation.
type QueryRewriteRequest struct {
Messages []*lkeap.Message // Multi-turn conversation history (up to 4 turns)
Model string // Model name for query rewriting
}
// QueryRewriteResponse defines the output of a query rewrite operation.
type QueryRewriteResponse struct {
RewrittenQuery string // The rewritten query
RawResponse *lkeap.QueryRewriteResponse
}
// QueryRewrite performs a query rewrite using the Tencent Cloud LKEAP API.
func (kc *KnowledgeClient) QueryRewrite(ctx context.Context, req QueryRewriteRequest) (*QueryRewriteResponse, error) {
log.Info().
Str("method", "KnowledgeClient.QueryRewrite").
Int("message_count", len(req.Messages)).
Str("model", req.Model).
Msg("Starting query rewrite operation")
if !kc.initted {
log.Error().Str("method", "KnowledgeClient.QueryRewrite").Msg("Client not initialized")
return nil, fmt.Errorf("knowledge client not initialized; call Init first")
}
// Validate input
if len(req.Messages) == 0 {
log.Error().Str("method", "KnowledgeClient.QueryRewrite").Msg("At least one message is required")
return nil, fmt.Errorf("at least one message is required")
}
if len(req.Messages) > 4 {
log.Warn().
Str("method", "KnowledgeClient.QueryRewrite").
Int("message_count", len(req.Messages)).
Msg("Message count exceeds 4, truncating to 4")
req.Messages = req.Messages[:4]
}
for i, msg := range req.Messages {
if msg.Role == nil || *msg.Role == "" {
log.Error().
Str("method", "KnowledgeClient.QueryRewrite").
Int("index", i).
Msg("Role is required in each message")
return nil, fmt.Errorf("message at index %d missing role", i)
}
if *msg.Role != "user" && *msg.Role != "assistant" {
log.Error().
Str("method", "KnowledgeClient.QueryRewrite").
Int("index", i).
Str("role", *msg.Role).
Msg("Invalid role; must be 'user' or 'assistant'")
return nil, fmt.Errorf("invalid role '%s' at index %d", *msg.Role, i)
}
if msg.Content == nil || *msg.Content == "" {
log.Error().
Str("method", "KnowledgeClient.QueryRewrite").
Int("index", i).
Msg("Content is required in each message")
return nil, fmt.Errorf("message at index %d missing content", i)
}
log.Debug().
Str("method", "KnowledgeClient.QueryRewrite").
Int("index", i).
Str("role", *msg.Role).
Str("content", *msg.Content).
Msg("Validated message")
}
if req.Model == "" {
log.Warn().Str("method", "KnowledgeClient.QueryRewrite").Msg("Model not specified, using default")
}
// Create Tencent Cloud request
tencentReq := lkeap.NewQueryRewriteRequest()
tencentReq.Messages = req.Messages // Directly use validated messages
if req.Model != "" {
tencentReq.Model = common.StringPtr(req.Model)
}
fmt.Println("len(tencentReq.Messages)",len(tencentReq.Messages))
tencentReqAsJson, _ := json.Marshal(tencentReq)
fmt.Println("len(tencentReq.Messages) json marsh",string(tencentReqAsJson))
// Perform request
response, err := kc.client.QueryRewriteWithContext(ctx, tencentReq)
if err != nil {
if _, ok := err.(*errors.TencentCloudSDKError); ok {
log.Error().
Err(err).
Str("method", "KnowledgeClient.QueryRewrite").
Msg("Tencent Cloud API error")
return nil, fmt.Errorf("tencent cloud api error: %w", err)
}
log.Error().
Err(err).
Str("method", "KnowledgeClient.QueryRewrite").
Msg("Failed to perform query rewrite")
return nil, fmt.Errorf("query rewrite failed: %w", err)
}
// Extract response fields
var rewrittenQuery string
var requestId string
if response.Response.Content != nil {
rewrittenQuery = *response.Response.Content
}
if response.Response.RequestId != nil {
requestId = *response.Response.RequestId
}
result := &QueryRewriteResponse{
RewrittenQuery: rewrittenQuery,
// Usage: response.Response.Usage,
// RequestId: requestId,
RawResponse: response,
}
log.Info().
Str("method", "KnowledgeClient.QueryRewrite").
Str("rewritten_query", rewrittenQuery).
Str("request_id", requestId).
Interface("usage", response.Response.Usage).
Str("raw_response", response.ToJsonString()).
Msg("Query rewrite operation completed successfully")
return result, nil
}
// // Extract rewritten query
// var rewrittenQuery string
// if response.Response.RewrittenQuery != nil {
// rewrittenQuery = *response.Response.RewrittenQuery
// }
// result := &QueryRewriteResponse{
// RewrittenQuery: rewrittenQuery,
// RawResponse: response,
// }
// log.Info().
// Str("method", "KnowledgeClient.QueryRewrite").
// Str("rewritten_query", rewrittenQuery).
// Str("raw_response", response.ToJsonString()).
// Msg("Query rewrite operation completed successfully")
// return result, nil
// }
// // Copyright 2025
// //
// // Licensed under the Apache License, Version 2.0 (the "License");
// // you may not use this file except in compliance with the License.
// // You may obtain a copy of the License at
// //
// // http://www.apache.org/licenses/LICENSE-2.0
// //
// // Unless required by applicable law or agreed to in writing, software
// // distributed under the License is distributed on an "AS IS" BASIS,
// // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// // See the License for the specific language governing permissions and
// // limitations under the License.
// //
// // SPDX-License-Identifier: Apache-2.0
// package knowledge
// import (
// "context"
// "fmt"
// "os"
// "sync"
// "github.com/rs/zerolog/log"
// "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
// "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
// "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
// lkeap "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/lkeap/v20240522"
// )
// // ClientConfig holds configuration options for the Tencent Cloud LKEAP client.
// type ClientConfig struct {
// SecretID string // Tencent Cloud Secret ID
// SecretKey string // Tencent Cloud Secret Key
// Token string // Optional: Temporary token for authentication
// Endpoint string // API endpoint (default: lkeap.tencentcloudapi.com)
// Region string // Tencent Cloud region (optional)
// }
// // KnowledgeClient manages interactions with the Tencent Cloud LKEAP API.
// type KnowledgeClient struct {
// client *lkeap.Client
// config ClientConfig
// mu sync.Mutex
// initted bool
// }
// // NewKnowledgeClient creates a new KnowledgeClient with the given configuration.
// func NewKnowledgeClient(config ClientConfig) *KnowledgeClient {
// log.Info().
// Str("method", "NewKnowledgeClient").
// Str("endpoint", config.Endpoint).
// Str("region", config.Region).
// Msg("Creating new KnowledgeClient")
// return &KnowledgeClient{
// config: config,
// }
// }
// // Init initializes the KnowledgeClient.
// func (kc *KnowledgeClient) Init(ctx context.Context) error {
// log.Info().Str("method", "KnowledgeClient.Init").Msg("Initializing KnowledgeClient")
// kc.mu.Lock()
// defer kc.mu.Unlock()
// if kc.initted {
// log.Error().Str("method", "KnowledgeClient.Init").Msg("Client already initialized")
// return errors.New("knowledge client already initialized")
// }
// // Load configuration defaults
// if kc.config.SecretID == "" {
// kc.config.SecretID = os.Getenv("TENCENTCLOUD_SECRET_ID")
// }
// if kc.config.SecretKey == "" {
// kc.config.SecretKey = os.Getenv("TENCENTCLOUD_SECRET_KEY")
// }
// if kc.config.Token == "" {
// kc.config.Token = os.Getenv("TENCENTCLOUD_TOKEN")
// }
// if kc.config.Endpoint == "" {
// kc.config.Endpoint = "lkeap.tencentcloudapi.com"
// }
// if kc.config.Region == "" {
// kc.config.Region = "" // Region can be empty for global APIs
// }
// // Validate configuration
// if kc.config.SecretID == "" || kc.config.SecretKey == "" {
// log.Error().Str("method", "KnowledgeClient.Init").Msg("SecretID and SecretKey are required")
// return fmt.Errorf("knowledge: SecretID and SecretKey are required")
// }
// // Create credential
// var credential *common.Credential
// if kc.config.Token != "" {
// credential = common.NewTokenCredential(kc.config.SecretID, kc.config.SecretKey, kc.config.Token)
// log.Debug().Str("method", "KnowledgeClient.Init").Msg("Using temporary token credential")
// } else {
// credential = common.NewCredential(kc.config.SecretID, kc.config.SecretKey)
// log.Debug().Str("method", "KnowledgeClient.Init").Msg("Using standard credential")
// }
// // Create client profile
// cpf := profile.NewClientProfile()
// cpf.HttpProfile.Endpoint = kc.config.Endpoint
// // Initialize client
// client, err := lkeap.NewClient(credential, kc.config.Region, cpf)
// if err != nil {
// log.Error().
// Err(err).
// Str("method", "KnowledgeClient.Init").
// Msg("Failed to create LKEAP client")
// return err
// }
// kc.client = client
// kc.initted = true
// log.Info().Str("method", "KnowledgeClient.Init").Msg("Initialization successful")
// return nil
// }
// // Message represents a single turn in a conversation.
// type Message struct {
// User string // User's question
// Assistant string // Assistant's response
// }
// // QueryRewriteRequest defines the input for a query rewrite operation.
// type QueryRewriteRequest struct {
// Messages []*Message // Multi-turn conversation history (up to 4 turns)
// Model string // Model name for query rewriting
// }
// // QueryRewriteResponse defines the output of a query rewrite operation.
// type QueryRewriteResponse struct {
// RewrittenQuery string // The rewritten query
// RawResponse *lkeap.QueryRewriteResponse
// }
// // QueryRewrite performs a query rewrite using the Tencent Cloud LKEAP API.
// func (kc *KnowledgeClient) QueryRewrite(ctx context.Context, req QueryRewriteRequest) (*QueryRewriteResponse, error) {
// log.Info().
// Str("method", "KnowledgeClient.QueryRewrite").
// Int("message_count", len(req.Messages)).
// Str("model", req.Model).
// Msg("Starting query rewrite operation")
// if !kc.initted {
// log.Error().Str("method", "KnowledgeClient.QueryRewrite").Msg("Client not initialized")
// return nil, fmt.Errorf("knowledge client not initialized; call Init first")
// }
// // Validate input
// if len(req.Messages) == 0 {
// log.Error().Str("method", "KnowledgeClient.QueryRewrite").Msg("At least one message is required")
// return nil, fmt.Errorf("at least one message is required")
// }
// if len(req.Messages) > 4 {
// log.Warn().
// Str("method", "KnowledgeClient.QueryRewrite").
// Int("message_count", len(req.Messages)).
// Msg("Message count exceeds 4, truncating to 4")
// req.Messages = req.Messages[:4]
// }
// for i, msg := range req.Messages {
// if msg.User == "" || msg.Assistant == "" {
// log.Error().
// Str("method", "KnowledgeClient.QueryRewrite").
// Int("index", i).
// Msg("User and Assistant fields are required in each message")
// return nil, fmt.Errorf("message at index %d missing user or assistant", i)
// }
// }
// if req.Model == "" {
// log.Warn().Str("method", "KnowledgeClient.QueryRewrite").Msg("Model not specified, using default")
// }
// // Create Tencent Cloud request
// tencentReq := lkeap.NewQueryRewriteRequest()
// tencentReq.Messages = make([]*lkeap.Message, len(req.Messages))
// for i, msg := range req.Messages {
// tencentReq.Messages[i] = &lkeap.Message{
// User: common.StringPtr(msg.User),
// Assistant: common.StringPtr(msg.Assistant),
// }
// log.Debug().
// Str("method", "KnowledgeClient.QueryRewrite").
// Int("index", i).
// Str("user", msg.User).
// Str("assistant", msg.Assistant).
// Msg("Added message to request")
// }
// if req.Model != "" {
// tencentReq.Model = common.StringPtr(req.Model)
// }
// // Perform request
// response, err := kc.client.QueryRewriteWithContext(ctx, tencentReq)
// if err != nil {
// if _, ok := err.(*errors.TencentCloudSDKError); ok {
// log.Error().
// Err(err).
// Str("method", "KnowledgeClient.QueryRewrite").
// Msg("Tencent Cloud API error")
// return nil, fmt.Errorf("tencent cloud api error: %w", err)
// }
// log.Error().
// Err(err).
// Str("method", "KnowledgeClient.QueryRewrite").
// Msg("Failed to perform query rewrite")
// return nil, fmt.Errorf("query rewrite failed: %w", err)
// }
// // Extract rewritten query
// var rewrittenQuery string
// if response.Response.RewrittenQuery != nil {
// rewrittenQuery = *response.Response.RewrittenQuery
// }
// result := &QueryRewriteResponse{
// RewrittenQuery: rewrittenQuery,
// RawResponse: response,
// }
// log.Info().
// Str("method", "KnowledgeClient.QueryRewrite").
// Str("rewritten_query", rewrittenQuery).
// Str("raw_response", response.ToJsonString()).
// Msg("Query rewrite operation completed successfully")
// return result, nil
// }
// // Copyright 2025
// //
// // Licensed under the Apache License, Version 2.0 (the "License");
// // you may not use this file except in compliance with the License.
// // You may obtain a copy of the License at
// //
// // http://www.apache.org/licenses/LICENSE-2.0
// //
// // Unless required by applicable law or agreed to in writing, software
// // distributed under the License is distributed on an "AS IS" BASIS,
// // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// // See the License for the specific language governing permissions and
// // limitations under the License.
// //
// // SPDX-License-Identifier: Apache-2.0
// package knowledge
// import (
// "context"
// "fmt"
// "os"
// "sync"
// "github.com/rs/zerolog/log"
// "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
// "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
// "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
// lkeap "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/lkeap/v20240522"
// )
// // ClientConfig holds configuration options for the Tencent Cloud LKEAP client.
// type ClientConfig struct {
// SecretID string // Tencent Cloud Secret ID
// SecretKey string // Tencent Cloud Secret Key
// Token string // Optional: Temporary token for authentication
// Endpoint string // API endpoint (default: lkeap.tencentcloudapi.com)
// Region string // Tencent Cloud region (optional)
// }
// // KnowledgeClient manages interactions with the Tencent Cloud LKEAP API.
// type KnowledgeClient struct {
// client *lkeap.Client
// config ClientConfig
// mu sync.Mutex
// initted bool
// }
// // NewKnowledgeClient creates a new KnowledgeClient with the given configuration.
// func NewKnowledgeClient(config ClientConfig) *KnowledgeClient {
// log.Info().
// Str("method", "NewKnowledgeClient").
// Str("endpoint", config.Endpoint).
// Str("region", config.Region).
// Msg("Creating new KnowledgeClient")
// return &KnowledgeClient{
// config: config,
// }
// }
// // Init initializes the KnowledgeClient.
// func (kc *KnowledgeClient) Init(ctx context.Context) error {
// log.Info().Str("method", "KnowledgeClient.Init").Msg("Initializing KnowledgeClient")
// kc.mu.Lock()
// defer kc.mu.Unlock()
// if kc.initted {
// log.Error().Str("method", "KnowledgeClient.Init").Msg("Client already initialized")
// return fmt.Errorf("knowledge client already initialized")
// }
// // Load configuration defaults
// if kc.config.SecretID == "" {
// kc.config.SecretID = os.Getenv("TENCENTCLOUD_SECRET_ID")
// }
// if kc.config.SecretKey == "" {
// kc.config.SecretKey = os.Getenv("TENCENTCLOUD_SECRET_KEY")
// }
// if kc.config.Token == "" {
// kc.config.Token = os.Getenv("TENCENTCLOUD_TOKEN")
// }
// if kc.config.Endpoint == "" {
// kc.config.Endpoint = "lkeap.tencentcloudapi.com"
// }
// if kc.config.Region == "" {
// kc.config.Region = "" // Region can be empty for global APIs
// }
// // Validate configuration
// if kc.config.SecretID == "" || kc.config.SecretKey == "" {
// log.Error().Str("method", "KnowledgeClient.Init").Msg("SecretID and SecretKey are required")
// //return errors.New("knowledge: SecretID and SecretKey are required")
// return fmt.Errorf("knowledge: SecretID and SecretKey are required")
// }
// // Create credential
// var credential *common.Credential
// if kc.config.Token != "" {
// credential = common.NewTokenCredential(kc.config.SecretID, kc.config.SecretKey, kc.config.Token)
// log.Debug().Str("method", "KnowledgeClient.Init").Msg("Using temporary token credential")
// } else {
// credential = common.NewCredential(kc.config.SecretID, kc.config.SecretKey)
// log.Debug().Str("method", "KnowledgeClient.Init").Msg("Using standard credential")
// }
// // Create client profile
// cpf := profile.NewClientProfile()
// cpf.HttpProfile.Endpoint = kc.config.Endpoint
// // Initialize client
// client, err := lkeap.NewClient(credential, kc.config.Region, cpf)
// if err != nil {
// log.Error().
// Err(err).
// Str("method", "KnowledgeClient.Init").
// Msg("Failed to create LKEAP client")
// return err
// }
// kc.client = client
// kc.initted = true
// log.Info().Str("method", "KnowledgeClient.Init").Msg("Initialization successful")
// return nil
// }
// // QueryRewriteRequest defines the input for a query rewrite operation.
// type QueryRewriteRequest struct {
// Query string // The input query to rewrite
// }
// // QueryRewriteResponse defines the output of a query rewrite operation.
// type QueryRewriteResponse struct {
// RewrittenQuery string // The rewritten query
// RawResponse *lkeap.QueryRewriteResponse
// }
// // QueryRewrite performs a query rewrite using the Tencent Cloud LKEAP API.
// func (kc *KnowledgeClient) QueryRewrite(ctx context.Context, req QueryRewriteRequest) (*QueryRewriteResponse, error) {
// log.Info().
// Str("method", "KnowledgeClient.QueryRewrite").
// Str("query", req.Query).
// Msg("Starting query rewrite operation")
// if !kc.initted {
// log.Error().Str("method", "KnowledgeClient.QueryRewrite").Msg("Client not initialized")
// //return nil, errors.New("knowledge client not initialized; call Init first")
// return nil,fmt.Errorf("knowledge client not initialized; call Init first")
// }
// if req.Query == "" {
// log.Error().Str("method", "KnowledgeClient.QueryRewrite").Msg("Query is required")
// //return nil, errors.New("query is required")
// return nil, fmt.Errorf("query is required")
// }
// // Create request
// tencentReq := lkeap.NewQueryRewriteRequest()
// tencentReq.Query = common.StringPtr(req.Query)
// // Perform request
// response, err := kc.client.QueryRewriteWithContext(ctx, tencentReq)
// if err != nil {
// if _, ok := err.(*errors.TencentCloudSDKError); ok {
// log.Error().
// Err(err).
// Str("method", "KnowledgeClient.QueryRewrite").
// Msg("Tencent Cloud API error")
// return nil, fmt.Errorf("tencent cloud api error: %w", err)
// }
// log.Error().
// Err(err).
// Str("method", "KnowledgeClient.QueryRewrite").
// Msg("Failed to perform query rewrite")
// return nil, fmt.Errorf("query rewrite failed: %w", err)
// }
// // Extract rewritten query
// var rewrittenQuery string
// if response.Response.RewrittenQuery != nil {
// rewrittenQuery = *response.Response.RewrittenQuery
// }
// result := &QueryRewriteResponse{
// RewrittenQuery: rewrittenQuery,
// RawResponse: response,
// }
// log.Info().
// Str("method", "KnowledgeClient.QueryRewrite").
// Str("rewritten_query", rewrittenQuery).
// Str("raw_response", response.ToJsonString()).
// Msg("Query rewrite operation completed successfully")
// return result, nil
// }
package knowledge
import (
"fmt"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
lkeap "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/lkeap/v20240522"
)
func knowldge() {
// 实例化一个认证对象,入参需要传入腾讯云账户 SecretId SecretKey,此处还需注意密钥对的保密
// 代码泄露可能会导致 SecretId SecretKey 泄露,并威胁账号下所有资源的安全性
// 以下代码示例仅供参考,建议采用更安全的方式来使用密钥
// 请参见:https://cloud.tencent.com/document/product/1278/85305
// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
credential := common.NewCredential(
"SecretId",
"SecretKey",
)
// 使用临时密钥示例
// credential := common.NewTokenCredential("SecretId", "SecretKey", "Token")
// 实例化一个client选项,可选的,没有特殊需求可以跳过
cpf := profile.NewClientProfile()
cpf.HttpProfile.Endpoint = "lkeap.tencentcloudapi.com"
// 实例化要请求产品的client对象,clientProfile是可选的
client, _ := lkeap.NewClient(credential, "", cpf)
// 实例化一个请求对象,每个接口都会对应一个request对象
request := lkeap.NewQueryRewriteRequest()
// 返回的resp是一个QueryRewriteResponse的实例,与请求对象对应
response, err := client.QueryRewrite(request)
if _, ok := err.(*errors.TencentCloudSDKError); ok {
fmt.Printf("An API error has returned: %s", err)
return
}
if err != nil {
panic(err)
}
// 输出json格式的字符串回包
fmt.Printf("%s", response.ToJsonString())
}
\ No newline at end of file
// Copyright 2025
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
package knowledge
import (
"context"
"os"
"testing"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
lkeap "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/lkeap/v20240522"
)
func TestMain(m *testing.M) {
// Configure zerolog for human-readable console output during tests
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
// Run tests
os.Exit(m.Run())
}
func TestKnowledgeClient_QueryRewrite(t *testing.T) {
// Warning: Do not hardcode credentials in production code. Use environment variables or a secure vault.
// The credentials below are assumed to be placeholders for testing purposes.
os.Setenv("TENCENTCLOUD_SECRET_ID", "AKID64oLfmfLtESUJ6i8LPSM4gCVbiniQuBF")
os.Setenv("TENCENTCLOUD_SECRET_KEY", "rX2JMBnBMJ2YqulOo37xa5OUMSN4Xnpd")
defer func() {
os.Unsetenv("TENCENTCLOUD_SECRET_ID")
os.Unsetenv("TENCENTCLOUD_SECRET_KEY")
}()
// Create client configuration
config := ClientConfig{
Endpoint: "lkeap.tencentcloudapi.com",
Region: "ap-guangzhou",
}
// Initialize client
client := NewKnowledgeClient(config)
ctx := context.Background()
// Test cases
tests := []struct {
name string
messages []*lkeap.Message
model string
expectError bool
}{
{
name: "ValidMultiTurnConversation",
messages: []*lkeap.Message{
{
Role: common.StringPtr("user"),
Content: common.StringPtr("What is the capital of France?"),
},
{
Role: common.StringPtr("assistant"),
Content: common.StringPtr("The capital of France is Paris."),
},
{
Role: common.StringPtr("user"),
Content: common.StringPtr("Tell me more about Paris."),
},
{
Role: common.StringPtr("assistant"),
Content: common.StringPtr("Paris is known for its art, culture, and landmarks like the Eiffel Tower."),
},
},
model: "",
expectError: true, // Expect error unless valid credentials are used
},
{
name: "EmptyMessages",
messages: []*lkeap.Message{},
model: "",
expectError: true,
},
{
name: "InvalidRole",
messages: []*lkeap.Message{
{
Role: common.StringPtr("invalid-role"),
Content: common.StringPtr("Test query"),
},
},
model: "",
expectError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Initialize client for each test
if err := client.Init(ctx); err != nil {
t.Fatalf("Failed to initialize KnowledgeClient: %v", err)
}
// Perform query rewrite
req := QueryRewriteRequest{
Messages: tt.messages,
Model: tt.model,
}
resp, err := client.QueryRewrite(ctx, req)
// Check error expectation
if tt.expectError {
if err == nil {
t.Error("Expected error, got none")
} else {
log.Debug().
Str("method", "TestKnowledgeClient_QueryRewrite").
Str("test_name", tt.name).
Err(err).
Msg("Received expected error")
}
return
}
// Check response (only for non-error cases)
if err != nil {
t.Fatalf("QueryRewrite failed: %v", err)
}
if resp.RewrittenQuery == "" {
t.Error("Expected non-empty rewritten query")
}
// if resp.RequestId == "" {
// t.Error("Expected non-empty request ID")
// }
// if resp.Usage == nil {
// t.Error("Expected non-nil usage")
// }
log.Info().
Str("method", "TestKnowledgeClient_QueryRewrite").
Str("test_name", tt.name).
Str("rewritten_query", resp.RewrittenQuery).
// Str("request_id", resp.RequestId).
// Interface("usage", resp.Usage).
Msg("Query rewrite successful")
})
}
}
// // Copyright 2025
// //
// // Licensed under the Apache License, Version 2.0 (the "License");
// // you may not use this file except in compliance with the License.
// // You may obtain a copy of the License at
// //
// // http://www.apache.org/licenses/LICENSE-2.0
// //
// // Unless required by applicable law or agreed to in writing, software
// // distributed under the License is distributed on an "AS IS" BASIS,
// // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// // See the License for the specific language governing permissions and
// // limitations under the License.
// //
// // SPDX-License-Identifier: Apache-2.0
// package knowledge
// import (
// "context"
// "os"
// "testing"
// "github.com/rs/zerolog"
// "github.com/rs/zerolog/log"
// "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
// lkeap "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/lkeap/v20240522"
// )
// func TestMain(m *testing.M) {
// // Configure zerolog for human-readable console output during tests
// zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
// log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
// // Run tests
// os.Exit(m.Run())
// }
// /*
// SecretId:AKID64oLfmfLtESUJ6i8LPSM4gCVbiniQuBF
// SecretKey:rX2JMBnBMJ2YqulOo37xa5OUMSN4Xnpd
// */
// func TestKnowledgeClient_QueryRewrite(t *testing.T) {
// // Set up environment variables for testing (mock credentials)
// os.Setenv("TENCENTCLOUD_SECRET_ID", "AKID64oLfmfLtESUJ6i8LPSM4gCVbiniQuBF")
// os.Setenv("TENCENTCLOUD_SECRET_KEY", "rX2JMBnBMJ2YqulOo37xa5OUMSN4Xnpd")
// defer func() {
// os.Unsetenv("TENCENTCLOUD_SECRET_ID")
// os.Unsetenv("TENCENTCLOUD_SECRET_KEY")
// }()
// // Create client configuration
// config := ClientConfig{
// Endpoint: "lkeap.tencentcloudapi.com",
// Region: "ap-guangzhou",
// }
// // Initialize client
// client := NewKnowledgeClient(config)
// ctx := context.Background()
// // Test cases
// tests := []struct {
// name string
// messages []*lkeap.Message
// model string
// expectError bool
// }{
// {
// name: "ValidMultiTurnConversation",
// messages: []*lkeap.Message{
// {
// Role: common.StringPtr("user"),
// Content: common.StringPtr("What is the capital of France?"),
// },
// {
// Role: common.StringPtr("assistant"),
// Content: common.StringPtr("The capital of France is Paris."),
// },
// {
// Role: common.StringPtr("user"),
// Content: common.StringPtr("Tell me more about Paris."),
// },
// {
// Role: common.StringPtr("assistant"),
// Content: common.StringPtr("Paris is known for its art, culture, and landmarks like the Eiffel Tower."),
// },
// },
// model: "default-model",
// expectError: true, // Expect error due to mock credentials
// },
// {
// name: "EmptyMessages",
// messages: []*lkeap.Message{},
// model: "default-model",
// expectError: true,
// },
// {
// name: "InvalidRole",
// messages: []*lkeap.Message{
// {
// Role: common.StringPtr("invalid-role"),
// Content: common.StringPtr("Test query"),
// },
// },
// model: "default-model",
// expectError: true,
// },
// }
// for _, tt := range tests {
// t.Run(tt.name, func(t *testing.T) {
// // Initialize client for each test
// if err := client.Init(ctx); err != nil {
// t.Fatalf("Failed to initialize KnowledgeClient: %v", err)
// }
// // Perform query rewrite
// req := QueryRewriteRequest{
// Messages: tt.messages,
// Model: tt.model,
// }
// resp, err := client.QueryRewrite(ctx, req)
// // Check error expectation
// if tt.expectError {
// if err == nil {
// t.Error("Expected error, got none")
// } else {
// log.Debug().
// Str("method", "TestKnowledgeClient_QueryRewrite").
// Str("test_name", tt.name).
// Err(err).
// Msg("Received expected error")
// }
// return
// }
// // Check response (only for non-error cases)
// if err != nil {
// t.Fatalf("QueryRewrite failed: %v", err)
// }
// if resp.RewrittenQuery == "" {
// t.Error("Expected non-empty rewritten query")
// }
// log.Info().
// Str("method", "TestKnowledgeClient_QueryRewrite").
// Str("test_name", tt.name).
// Str("rewritten_query", resp.RewrittenQuery).
// Msg("Query rewrite successful")
// })
// }
// }
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment