paint-brush
Le Ndlela Entsha yokuKhuthaza yenza ukuba iziphumo ze-AI zisebenziseke ngokwenenenge@abhic137
2,049 ukufunda
2,049 ukufunda

Le Ndlela Entsha yokuKhuthaza yenza ukuba iziphumo ze-AI zisebenziseke ngokwenene

nge Abhishek Chadha15m2024/12/04
Read on Terminal Reader

Inde kakhulu; Ukufunda

I-meta-prompting ecwangcisiweyo bubuchule obuvelisa i-JSON schemas yezisombululo ngaphambi kokwenza imisebenzi. Oku kunceda ekudaleni ukusebenziseka kwakhona, okuthembekileyo, kunye nokwaziswa okuqikelelweyo.
featured image - Le Ndlela Entsha yokuKhuthaza yenza ukuba iziphumo ze-AI zisebenziseke ngokwenene
Abhishek Chadha HackerNoon profile picture
0-item
1-item
2-item

Umceli mngeni othe gqolo kwiimodeli ezinkulu zolwimi (LLMs) lutyekelo lwabo lokuvelisa imveliso engalindelekanga. Ngaphandle koncedo oluyilwe ngononophelo, iiLLM zihlala ziphambuka kulindelo, zenza imveliso yazo ibe nzima ukuphinda isetyenziswe okanye idityaniswe kukuhamba komsebenzi. Okubi nangakumbi, iziphumo azisoloko ziphinda-phinda, zinzima ukusetyenzwa komsinga.


Kule post yebhlog, siphonononga i-meta-prompting ecwangcisiweyo , ubuchule obuvelisa i-JSON schemas yezisombululo ngaphambi kokwenza imisebenzi. Oku kunceda ekudaleni ukusebenziseka kwakhona, okuthembekileyo, kunye nokwaziswa okuqikelelweyo.

Imvelaphi

Uninzi lweeLLM zangoku zibonelela ngemowudi yemveliso ye-JSON, kodwa iziphumo azihlali zihambelana ne-schema elindelekileyo. Abaphuhlisi bahlala bebhenela kwiindlela zokujonga kwaye baphinde bazame, ezidla ixesha, ezibizayo, kwaye ezithanda ukophula amava omsebenzisi.


Nge gpt4o , i-OpenAI yazisa iziphumo ezicwangcisiweyo eziqinisekisa ukuba imveliso iya kuhambelana ne-schema ye-JSON enikezelwe ngumsebenzisi. Nangona iinkcukacha ezithe ngqo zingaxelwanga, oku kunokwenzeka ukuba kuphunyezwe indibaniselwano yokubhalwa kweekhowuwudi okuthintelweyo kunye nesampulu yokulogit ecalanye. Ubuchule obufanayo bubonelelwa zezinye izixhobo ezinje ngesikhokelo, amagqabantshintshi, inversion, CommandR, SGlang. Ezi ndlela zixhobisa abaphuhlisi ukuba bakhokele iziphumo kwi-JSON schemas, nganye inorhwebo olulodwa.

Yintoni i-meta-prompting ecwangcisiweyo?

I-Meta-prompting ecwangcisiweyo nabuphi na ubuchule obusebenzisa i-LLM ukwenza ngokuguquguqukayo inkcazo ecwangcisiweyo yengxaki phambi kokuvelisa isisombululo. Le ndlela ibonelela ngeengenelo ezininzi ngaphezu kokukhuthaza ngokuthe ngqo:

  1. I-Dynamic : Ulwakhiwo lwemveliso lwenziwa ngexesha lokusebenza ngokusekwe kwiinkcazo zomsebenzi, kunokuba zifakwe iikhowudi okanye zilungiswe kakuhle kwimodeli.
  2. I-Aptable : I-schema evelisiweyo ifundeka ngumntu kwaye inokuhlolwa, ingqinisiswe, okanye ilungiswe ngabantu okanye ezinye iiLLM.
  3. Isebenziseka kwakhona : Ischema sinokugcinwa kwaye sisetyenziswe kwakhona kwimisebenzi emininzi, ukubaleka, kunye noomatshini.
  4. Uqikelelo oluqikelelweyo : Izisombululo ziya kuhambelana nesakhiwo esichazwe kakuhle, esenza ukuba zilungele ukubala phantsi.



Ikhowudi

Masihambe kumzekelo apho sisebenzisa i-meta-prompting ecwangcisiweyo ukwenza ulwandlalo lwenoveli entsha ethengisa kakhulu yentlola.

