检查提示是否有效-vertexai

问题描述 投票:0回答:1

我们正在使用Google App Engine Standard F1实例,Python 3.12。用户输入字符串,我们将其转换为提示,并从Genai获取输出。我们正在按照示例here的示例。 from google import genai from google.genai import types import base64 def generate(): client = genai.Client( vertexai=True, project="openbarn-ai-module", location="us-central1", ) model = "gemini-2.0-flash-001" contents = [ types.Content( role="user", parts=[ types.Part.from_text(text="""adkfjsadfafsd""") ] ) ] generate_content_config = types.GenerateContentConfig( temperature = 1, top_p = 0.95, max_output_tokens = 8192, response_modalities = ["TEXT"], safety_settings = [types.SafetySetting( category="HARM_CATEGORY_HATE_SPEECH", threshold="OFF" ),types.SafetySetting( category="HARM_CATEGORY_DANGEROUS_CONTENT", threshold="OFF" ),types.SafetySetting( category="HARM_CATEGORY_SEXUALLY_EXPLICIT", threshold="OFF" ),types.SafetySetting( category="HARM_CATEGORY_HARASSMENT", threshold="OFF" )], ) for chunk in client.models.generate_content_stream( model = model, contents = contents, config = generate_content_config, ): print(chunk.text, end="") generate()

字符串“ ADKFJSADFAFSD”是用户输入的垃圾。如果用户编写了有效的提示 - 例如“ AI如何工作”,则代码应尽其所能。但是,如何检查给定的字符串是否是有效的提示?如果提示是有效的,是否可以在调用Generate_Content_Stream之前确认?

google-cloud-vertex-ai google-gemini
1个回答
0
投票
I使用Gemini对代理进行了编码,该代理以1或0回答我在提示系统中指定的逻辑。

i在这里提供一个起始代码:

def valid_prompt_dispatcher(message): system_prompt = "You are a classifier that determines if an input is a meaningful and coherent sentence. Respond with '1' for valid inputs and '0' for gibberish." model = GenerativeModel( model_name="gemini-1.5-pro-002" system_instruction=system_prompt ) generation_config = GenerationConfig( top_p=0.9, temperature=0.7, top_k=32, candidate_count=1, max_output_tokens=10, ) chat = model.start_chat(history=[], response_validation=True) response = chat.send_message(message, generation_config=generation_config) return response.candidates[0].text.strip() == "1"

如果提示不散发,则此功能以true响应,否则返回false。

在您的代码中,您将必须做类似的事情:
if valid_prompt_dispatcher(prompt):
      contents = [
      types.Content(
        role="user",
        parts=[types.Part.from_text(text=prompt)
        ]
      )
    ]
else:
      raise Exception("Error: the prompt must not be gibberish")

当然,我不确定您正在使用的特定用途酶,因此仅插入了升高的例外来进行视觉解释。

如果此答案有助于解决您的问题,请考虑将其标记为帮助他人有相同问题的接受。


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.