Yonke ikhowudi yale post blog ifumaneka kule Colab Notebook .

qiniseka ukuba useta OPENAI_API_KEY yakho kwiiMfihlo zeColab

1. Ukuvelisa isakhiwo

dInyathelo lokuqala kukuchaza i-schema ye-JSON echaza isiphumo esifunekayo. Ukwenza oku, siya kwenza i-schema ye-JSON ye-schema ye-JSON - ngokufanelekileyo, i -meta-schema ! Oku kunikezelwa njengenxalenye yenkcazo kodwa kufuneka senze utshintsho oluthile.

1.1 Ukulungisa imeta-schema

I-OpenAI kunye nee-API zemveliso ezicwangcisiweyo ze-OpenAI zibeka izithintelo ezininzi kwi-schemas ye-JSON eqhelekileyo. Oku kulishwa kodwa yinto esinokuyisebenzela ngoku. Siza kulungisa imeta-schema ukuqinisekisa ukuhambelana:

 from jsonschema import Draft202012Validator def openai_compatible_metaschema(schema: Dict[str, object]): schema["type"] = "object" del schema["allOf"] return schema openai_json_metaschema = openai_compatible_metaschema( copy.deepcopy(Draft202012Validator.META_SCHEMA) )


Qaphela *: Kuyabonakala ukuba* uguqulo alunazithintelo kwaye luxhasa i-JSON schemas ngokungekho mthethweni...kodwa akukho fikelelo luluntu okwangoku!

1.2 Ukongeza izithintelo kwi-meta-prompt yethu

Okulandelayo, sifaka izikhokelo kwi-prompt yokuqinisekisa ukuba i-schema ye-JSON esiphumo ithobela imiqobo ye-OpenAI. Njengokuba:

  • Onke amabala kufuneka afuneke.
  • Izinto zinemida kubunzulu bendlwane kunye nobukhulu.
  • Iipropati ezongezelelweyo kufuneka zingavunyelwa ( "additionalProperties": false ).
 system_guidelines = "\n".join( [ "All fields must be required - To use Structured Outputs, all fields or function parameters must be specified as required. NOTE: Although all fields must be required (and the model will return a value for each parameter), it is possible to emulate an optional parameter by using a union type with null." "Objects have limitations on nesting depth and size - A schema may have up to 100 object properties total, with up to 5 levels of nesting.", "Limitations on total string size - In a schema, total string length of all property names, definition names, enum values, and const values cannot exceed 15,000 characters.", "Limitations on enum size - A schema may have up to 500 enum values across all enum properties. For a single enum property with string values, the total string length of all enum values cannot exceed 7,500 characters when there are more than 250 enum values.", "additionalProperties: false must always be set in objects - additionalProperties controls whether it is allowable for an object to contain additional keys / values that were not defined in the JSON Schema. Structured Outputs only supports generating specified keys / values, so we require developers to set additionalProperties: false to opt into Structured Outputs.", "Some type-specific keywords are not yet supported - Notable keywords not supported include: For strings: minLength, maxLength, pattern, format; For numbers: minimum, maximum, multipleOf; For objects: patternProperties, unevaluatedProperties, propertyNames, minProperties, maxProperties; For arrays: unevaluatedItems, contains, minContains, maxContains, minItems, maxItems, uniqueItems", "For anyOf, the nested schemas must each be a valid JSON Schema per this subset", "Definitions are supported - You can use definitions to define subschemas which are referenced throughout your schema. The following is a simple example.", "Recursive schemas are supported - Sample recursive schema using # to indicate root recursion.", ] )

1.3 Ukumisela i-meta-prompt

Ngoku sichaza i-meta-prompt yokuvelisa i-schema ye-JSON ye-spy thriller outline.

 from langchain.prompts import ChatPromptTemplate task_description = "Write an outline for a bestselling spy thriller novel" task_guidelines = """ - You must follow one of the six basic story arcs: Rags to riches, Riches to rags, Icarus, Oedipus, Cinderella, Man in a hole - Outputs must include characters, plot points (including exposition, rising action, climax, falling action, and resolution), central conflict, setting, major turning points or "beats," character arcs, and a synopsis of the story; essentially, a detailed breakdown of the key elements that will drive the narrative throughout the novel. """ prompt_messages = ChatPromptTemplate.from_messages( [ ( "system", "You are an expert in creating JSON schemas. You have been asked to generate a detailed JSON schema for the output of a given task based based on a task desciption and some guidelines.", ), ( "system", "Your JSON schema must always adhere to the following system system guidelines for JSON schemas:\n<system_guidelines>\n{system_guidelines}\n</system_guidelines>", ), ( "user", "Use the task description and guidelines below to generate an output JSON schema for the following task based on the guidelines provided.\n\n<task_description>\n{task_description}\n</task_description>\n\n<guidelines>\n{task_guidelines}\n</guidelines>", ), ] )

1.4 Ukuvelisa ubume

Sicela iLLM ukwenza ischema:

 messages = prompt_messages.format_messages( system_guidelines=system_guidelines, task_description=task_description, task_guidelines=task_guidelines ) ## Make sure to set up OPENAI_API_KEY in your Colab Secrets ## https://x.com/GoogleColab/status/1719798406195867814 client = OpenAI(api_key=userdata.get('OPENAI_API_KEY')) model = "gpt-4o" metaprompt_completion = client.beta.chat.completions.parse( model=model, messages=convert_to_penai_messages(messages), response_format={ "type": "json_schema", "json_schema": JSONSchema( name="JsonMetaschema", description="JSON Metaschema for the 2020-12 Draft of the JSON Schema specification that can be used to validate JSON data", schema=openai_json_metaschema, strict=False, ) } ) task_output_schema = json.loads(metaprompt_completion.choices[0].message.content) print(json.dumps(task_output_schema, indent=2))


 { "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "Outline for a Bestselling Spy Thriller Novel", "type": "object", "properties": { "storyArc": { "type": "string", "enum": [ "Rags to riches", "Riches to rags", "Icarus", "Oedipus", "Cinderella", "Man in a hole" ] }, "characters": { "type": "array", "items": { "type": "object", "properties": { "name": { "type": "string" }, "role": { "type": "string" }, "description": { "type": "string" }, "arc": { "type": "string" } }, "required": ["name", "role", "description", "arc"], "additionalProperties": false }, "minItems": 1 }, "plotPoints": { "type": "object", "properties": { "exposition": { "type": "string" }, "risingAction": { "type": "string" }, "climax": { "type": "string" }, "fallingAction": { "type": "string" }, "resolution": { "type": "string" } }, "required": [ "exposition", "risingAction", "climax", "fallingAction", "resolution" ], "additionalProperties": false }, "centralConflict": { "type": "string" }, "setting": { "type": "string" }, "majorTurningPoints": { "type": "array", "items": { "type": "string" }, "minItems": 1 }, "characterArcs": { "type": "object", "properties": { "protagonistArc": { "type": "string" }, "antagonistArc": { "type": "string" }, "supportingCharactersArcs": { "type": "array", "items": { "type": "string" }, "minItems": 0 } }, "required": [ "protagonistArc", "antagonistArc", "supportingCharactersArcs" ], "additionalProperties": false }, "synopsis": { "type": "string" } }, "required": [ "storyArc", "characters", "plotPoints", "centralConflict", "setting", "majorTurningPoints", "characterArcs", "synopsis" ], "additionalProperties": false }


Ngoku sine-schema echaza ulwandlalo lwenoveli yethu ye-spythriller. Oku kunokuqhubekeka kwifayile okanye kwisiseko sedatha.

2. Ukuvelisa isisombululo

2.1 Ukuseta ngokukhawuleza

Ngokusebenzisa iskimu, sichaza isilumkiso kulwandlalo lwenoveli. siza kusebenzisa iimpembelelo ezisisiseko kunye nezikhokelo:

 user_requirements = "Tell a story about counter-intelligence operative working against the clock. The novel should be extremely realistic, slow burn." task_prompt = ChatPromptTemplate.from_messages( [ ( "system", "You are a world-renowned author that has written dozens of bestselling thriller novels. Your task is to create an outline for a new novel based on the user's requirements.", ), ( "user", "Please write a novel outline based strictly on the following requirements <requirements>{requirements}</requirements>", ), ] ) task_completion = client.beta.chat.completions.parse( model=model, messages=convert_to_openai_messages(task_prompt.format_messages(requirements=user_requirements)), response_format={ "type": "json_schema", "json_schema": JSONSchema( ## TODO: You can change this depending your task name="ThrillerNovelOutlineSchema", description="A schema for outlining a new novel", schema=task_output_schema, strict=False, ) } ) task_result = json.loads(task_completion.choices[0].message.content)


Nalu ulwandlalo lwentlola yethu elandelayo:

 { "storyArc": "Cinderella", "synopsis": "In 'The Clockwork Veil', Ethan Cross, a savvy counter-intelligence operative, is thrust into a high-pressure scenario where leaked documents threaten national integrity. As he races against time to unmask a mole within the agency, Ethan confronts his personal fears and the boundaries of the meticulous strategies he's known for. This slow-burn thriller follows Ethan's transformation in a world where every second could spell disaster, culminating in a showdown with Lena Grey\u2014a former ally who has turned the clockwork of espionage into her personal vendetta. Through grit and cunning, Ethan must adapt his methods, realizing that in the world of espionage, the most powerful weapon is a well-timed intuition.", "characters": [ { "name": "Ethan Cross", "role": "Protagonist", "description": "A meticulous and resourceful counter-intelligence operative known for his analytical mind and calm demeanor under pressure.", "arc": "Ethan transforms from a methodical planner to a decisive action-taker as he confronts his personal fears and realizes the importance of instinct." }, { "name": "Lena Grey", "role": "Antagonist", "description": "A brilliant but disillusioned former operative now turned mole, seeking vengeance against the agency she believes wronged her.", "arc": "Lena starts with a single-minded focus on revenge but gradually becomes conflicted as old loyalties resurface." }, { "name": "Dr. Julia Ward", "role": "Supporting Character", "description": "An astute psychologist who helps Ethan manage the stress of his demanding role and assists in profiling Lena's psychological state.", "arc": "Julia grows from a secondary advisory role to a key player in helping Ethan unearth Lena's motivations." }, { "name": "Michael Garner", "role": "Supporting Character", "description": "Ethan's trusted field partner and an expert in electronic surveillance, providing vital technical support.", "arc": "Michael's experience is tested as he learns to adapt to unpredictable situations, becoming more versatile in his approach." } ], "plotPoints": { "exposition": "Ethan Cross is tasked with investigating a series of leaked documents that could compromise national security. The leaks point to an insider within the agency.", "risingAction": "As Ethan dives deeper, he uncovers a trail leading to Lena Grey, a former colleague presumed dead. Evidence mounts as Ethan closes in, forcing him to question his long-standing methodologies.", "climax": "Ethan finally confronts Lena, who has rigged a trap to destroy critical evidence. In a tense standoff, Ethan must choose between following protocol or taking a risk to stop her.", "fallingAction": "With quick thinking and a new reliance on intuition, Ethan manages to disarm the trap. Lena, deflated, questions her own motives as old memories of camaraderie surface.", "resolution": "Lena is apprehended, the mole hunt ends, and Ethan reflects on his journey, acknowledging the balance between calculated strategy and spontaneity." }, "centralConflict": "Ethan Cross must identify and capture a mole within the agency who is leaking classified information, while dealing with his own rigid attachment to protocol in a dynamically evolving threat landscape.", "setting": "The story unfolds across various global locations including the bustling intelligence hub of Langley, a remote cabin in the Swiss Alps, and the teeming streets of Berlin, lending an authentic and international scope to the narrative.", "majorTurningPoints": [ "Ethan discovers the identity of the mole as his former colleague Lena Grey.", "Lena executes a series of diversions leading to a crisis within the agency.", "Ethan's adherence to protocol nearly costs him a critical breakthrough.", "Ethan's confrontation with Lena culminates in an uncharacteristic display of intuition that saves the mission." ], "characterArcs": { "protagonistArc": "Ethan evolves from strictly adhering to procedures to embracing a balance between strategy and instinctive decision-making, essential in high-stakes situations.", "antagonistArc": "Lena's journey from spite-fueled revenge to questioning her own motivations reflects a shift from isolation to an internal struggle with her past loyalties.", "supportingCharactersArcs": [ "Julia grows from providing psychological insights to playing an active role in strategizing the final approach to Lena.", "Michael transitions from a technical support role to becoming a crucial element in executing Ethan\u2019s plans, emphasizing adaptability." ] } } d


Ngoku singaphinda sisebenzise le schema ukuvelisa izisombululo ezininzi kumbhobho oneziqinisekiso ezinamandla malunga nemimandla equlethwe yimveliso.

Ukuqukumbela

I-meta-prompting ecwangcisiweyo yenza ukuba uchaze ubume kubhabho, ukwenza iziphumo zeLLM zithembeke ngakumbi kwiinkqubo ezisezantsi. Hlala ubukele isithuba esilandelayo, apho siza kuphonononga ukudibanisa i-meta-prompting ecwangcisiweyo kunye nobunye ubuchule.